diff --git a/src/org/openbravo/module/remittance/ad_forms/CancelReturnRemittance.java b/src/org/openbravo/module/remittance/ad_forms/CancelReturnRemittance.java
index 0c35bf897084083f32f960786bcc1fb7b3f0cf39..1d9b03549a72f6df75ba564983eeb7fff05464dc 100644
--- a/src/org/openbravo/module/remittance/ad_forms/CancelReturnRemittance.java
+++ b/src/org/openbravo/module/remittance/ad_forms/CancelReturnRemittance.java
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2011-2019 Openbravo SLU
+ * All portions are Copyright (C) 2011-2023 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -79,6 +79,7 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
   public static final String STATUS_PAYMENTMADE = "PPM";
   public static final String STATUS_PAYMENTRECEIVED = "RPR";
 
+  @Override
   public void doPost(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException {
 
@@ -113,8 +114,8 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
           strRemittanceId = vars.getSessionValue("CancelReturnRemittance.remittanceid");
           vars.removeSessionValue("CancelReturnRemittance.remittanceid");
         }
-        String strBusinessPartnerId = vars
-            .getStringParameter("inpCBPartnerId", IsIDFilter.instance);
+        String strBusinessPartnerId = vars.getStringParameter("inpCBPartnerId",
+            IsIDFilter.instance);
         String strNewFilter = vars.getStringParameter("newFilter");
         String strOffset = vars.getStringParameter("offset");
         String strPageSize = vars.getStringParameter("page_size");
@@ -126,8 +127,9 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
             strDateFrom, strDateTo);
       } else {
         // When mouse over a float column in a dojo grid this action is performed automatically
-        XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
-            "org/openbravo/erpCommon/utility/DataGridTotal").createXmlDocument();
+        XmlDocument xmlDocument = xmlEngine
+            .readXmlTemplate("org/openbravo/erpCommon/utility/DataGridTotal")
+            .createXmlDocument();
         xmlDocument.setParameter("total", "0");
         response.setContentType("text/xml; charset=UTF-8");
         response.setHeader("Cache-Control", "no-cache");
@@ -164,8 +166,8 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
         myMessage.setType("Success");
         myMessage.setTitle(Utility.messageBD(this, "Success", vars.getLanguage()));
         vars.setMessage(adFormId, myMessage);
-        printPageDataSheet(response, vars, strOrganizationId, strRemittanceId,
-            strBusinessPartnerId, strDateFrom, strDateTo, strDescription);
+        printPageDataSheet(response, vars, strOrganizationId, strRemittanceId, strBusinessPartnerId,
+            strDateFrom, strDateTo, strDescription);
       } catch (Exception e) {
         log4j.error("Error in doPost: ", e);
         final String formClassName = this.getClass().getName();
@@ -176,12 +178,13 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
         myMessage.setType("Error");
         myMessage.setTitle(Utility.messageBD(this, "Error", vars.getLanguage()));
         vars.setMessage(adFormId, myMessage);
-        printPageDataSheet(response, vars, strOrganizationId, strRemittanceId,
-            strBusinessPartnerId, strDateFrom, strDateTo, strDescription);
+        printPageDataSheet(response, vars, strOrganizationId, strRemittanceId, strBusinessPartnerId,
+            strDateFrom, strDateTo, strDescription);
       }
 
-    } else
+    } else {
       pageError(response);
+    }
 
   }
 
@@ -190,8 +193,9 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
       String strDateTo, String strDescription) throws IOException, ServletException {
     log4j.debug("Output: CancelReturnRemittance");
 
-    XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
-        "org/openbravo/module/remittance/ad_forms/CancelReturnRemittance").createXmlDocument();
+    XmlDocument xmlDocument = xmlEngine
+        .readXmlTemplate("org/openbravo/module/remittance/ad_forms/CancelReturnRemittance")
+        .createXmlDocument();
 
     final String formClassName = this.getClass().getName();
     final String adFormId = getADFormInfo(formClassName).getId();
@@ -227,8 +231,8 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
     String remittanceComboHtml = FIN_Utility.getOptionsList(remittances, strRemittanceId, true);
     xmlDocument.setParameter("sectionDetailRemittance", remittanceComboHtml);
 
-    ToolBar toolbar = new ToolBar(this, vars.getLanguage(), "CancelReturnRemittance", false, "",
-        "", "", false, "ad_forms", strReplaceWith, false, true);
+    ToolBar toolbar = new ToolBar(this, vars.getLanguage(), "CancelReturnRemittance", false, "", "",
+        "", false, "ad_forms", strReplaceWith, false, true);
     toolbar.prepareSimpleToolBarTemplate();
     xmlDocument.setParameter("toolbar", toolbar.toString());
 
@@ -240,9 +244,8 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
       xmlDocument.setParameter("childTabContainer", tabs.childTabs());
       xmlDocument.setParameter("theme", vars.getTheme());
 
-      NavigationBar nav = new NavigationBar(this, vars.getLanguage(),
-          "CancelReturnRemittance.html", classInfo.id, classInfo.type, strReplaceWith,
-          tabs.breadcrumb());
+      NavigationBar nav = new NavigationBar(this, vars.getLanguage(), "CancelReturnRemittance.html",
+          classInfo.id, classInfo.type, strReplaceWith, tabs.breadcrumb());
       xmlDocument.setParameter("navigationBar", nav.toString());
       LeftTabsBar lBar = new LeftTabsBar(this, vars.getLanguage(), "CancelReturnRemittance.html",
           strReplaceWith);
@@ -280,8 +283,9 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
   private void printGridStructure(HttpServletResponse response, VariablesSecureApp vars)
       throws IOException, ServletException {
     log4j.debug("Output: print page structure");
-    XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
-        "org/openbravo/erpCommon/utility/DataGridStructure").createXmlDocument();
+    XmlDocument xmlDocument = xmlEngine
+        .readXmlTemplate("org/openbravo/erpCommon/utility/DataGridStructure")
+        .createXmlDocument();
 
     SQLReturnObject[] data = getHeaders(vars);
     String type = "Hidden";
@@ -296,8 +300,9 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
     response.setContentType("text/xml; charset=UTF-8");
     response.setHeader("Cache-Control", "no-cache");
     PrintWriter out = response.getWriter();
-    if (log4j.isDebugEnabled())
+    if (log4j.isDebugEnabled()) {
       log4j.debug(xmlDocument.print());
+    }
     out.println(xmlDocument.print());
     out.close();
   }
@@ -307,7 +312,8 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
     Vector<SQLReturnObject> vAux = new Vector<SQLReturnObject>();
     String[] colWidths = { "100", "100", "150", "350", "85", "100", "50", "0" }; // total 935
     String[] colLabels = { "REM_REMITTANCE_DOCUMENTNO", "APRM_PAYEXECMNGT_DOCUMENTNO",
-        "APRM_FATS_BPARTNER", "Description", "REM_ExpectedDate", "Amount", "SOS_CURRENCY", "rowkey" };
+        "APRM_FATS_BPARTNER", "Description", "REM_ExpectedDate", "Amount", "SOS_CURRENCY",
+        "rowkey" };
     String[] colLabelsFormat = { "string", "string", "string", "string", "string", "float",
         "string", "string" };
     for (int i = 0; i < colNames.length; i++) {
@@ -362,24 +368,25 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
         // String[] colNames = { "documentno", "businesspartner", "description", "duedate",
         // "amount", "currency", "rowkey" };
 
-        orderByColsMap.put("remittanceDocumentno", "rl." + RemittanceLine.PROPERTY_REMITTANCE + "."
-            + Remittance.PROPERTY_DOCUMENTNO);
-        orderByColsMap.put("documentno", "rl." + RemittanceLine.PROPERTY_PAYMENT + "."
-            + FIN_Payment.PROPERTY_DOCUMENTNO);
-        orderByColsMap.put("businesspartner", "rl." + RemittanceLine.PROPERTY_PAYMENT + "."
-            + FIN_Payment.PROPERTY_BUSINESSPARTNER);
-        orderByColsMap.put("description", "rl." + RemittanceLine.PROPERTY_PAYMENT + "."
-            + FIN_Payment.PROPERTY_DESCRIPTION);
-        orderByColsMap.put("duedate", "rl." + RemittanceLine.PROPERTY_PAYMENT + "."
-            + FIN_Payment.PROPERTY_PAYMENTDATE);
-        orderByColsMap.put("amount", "rl." + RemittanceLine.PROPERTY_PAYMENT + "."
-            + FIN_Payment.PROPERTY_AMOUNT);
-        orderByColsMap.put("currency", "rl." + RemittanceLine.PROPERTY_PAYMENT + "."
-            + FIN_Payment.PROPERTY_CURRENCY);
-        orderByColsMap.put("rowkey", "rl." + RemittanceLine.PROPERTY_PAYMENT + "."
-            + FIN_Payment.PROPERTY_ID);
-        for (int i = 0; i < colNames.length; i++)
+        orderByColsMap.put("remittanceDocumentno",
+            "rl." + RemittanceLine.PROPERTY_REMITTANCE + "." + Remittance.PROPERTY_DOCUMENTNO);
+        orderByColsMap.put("documentno",
+            "rl." + RemittanceLine.PROPERTY_PAYMENT + "." + FIN_Payment.PROPERTY_DOCUMENTNO);
+        orderByColsMap.put("businesspartner",
+            "rl." + RemittanceLine.PROPERTY_PAYMENT + "." + FIN_Payment.PROPERTY_BUSINESSPARTNER);
+        orderByColsMap.put("description",
+            "rl." + RemittanceLine.PROPERTY_PAYMENT + "." + FIN_Payment.PROPERTY_DESCRIPTION);
+        orderByColsMap.put("duedate",
+            "rl." + RemittanceLine.PROPERTY_PAYMENT + "." + FIN_Payment.PROPERTY_PAYMENTDATE);
+        orderByColsMap.put("amount",
+            "rl." + RemittanceLine.PROPERTY_PAYMENT + "." + FIN_Payment.PROPERTY_AMOUNT);
+        orderByColsMap.put("currency",
+            "rl." + RemittanceLine.PROPERTY_PAYMENT + "." + FIN_Payment.PROPERTY_CURRENCY);
+        orderByColsMap.put("rowkey",
+            "rl." + RemittanceLine.PROPERTY_PAYMENT + "." + FIN_Payment.PROPERTY_ID);
+        for (int i = 0; i < colNames.length; i++) {
           strOrderBy = strOrderBy.replace(colNames[i], orderByColsMap.get(colNames[i]));
+        }
 
         String[] orderByClause = strOrderBy.split(" ");
         String strOrderByProperty = orderByClause[0];
@@ -397,8 +404,8 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
                                                                          // load
           gridPayments = getRemittanceLineRowCount(
               OBDal.getInstance().get(Organization.class, strOrgId),
-              OBDal.getInstance().get(Remittance.class, strRemittanceId), strDescription, OBDal
-                  .getInstance().get(BusinessPartner.class, strBusinessPartner), strDateFrom,
+              OBDal.getInstance().get(Remittance.class, strRemittanceId), strDescription,
+              OBDal.getInstance().get(BusinessPartner.class, strBusinessPartner), strDateFrom,
               strDateTo, offset, pageSize, null, null);
           strNumRows = Integer.toString(gridPayments.size());
 
@@ -409,8 +416,8 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
 
         gridPayments = getRemittanceLineRowCount(
             OBDal.getInstance().get(Organization.class, strOrgId),
-            OBDal.getInstance().get(Remittance.class, strRemittanceId), strDescription, OBDal
-                .getInstance().get(BusinessPartner.class, strBusinessPartner), strDateFrom,
+            OBDal.getInstance().get(Remittance.class, strRemittanceId), strDescription,
+            OBDal.getInstance().get(BusinessPartner.class, strBusinessPartner), strDateFrom,
             strDateTo, offset, pageSize, strOrderByProperty, strAscDesc);
         strNumRows = Integer.toString(gridPayments != null ? gridPayments.size() : 0);
       } catch (ServletException e) {
@@ -422,10 +429,11 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
         } else {
           type = myError.getType();
           title = myError.getTitle();
-          if (!myError.getMessage().startsWith("<![CDATA["))
+          if (!myError.getMessage().startsWith("<![CDATA[")) {
             description = "<![CDATA[" + myError.getMessage() + "]]>";
-          else
+          } else {
             description = myError.getMessage();
+          }
         }
       } catch (Exception e) {
         log4j.debug("Error obtaining rows data");
@@ -439,12 +447,15 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
         log4j.error("Error in print grid data: ", e);
       }
     }
-    if (!type.startsWith("<![CDATA["))
+    if (!type.startsWith("<![CDATA[")) {
       type = "<![CDATA[" + type + "]]>";
-    if (!title.startsWith("<![CDATA["))
+    }
+    if (!title.startsWith("<![CDATA[")) {
       title = "<![CDATA[" + title + "]]>";
-    if (!description.startsWith("<![CDATA["))
+    }
+    if (!description.startsWith("<![CDATA[")) {
       description = "<![CDATA[" + description + "]]>";
+    }
     StringBuffer strRowsData = new StringBuffer();
     if (action.equalsIgnoreCase("getIdsInRange")) {
       strRowsData.append("<xml-rangeid>\n");
@@ -464,7 +475,8 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
         strRowsData.append("]]></id>\n");
       }
     } else {
-      strRowsData.append("  <rows numRows=\"").append(strNumRows)
+      strRowsData.append("  <rows numRows=\"")
+          .append(strNumRows)
           .append("\" backendPage=\"" + page + "\">\n");
       if (gridPayments != null && gridPayments.size() > 0) {
 
@@ -483,50 +495,61 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
               // "amount", "currency", "rowkey"
               String columnData = "";
               switch (k) {
-              case 0: // remittance document no
-                columnData = REM_SettleProtest.getPaymentRemittance(pay).getDocumentNo();
-                break;
-              case 1: // payment documentno
-                columnData = pay.getDocumentNo();
-                break;
-              case 2: // business partner
-                columnData = pay.getBusinessPartner() != null ? pay.getBusinessPartner()
-                    .getIdentifier() : "";
-                break;
-              case 3: // description
-                if (pay.getDescription() != null)
-                  columnData = pay.getDescription();
-                break;
-              case 4: // due date
-                columnData = Utility.formatDate(pay.getPaymentDate(), vars.getJavaDateFormat());
-                break;
-              case 5: // amount
-                columnData = numberFormat.format(pay.getAmount());
-                break;
-              case 6: // currency
-                columnData = pay.getCurrency().getISOCode();
-                break;
-              case 7: // row key
-                columnData = pay.getId().toString();
-                break;
-              default: // invalid
-                log4j.error("Invalid column");
-                break;
+                case 0: // remittance document no
+                  columnData = REM_SettleProtest.getPaymentRemittance(pay).getDocumentNo();
+                  break;
+                case 1: // payment documentno
+                  columnData = pay.getDocumentNo();
+                  break;
+                case 2: // business partner
+                  columnData = pay.getBusinessPartner() != null
+                      ? pay.getBusinessPartner().getIdentifier()
+                      : "";
+                  break;
+                case 3: // description
+                  if (pay.getDescription() != null) {
+                    columnData = pay.getDescription();
+                  }
+                  break;
+                case 4: // due date
+                  columnData = Utility.formatDate(pay.getPaymentDate(), vars.getJavaDateFormat());
+                  break;
+                case 5: // amount
+                  columnData = numberFormat.format(pay.getAmount());
+                  break;
+                case 6: // currency
+                  columnData = pay.getCurrency().getISOCode();
+                  break;
+                case 7: // row key
+                  columnData = pay.getId().toString();
+                  break;
+                default: // invalid
+                  log4j.error("Invalid column");
+                  break;
               }
 
               if (columnData != "") {
-                if (headers[k].getField("adReferenceId").equals("32"))
+                if (headers[k].getField("adReferenceId").equals("32")) {
                   strRowsData.append(strReplaceWith).append("/images/");
-                strRowsData.append(columnData.replaceAll("<b>", "").replaceAll("<B>", "")
-                    .replaceAll("</b>", "").replaceAll("</B>", "").replaceAll("<i>", "")
-                    .replaceAll("<I>", "").replaceAll("</i>", "").replaceAll("</I>", "")
-                    .replaceAll("<p>", "&nbsp;").replaceAll("<P>", "&nbsp;")
-                    .replaceAll("<br>", "&nbsp;").replaceAll("<BR>", "&nbsp;"));
+                }
+                strRowsData.append(columnData.replaceAll("<b>", "")
+                    .replaceAll("<B>", "")
+                    .replaceAll("</b>", "")
+                    .replaceAll("</B>", "")
+                    .replaceAll("<i>", "")
+                    .replaceAll("<I>", "")
+                    .replaceAll("</i>", "")
+                    .replaceAll("</I>", "")
+                    .replaceAll("<p>", "&nbsp;")
+                    .replaceAll("<P>", "&nbsp;")
+                    .replaceAll("<br>", "&nbsp;")
+                    .replaceAll("<BR>", "&nbsp;"));
               } else {
                 if (headers[k].getField("adReferenceId").equals("32")) {
                   strRowsData.append(strReplaceWith).append("/images/blank.gif");
-                } else
+                } else {
                   strRowsData.append("&nbsp;");
+                }
               }
               strRowsData.append("]]></td>\n");
             }
@@ -546,8 +569,9 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
     response.setContentType("text/xml; charset=UTF-8");
     response.setHeader("Cache-Control", "no-cache");
     PrintWriter out = response.getWriter();
-    if (log4j.isDebugEnabled())
+    if (log4j.isDebugEnabled()) {
       log4j.debug(strRowsData.toString());
+    }
     out.print(strRowsData.toString());
     out.close();
   }
@@ -579,23 +603,23 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
   private List<Remittance> getOpenRemittances(String strOrganizationId) {
     OBContext.setAdminMode();
     try {
-      final StringBuilder whereClause = new StringBuilder();
-
-      whereClause.append(" as rl ");
-      whereClause.append(" where rl.remittance.processed = " + Boolean.TRUE);
-      whereClause.append(" and not exists ");
-      whereClause
-          .append(" (select 1 from REM_RemittanceLineCancel rlc where rlc.payment.id = rl.payment.id and rlc.remittance.id = rl.remittance.id)");
-      whereClause.append(" and not exists ");
-      whereClause
-          .append(" (select 1 from REM_RemittanceLineReturn rlr where rlr.payment.id = rl.payment.id and rlr.remittance.id = rl.remittance.id)");
-      whereClause.append(" and rl.organization.id in (");
-      whereClause.append(Utility.getInStrSet(OBContext.getOBContext()
-          .getOrganizationStructureProvider().getChildTree(strOrganizationId, true)));
-      whereClause.append(") ");
-      whereClause.append("order by rl.remittance.documentNo");
-      final OBQuery<RemittanceLine> obqRemLine = OBDal.getInstance().createQuery(
-          RemittanceLine.class, whereClause.toString());
+      // @formatter:off
+      String whereClause = ""
+          + " as rl "
+          + " where rl.remittance.processed = true"
+          + " and not exists "
+          + " (select 1 from REM_RemittanceLineCancel rlc where rlc.payment.id = rl.payment.id and rlc.remittance.id = rl.remittance.id)"
+          + " and not exists "
+          + " (select 1 from REM_RemittanceLineReturn rlr where rlr.payment.id = rl.payment.id and rlr.remittance.id = rl.remittance.id)"
+          + " and rl.organization.id in :orgsIds"
+          + " order by rl.remittance.documentNo";
+      // @formatter:on
+      final OBQuery<RemittanceLine> obqRemLine = OBDal.getInstance()
+          .createQuery(RemittanceLine.class, whereClause);
+      obqRemLine.setNamedParameter("orgIds",
+          OBContext.getOBContext()
+              .getOrganizationStructureProvider()
+              .getChildTree(strOrganizationId, true));
       obqRemLine.setFilterOnReadableClients(false);
       obqRemLine.setFilterOnReadableOrganization(false);
       List<Remittance> remittances = new ArrayList<Remittance>();
@@ -641,7 +665,8 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
     }
     List<FIN_Payment> payments = new ArrayList<FIN_Payment>();
     for (RemittanceLine remittanceLine : getRemittanceLine(organization, remittance, description,
-        businessPartner, strDateFrom, strDateTo, offset, pageSize, strOrderByProperty, strAscDesc)) {
+        businessPartner, strDateFrom, strDateTo, offset, pageSize, strOrderByProperty,
+        strAscDesc)) {
       if (!payments.contains(remittanceLine.getPayment())) {
         payments.add(remittanceLine.getPayment());
       }
@@ -677,74 +702,73 @@ public class CancelReturnRemittance extends HttpSecureAppServlet {
     Date dateto = FIN_Utility.getDate(strDateTo);
     try {
       OBContext.setAdminMode();
-      final StringBuilder whereClause = new StringBuilder();
       final Map<String, Object> parameters = new HashMap<>();
 
-      whereClause.append(" as rl ");
-      whereClause.append(" where rl.remittance.processed = " + Boolean.TRUE);
+      // @formatter:off
+      String whereClause = ""
+          + " as rl "
+          + " where rl.remittance.processed = true";
       if (remittance != null) {
-        whereClause.append(" and rl.remittance.id = '");
-        whereClause.append(remittance.getId());
-        whereClause.append("'");
+        whereClause += " and rl.remittance.id = :remittanceId";
+        parameters.put("remittanceId", remittance.getId());
       }
-      whereClause.append(" and not exists ");
       whereClause
-          .append(" (select 1 from REM_RemittanceLineCancel rlc where rlc.payment.id = rl.payment.id ");
+          += " and not exists "
+          +  " (select 1 from REM_RemittanceLineCancel rlc where rlc.payment.id = rl.payment.id ";
       if (remittance != null) {
-        whereClause.append(" and rlc.remittance.id = '");
-        whereClause.append(remittance.getId());
-        whereClause.append("'");
+        whereClause += " and rlc.remittance.id = :remittanceId";
+        // param is already added above
       } else {
-        whereClause.append(" and rlc.remittance.id = rl.remittance.id ");
+        whereClause += " and rlc.remittance.id = rl.remittance.id ";
       }
-      whereClause.append(") ");
-      whereClause.append(" and not exists ");
       whereClause
-          .append(" (select 1 from REM_RemittanceLineReturn rlr where rlr.payment.id = rl.payment.id ");
+          += ") "
+          +  " and not exists "
+          +  " (select 1 from REM_RemittanceLineReturn rlr where rlr.payment.id = rl.payment.id ";
       if (remittance != null) {
-        whereClause.append(" and rlr.remittance.id = '");
-        whereClause.append(remittance.getId());
-        whereClause.append("'");
+        whereClause += " and rlr.remittance.id = :remittanceId";
+        // param is already added above
       } else {
-        whereClause.append(" and rlr.remittance.id = rl.remittance.id ");
+        whereClause += " and rlr.remittance.id = rl.remittance.id ";
       }
-      whereClause.append(") ");
+      whereClause += ") ";
       if (description != null && !"".equals(description)) {
-        whereClause.append("and rl.payment.description like :description");
+        whereClause += "and rl.payment.description like :description ";
         parameters.put("description", "%" + description + "%");
       }
       if (businessPartner != null) {
-        whereClause.append("and rl.payment.businessPartner.id = '");
-        whereClause.append(businessPartner.getId());
-        whereClause.append("' ");
+        whereClause += "and rl.payment.businessPartner.id = :businessPartnerId ";
+        parameters.put("businessPartnerId", businessPartner.getId());
       }
       if (!"".equals(strDateFrom)) {
-        whereClause.append("and rl.payment.paymentDate >= :dateFrom ");
+        whereClause += "and rl.payment.paymentDate >= :dateFrom ";
         parameters.put("dateFrom", datefrom);
       }
       if (!"".equals(strDateTo)) {
-        whereClause.append("and rl.payment.paymentDate <= :dateTo ");
+        whereClause += "and rl.payment.paymentDate <= :dateTo ";
         parameters.put("dateTo", dateto);
       }
       if (businessPartner != null) {
-        whereClause.append("and rl.payment.businessPartner.id = '");
-        whereClause.append(businessPartner.getId());
-        whereClause.append("' ");
+        whereClause += "and rl.payment.businessPartner.id = :businessPartnerId ";
+        // param is already added above
       }
-      whereClause.append("and rl.payment.organization.id in (");
-      whereClause.append(Utility.getInStrSet(OBContext.getOBContext()
-          .getOrganizationStructureProvider().getChildTree(organization.getId(), true)));
-      whereClause.append(") ");
+      whereClause += "and rl.payment.organization.id in :orgIds ";
+      parameters.put("orgIds", OBContext.getOBContext()
+          .getOrganizationStructureProvider()
+          .getChildTree(organization.getId(), true));
       if (strOrderByProperty != null && !strOrderByProperty.isEmpty()) {
-        whereClause.append("order by ");
-        whereClause.append(strOrderByProperty);
-        whereClause.append(" ");
+        whereClause
+            += "order by "
+            +  strOrderByProperty
+            +  " ";
+      }
+      if (strAscDesc != null && !strAscDesc.isEmpty()) {
+        whereClause += strAscDesc;
       }
-      if (strAscDesc != null && !strAscDesc.isEmpty())
-        whereClause.append(strAscDesc);
+      // @formatter:off
 
-      final OBQuery<RemittanceLine> obqP = OBDal.getInstance().createQuery(RemittanceLine.class,
-          whereClause.toString());
+      final OBQuery<RemittanceLine> obqP = OBDal.getInstance()
+          .createQuery(RemittanceLine.class, whereClause);
       obqP.setNamedParameters(parameters);
       obqP.setFilterOnReadableOrganization(false);
 
diff --git a/src/org/openbravo/module/remittance/ad_forms/DocREMRemittance.java b/src/org/openbravo/module/remittance/ad_forms/DocREMRemittance.java
index d0dbb25e60ea3364e8aff0ee7232bc0f0be0c1ba..6b072fb605ac31e4d29d7a20c0881eb9dbbc5650 100644
--- a/src/org/openbravo/module/remittance/ad_forms/DocREMRemittance.java
+++ b/src/org/openbravo/module/remittance/ad_forms/DocREMRemittance.java
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2011-2020 Openbravo SLU
+ * All portions are Copyright (C) 2011-2023 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -275,16 +275,18 @@ public class DocREMRemittance extends AcctServer {
 
   private String getRemittanceLineFromPaymentDetail(final FIN_PaymentDetail detail,
       Remittance remittance) {
-    StringBuilder hql = new StringBuilder();
-    hql.append(" select remline.id ");
-    hql.append(" from REM_RemittanceLine remline");
-    hql.append(" where remline.paymentScheduleDetail.paymentDetails.id is not null");
-    hql.append(" and remline.paymentScheduleDetail.paymentDetails.id = :paymentDetailsId");
-    hql.append(" and remline.remittance.id = :remittanceId");
+    // @formatter:off
+    String hql = ""
+        + " select remline.id "
+        + " from REM_RemittanceLine remline"
+        + " where remline.paymentScheduleDetail.paymentDetails.id is not null"
+        + " and remline.paymentScheduleDetail.paymentDetails.id = :paymentDetailsId"
+        + " and remline.remittance.id = :remittanceId";
+    // @formatter:on
 
     Query<String> remitanceLineQuery = OBDal.getInstance()
         .getSession()
-        .createQuery(hql.toString(), String.class);
+        .createQuery(hql, String.class);
     remitanceLineQuery.setParameter("paymentDetailsId", detail.getId());
     remitanceLineQuery.setParameter("remittanceId", remittance.getId());
 
@@ -331,19 +333,24 @@ public class DocREMRemittance extends AcctServer {
       VariablesSecureApp vars) throws ServletException {
     // Select specific definition
     String strClassname = "";
-    final StringBuilder whereClause = new StringBuilder();
+    String whereClause = "";
     Fact fact = new Fact(this, as, Fact.POST_Actual);
     String Fact_Acct_Group_ID = SequenceIdData.getUUID();
     OBContext.setAdminMode();
     try {
-      whereClause.append(" as astdt ");
-      whereClause.append(
-          " where astdt.acctschemaTable.accountingSchema.id = '" + as.m_C_AcctSchema_ID + "'");
-      whereClause.append(" and astdt.acctschemaTable.table.id = '" + AD_Table_ID + "'");
-      whereClause.append(" and astdt.documentCategory = '" + DocumentType + "'");
+      // @formatter:off
+      whereClause
+          += " as astdt "
+          +  " where astdt.acctschemaTable.accountingSchema.id = :acctSchemaId"
+          +  " and astdt.acctschemaTable.table.id = :tableId"
+          +  " and astdt.documentCategory = :docType";
+      // @formatter:on
 
       final OBQuery<AcctSchemaTableDocType> obqParameters = OBDal.getInstance()
-          .createQuery(AcctSchemaTableDocType.class, whereClause.toString());
+          .createQuery(AcctSchemaTableDocType.class, whereClause);
+      obqParameters.setNamedParameter("acctSchemaId", as.m_C_AcctSchema_ID);
+      obqParameters.setNamedParameter("tableId", AD_Table_ID);
+      obqParameters.setNamedParameter("docType", DocumentType);
       final List<AcctSchemaTableDocType> acctSchemaTableDocTypes = obqParameters.list();
 
       if (acctSchemaTableDocTypes != null && acctSchemaTableDocTypes.size() > 0) {
@@ -351,14 +358,17 @@ public class DocREMRemittance extends AcctServer {
       }
 
       if (strClassname.equals("")) {
-        final StringBuilder whereClause2 = new StringBuilder();
-
-        whereClause2.append(" as ast ");
-        whereClause2.append(" where ast.accountingSchema.id = '" + as.m_C_AcctSchema_ID + "'");
-        whereClause2.append(" and ast.table.id = '" + AD_Table_ID + "'");
+        // @formatter:off
+        String whereClause2 = ""
+            + " as ast "
+            + " where ast.accountingSchema.id = :acctSchemaId"
+            + " and ast.table.id = :tableId";
+        // @formatter:on
 
         final OBQuery<AcctSchemaTable> obqParameters2 = OBDal.getInstance()
-            .createQuery(AcctSchemaTable.class, whereClause2.toString());
+            .createQuery(AcctSchemaTable.class, whereClause2);
+        obqParameters2.setNamedParameter("acctSchemaId", as.m_C_AcctSchema_ID);
+        obqParameters2.setNamedParameter("tableId", AD_Table_ID);
         final List<AcctSchemaTable> acctSchemaTables = obqParameters2.list();
         if (acctSchemaTables != null && acctSchemaTables.size() > 0
             && acctSchemaTables.get(0).getCreatefactTemplate() != null) {
@@ -734,13 +744,15 @@ public class DocREMRemittance extends AcctServer {
       Set<FIN_Payment> usedPayments = new HashSet<FIN_Payment>();
       for (RemittanceLine line : remittance.getREMRemittanceLineList()) {
         if (!usedPayments.contains(line.getPayment())) {
-          StringBuilder where = new StringBuilder();
-          where.append(" select sum(pd." + FIN_PaymentDetail.PROPERTY_AMOUNT + ")");
-          where.append(" from " + FIN_PaymentDetail.ENTITY_NAME + " as pd");
-          where.append(" where pd." + FIN_PaymentDetail.PROPERTY_FINPAYMENT + ".id = :paymentId");
+          // @formatter:off
+          String where = ""
+              + " select sum(pd.amount)"
+              + " from FIN_Payment_Detail as pd"
+              + " where pd.finPayment.id = :paymentId";
+          // @formatter:on
           Query<BigDecimal> qry = OBDal.getInstance()
               .getSession()
-              .createQuery(where.toString(), BigDecimal.class);
+              .createQuery(where, BigDecimal.class);
           qry.setParameter("paymentId", line.getPayment().getId());
           BigDecimal paymentAmt = qry.uniqueResult();
           amount = amount.add(line.getPayment().isReceipt() ? paymentAmt : paymentAmt.negate());
diff --git a/src/org/openbravo/module/remittance/ad_forms/DocREMRemittanceCancel.java b/src/org/openbravo/module/remittance/ad_forms/DocREMRemittanceCancel.java
index 39720699111c7660774ee1d289c0952feafc9f75..c4b79ceb1df0c5c43aae70f2736d467a8f8a82d9 100644
--- a/src/org/openbravo/module/remittance/ad_forms/DocREMRemittanceCancel.java
+++ b/src/org/openbravo/module/remittance/ad_forms/DocREMRemittanceCancel.java
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2011-2020 Openbravo SLU
+ * All portions are Copyright (C) 2011-2023 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -100,19 +100,23 @@ public class DocREMRemittanceCancel extends AcctServer {
       VariablesSecureApp vars) throws ServletException {
     // Select specific definition
     String strClassname = "";
-    final StringBuilder whereClause = new StringBuilder();
     Fact fact = new Fact(this, as, Fact.POST_Actual);
     String Fact_Acct_Group_ID = SequenceIdData.getUUID();
     OBContext.setAdminMode();
     try {
-      whereClause.append(" as astdt ");
-      whereClause.append(
-          " where astdt.acctschemaTable.accountingSchema.id = '" + as.m_C_AcctSchema_ID + "'");
-      whereClause.append(" and astdt.acctschemaTable.table.id = '" + AD_Table_ID + "'");
-      whereClause.append(" and astdt.documentCategory = '" + DocumentType + "'");
+      // @formatter:off
+      String whereClause = ""
+          + " as astdt "
+          + " where astdt.acctschemaTable.accountingSchema.id = :acctSchemaId"
+          + " and astdt.acctschemaTable.table.id = :tableId"
+          + " and astdt.documentCategory = :docType";
+      // @formatter:on
 
       final OBQuery<AcctSchemaTableDocType> obqParameters = OBDal.getInstance()
-          .createQuery(AcctSchemaTableDocType.class, whereClause.toString());
+          .createQuery(AcctSchemaTableDocType.class, whereClause);
+      obqParameters.setNamedParameter("acctSchemaId", as.m_C_AcctSchema_ID);
+      obqParameters.setNamedParameter("tableId", AD_Table_ID);
+      obqParameters.setNamedParameter("docType", DocumentType);
       final List<AcctSchemaTableDocType> acctSchemaTableDocTypes = obqParameters.list();
 
       if (acctSchemaTableDocTypes != null && acctSchemaTableDocTypes.size() > 0) {
@@ -120,14 +124,17 @@ public class DocREMRemittanceCancel extends AcctServer {
       }
 
       if (strClassname.equals("")) {
-        final StringBuilder whereClause2 = new StringBuilder();
-
-        whereClause2.append(" as ast ");
-        whereClause2.append(" where ast.accountingSchema.id = '" + as.m_C_AcctSchema_ID + "'");
-        whereClause2.append(" and ast.table.id = '" + AD_Table_ID + "'");
+        // @formatter:off
+        String whereClause2 = ""
+            + " as ast "
+            + " where ast.accountingSchema.id = :acctSchemaId"
+            + " and ast.table.id = :tableId";
+        // @formatter:on
 
         final OBQuery<AcctSchemaTable> obqParameters2 = OBDal.getInstance()
-            .createQuery(AcctSchemaTable.class, whereClause2.toString());
+            .createQuery(AcctSchemaTable.class, whereClause2);
+        obqParameters.setNamedParameter("acctSchemaId", as.m_C_AcctSchema_ID);
+        obqParameters.setNamedParameter("tableId", AD_Table_ID);
         final List<AcctSchemaTable> acctSchemaTables = obqParameters2.list();
         if (acctSchemaTables != null && acctSchemaTables.size() > 0
             && acctSchemaTables.get(0).getCreatefactTemplate() != null) {
diff --git a/src/org/openbravo/module/remittance/ad_forms/DocREMRemittanceReturn.java b/src/org/openbravo/module/remittance/ad_forms/DocREMRemittanceReturn.java
index b120259a0e58fd94db69e67de71c5d439be8588f..7729a982da5a4c5e3d4d758873cd6a64e68f47a3 100644
--- a/src/org/openbravo/module/remittance/ad_forms/DocREMRemittanceReturn.java
+++ b/src/org/openbravo/module/remittance/ad_forms/DocREMRemittanceReturn.java
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2011-2020 Openbravo SLU
+ * All portions are Copyright (C) 2011-2023 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -226,19 +226,23 @@ public class DocREMRemittanceReturn extends AcctServer {
       VariablesSecureApp vars) throws ServletException {
     // Select specific definition
     String strClassname = "";
-    final StringBuilder whereClause = new StringBuilder();
     Fact fact = new Fact(this, as, Fact.POST_Actual);
     String Fact_Acct_Group_ID = SequenceIdData.getUUID();
     OBContext.setAdminMode();
     try {
-      whereClause.append(" as astdt ");
-      whereClause.append(
-          " where astdt.acctschemaTable.accountingSchema.id = '" + as.m_C_AcctSchema_ID + "'");
-      whereClause.append(" and astdt.acctschemaTable.table.id = '" + AD_Table_ID + "'");
-      whereClause.append(" and astdt.documentCategory = '" + DocumentType + "'");
+      // @formatter:off
+      String whereClause = ""
+          + " as astdt "
+          + " where astdt.acctschemaTable.accountingSchema.id = :acctSchemaId"
+          + " and astdt.acctschemaTable.table.id = :tableId"
+          + " and astdt.documentCategory = :docType";
+      // @formatter:on
 
       final OBQuery<AcctSchemaTableDocType> obqParameters = OBDal.getInstance()
-          .createQuery(AcctSchemaTableDocType.class, whereClause.toString());
+          .createQuery(AcctSchemaTableDocType.class, whereClause);
+      obqParameters.setNamedParameter("acctSchemaId", as.m_C_AcctSchema_ID);
+      obqParameters.setNamedParameter("tableId", AD_Table_ID);
+      obqParameters.setNamedParameter("docType", DocumentType);
       final List<AcctSchemaTableDocType> acctSchemaTableDocTypes = obqParameters.list();
 
       if (acctSchemaTableDocTypes != null && acctSchemaTableDocTypes.size() > 0) {
@@ -246,14 +250,17 @@ public class DocREMRemittanceReturn extends AcctServer {
       }
 
       if (strClassname.equals("")) {
-        final StringBuilder whereClause2 = new StringBuilder();
-
-        whereClause2.append(" as ast ");
-        whereClause2.append(" where ast.accountingSchema.id = '" + as.m_C_AcctSchema_ID + "'");
-        whereClause2.append(" and ast.table.id = '" + AD_Table_ID + "'");
+        // @formatter:off
+        String whereClause2 = ""
+            + " as ast "
+            + " where ast.accountingSchema.id = :acctSchemaId"
+            + " and ast.table.id = :tableId";
+        // @formatter:on
 
         final OBQuery<AcctSchemaTable> obqParameters2 = OBDal.getInstance()
-            .createQuery(AcctSchemaTable.class, whereClause2.toString());
+            .createQuery(AcctSchemaTable.class, whereClause2);
+        obqParameters.setNamedParameter("acctSchemaId", as.m_C_AcctSchema_ID);
+        obqParameters.setNamedParameter("tableId", AD_Table_ID);
         final List<AcctSchemaTable> acctSchemaTables = obqParameters2.list();
         if (acctSchemaTables != null && acctSchemaTables.size() > 0
             && acctSchemaTables.get(0).getCreatefactTemplate() != null) {
diff --git a/src/org/openbravo/module/remittance/event/PaymentEventHandler.java b/src/org/openbravo/module/remittance/event/PaymentEventHandler.java
index 58e1d96d0b3eb63bc47101f0712055a1a3b1ea44..0830edc234127c0ad69ea9620933545e07922615 100644
--- a/src/org/openbravo/module/remittance/event/PaymentEventHandler.java
+++ b/src/org/openbravo/module/remittance/event/PaymentEventHandler.java
@@ -43,14 +43,17 @@ public class PaymentEventHandler extends EntityPersistenceEventObserver {
 
     if ((!"RPAP".equalsIgnoreCase(oldStatus) && "RPAP".equalsIgnoreCase(newStatus))
         && (newProcessed == false)) {
-      StringBuilder hql = new StringBuilder();
-      hql.append("select 1 ");
-      hql.append(" from REM_RemittanceLine ");
-      hql.append(" where payment = '").append(payment.getId()).append("'");
+      // @formatter:off
+      String hql = ""
+          + "select 1 "
+          + " from REM_RemittanceLine "
+          + " where payment = :id";
+      // @formatter:on
 
       final Session session = OBDal.getInstance().getSession();
       @SuppressWarnings("rawtypes")
-      final Query query = session.createQuery(hql.toString());
+      final Query query = session.createQuery(hql);
+      query.setParameter("id", payment.getId());
 
       if (query.list().size() > 0) {
         String language = OBContext.getOBContext().getLanguage().getLanguage();
diff --git a/src/org/openbravo/module/remittance/hooks/REMModifyPaymentPlanHook.java b/src/org/openbravo/module/remittance/hooks/REMModifyPaymentPlanHook.java
index 7d73d2801b7646a1ef92f1c891fc2a9570e26689..773bc28b8f8ff3f7b626a1ad999ed9947ab7eb81 100644
--- a/src/org/openbravo/module/remittance/hooks/REMModifyPaymentPlanHook.java
+++ b/src/org/openbravo/module/remittance/hooks/REMModifyPaymentPlanHook.java
@@ -1,70 +1,71 @@
-/*
- *************************************************************************
- * The contents of this file are subject to the Openbravo  Public  License
- * Version  1.0  (the  "License"),  being   the  Mozilla   Public  License
- * Version 1.1  with a permitted attribution clause; you may not  use this
- * file except in compliance with the License. You  may  obtain  a copy of
- * the License at http://www.openbravo.com/legal/license.html
- * Software distributed under the License  is  distributed  on  an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
- * License for the specific  language  governing  rights  and  limitations
- * under the License.
- * The Original Code is Openbravo ERP.
- * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2018 Openbravo SLU
- * All Rights Reserved.
- * Contributor(s):  ______________________________________.
- *************************************************************************
- */
-
-package org.openbravo.module.remittance.hooks;
-
-import java.util.List;
-
-import javax.enterprise.context.ApplicationScoped;
-
-import org.openbravo.advpaymentmngt.ModifyPaymentPlanHook;
-import org.openbravo.base.exception.OBException;
-import org.openbravo.dal.service.OBDal;
-import org.openbravo.dal.service.OBQuery;
-import org.openbravo.model.financialmgmt.payment.FIN_PaymentSchedule;
-import org.openbravo.module.remittance.RemittanceLine;
-
-/**
- * Modified Payment Plan hook implementation for Remittance module
- * 
- * It validates that it is not possible to change the due date of a Payment Schedule Detail to a
- * date after the expected date when this Payment Schedule Detail is already included in a
- * Remittance (or has a Payment included in a Remittance)
- */
-@ApplicationScoped
-public class REMModifyPaymentPlanHook extends ModifyPaymentPlanHook {
-
-  @Override
-  public void validatePaymentSchedule(List<FIN_PaymentSchedule> modifiedPaymentSchedule) {
-    for (FIN_PaymentSchedule psd : modifiedPaymentSchedule) {
-      if (isIncludedInARemmitance(psd)) {
-        throw new OBException("APRM_remline_finpayschdet");
-      }
-    }
-  }
-
-  private boolean isIncludedInARemmitance(FIN_PaymentSchedule psd) {
-    StringBuilder hql = new StringBuilder();
-    hql.append(" payment.id in (select finPayment.id ");
-    hql.append("                  from FIN_Payment_Detail pd ");
-    hql.append("                  where pd.id in (select psd.paymentDetails.id ");
-    hql.append("                                  from FIN_Payment_ScheduleDetail psd ");
-    hql.append("                                  where psd.invoicePaymentSchedule.id = :paymentScheduleId and canceled = false) ) ");
-    hql.append(" or paymentScheduleDetail.id in (select psd.id ");
-    hql.append("                                   from FIN_Payment_ScheduleDetail psd ");
-    hql.append("                                   where psd.invoicePaymentSchedule.id = :paymentScheduleId and canceled = false) ");
-
-    OBQuery<RemittanceLine> query = OBDal.getInstance().createQuery(RemittanceLine.class,
-        hql.toString());
-    query.setNamedParameter("paymentScheduleId", psd.getId());
-    query.setMaxResult(1);
-    return query.uniqueResult() != null;
-  }
-
-}
+/*
+ *************************************************************************
+ * The contents of this file are subject to the Openbravo  Public  License
+ * Version  1.0  (the  "License"),  being   the  Mozilla   Public  License
+ * Version 1.1  with a permitted attribution clause; you may not  use this
+ * file except in compliance with the License. You  may  obtain  a copy of
+ * the License at http://www.openbravo.com/legal/license.html
+ * Software distributed under the License  is  distributed  on  an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ * License for the specific  language  governing  rights  and  limitations
+ * under the License.
+ * The Original Code is Openbravo ERP.
+ * The Initial Developer of the Original Code is Openbravo SLU
+ * All portions are Copyright (C) 2018-2023 Openbravo SLU
+ * All Rights Reserved.
+ * Contributor(s):  ______________________________________.
+ *************************************************************************
+ */
+
+package org.openbravo.module.remittance.hooks;
+
+import java.util.List;
+
+import javax.enterprise.context.ApplicationScoped;
+
+import org.openbravo.advpaymentmngt.ModifyPaymentPlanHook;
+import org.openbravo.base.exception.OBException;
+import org.openbravo.dal.service.OBDal;
+import org.openbravo.dal.service.OBQuery;
+import org.openbravo.model.financialmgmt.payment.FIN_PaymentSchedule;
+import org.openbravo.module.remittance.RemittanceLine;
+
+/**
+ * Modified Payment Plan hook implementation for Remittance module
+ * 
+ * It validates that it is not possible to change the due date of a Payment Schedule Detail to a
+ * date after the expected date when this Payment Schedule Detail is already included in a
+ * Remittance (or has a Payment included in a Remittance)
+ */
+@ApplicationScoped
+public class REMModifyPaymentPlanHook extends ModifyPaymentPlanHook {
+
+  @Override
+  public void validatePaymentSchedule(List<FIN_PaymentSchedule> modifiedPaymentSchedule) {
+    for (FIN_PaymentSchedule psd : modifiedPaymentSchedule) {
+      if (isIncludedInARemmitance(psd)) {
+        throw new OBException("APRM_remline_finpayschdet");
+      }
+    }
+  }
+
+  private boolean isIncludedInARemmitance(FIN_PaymentSchedule psd) {
+    // @formatter:off
+    String hql = ""
+        + " payment.id in (select finPayment.id "
+        + "                  from FIN_Payment_Detail pd "
+        + "                  where pd.id in (select psd.paymentDetails.id "
+        + "                                  from FIN_Payment_ScheduleDetail psd "
+        + "                                  where psd.invoicePaymentSchedule.id = :paymentScheduleId and canceled = false) ) "
+        + " or paymentScheduleDetail.id in (select psd.id "
+        + "                                   from FIN_Payment_ScheduleDetail psd "
+        + "                                   where psd.invoicePaymentSchedule.id = :paymentScheduleId and canceled = false) ";
+    // @formatter:on
+
+    OBQuery<RemittanceLine> query = OBDal.getInstance().createQuery(RemittanceLine.class, hql);
+    query.setNamedParameter("paymentScheduleId", psd.getId());
+    query.setMaxResult(1);
+    return query.uniqueResult() != null;
+  }
+
+}
diff --git a/src/org/openbravo/module/remittance/process/REM_AddRemittance.java b/src/org/openbravo/module/remittance/process/REM_AddRemittance.java
index 68f4db99f47743a751b17b6c5b9ac08d159abb83..86207e4648796548d2ca8fbe3ca1ad62b4a3e40e 100644
--- a/src/org/openbravo/module/remittance/process/REM_AddRemittance.java
+++ b/src/org/openbravo/module/remittance/process/REM_AddRemittance.java
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2013-2018 Openbravo SLU
+ * All portions are Copyright (C) 2013-2023 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -45,18 +45,14 @@ import org.openbravo.dal.service.OBQuery;
 import org.openbravo.data.FieldProvider;
 import org.openbravo.erpCommon.utility.FieldProviderFactory;
 import org.openbravo.erpCommon.utility.Utility;
-import org.openbravo.model.common.businesspartner.BusinessPartner;
 import org.openbravo.model.common.currency.Currency;
 import org.openbravo.model.common.enterprise.DocumentType;
 import org.openbravo.model.common.enterprise.Organization;
-import org.openbravo.model.common.invoice.Invoice;
 import org.openbravo.model.financialmgmt.gl.GLItem;
 import org.openbravo.model.financialmgmt.payment.FIN_Payment;
 import org.openbravo.model.financialmgmt.payment.FIN_PaymentMethod;
 import org.openbravo.model.financialmgmt.payment.FIN_PaymentPropDetail;
-import org.openbravo.model.financialmgmt.payment.FIN_PaymentSchedule;
 import org.openbravo.model.financialmgmt.payment.FIN_PaymentScheduleDetail;
-import org.openbravo.model.financialmgmt.payment.PaymentPriority;
 import org.openbravo.module.remittance.Remittance;
 import org.openbravo.module.remittance.RemittanceLine;
 import org.openbravo.module.remittance.RemittanceLineCancel;
@@ -73,14 +69,16 @@ public class REM_AddRemittance {
           payment.getPaymentMethod()));
       rem.add(Restrictions.eq(Remittance.PROPERTY_FINANCIALACCOUNT, payment.getAccount()));
       rem.add(Restrictions.eq(Remittance.PROPERTY_PROCESSED, false));
-      rem.add(Restrictions.in("organization.id", OBContext.getOBContext()
-          .getOrganizationStructureProvider()
-          .getParentTree(payment.getOrganization().getId(), true)));
+      rem.add(Restrictions.in("organization.id",
+          OBContext.getOBContext()
+              .getOrganizationStructureProvider()
+              .getParentTree(payment.getOrganization().getId(), true)));
       List<Remittance> openRemittances = rem.list();
       if (openRemittances.size() > 0) {
         return openRemittances.get(0);
-      } else
+      } else {
         return newRemmitance(payment);
+      }
     } finally {
       OBContext.restorePreviousMode();
     }
@@ -127,13 +125,16 @@ public class REM_AddRemittance {
     try {
       OBCriteria<RemittanceType> rt = OBDal.getInstance().createCriteria(RemittanceType.class);
       rt.add(Restrictions.eq(RemittanceType.PROPERTY_PAYMENTMETHOD, payment.getPaymentMethod()));
-      rt.add(Restrictions.in("organization.id", OBContext.getOBContext()
-          .getOrganizationStructureProvider().getNaturalTree(payment.getOrganization().getId())));
+      rt.add(Restrictions.in("organization.id",
+          OBContext.getOBContext()
+              .getOrganizationStructureProvider()
+              .getNaturalTree(payment.getOrganization().getId())));
       List<RemittanceType> remittanceTypes = rt.list();
       if (remittanceTypes.size() > 0) {
         remittanceType = remittanceTypes.get(0);
-      } else
+      } else {
         return null;
+      }
     } finally {
       OBContext.restorePreviousMode();
     }
@@ -149,10 +150,11 @@ public class REM_AddRemittance {
       rl.setMaxResults(1);
       List<RemittanceLine> remittanceLines = rl.list();
       if (remittanceLines.size() > 0) {
-        return (remittanceLines.get(0).getLineNo() == null) ? 10l : remittanceLines.get(0)
-            .getLineNo() + 10l;
-      } else
+        return (remittanceLines.get(0).getLineNo() == null) ? 10l
+            : remittanceLines.get(0).getLineNo() + 10l;
+      } else {
         return 10l;
+      }
     } finally {
       OBContext.restorePreviousMode();
     }
@@ -211,7 +213,8 @@ public class REM_AddRemittance {
 
     // FieldProvider[] data = new FieldProviderFactory[selectedScheduledPayments.size()];
     FieldProvider[] data = FieldProviderFactory.getFieldProviderArray(shownScheduledPaymentDetails);
-    String dateFormat = OBPropertiesProvider.getInstance().getOpenbravoProperties()
+    String dateFormat = OBPropertiesProvider.getInstance()
+        .getOpenbravoProperties()
         .getProperty("dateFormat.java");
     SimpleDateFormat dateFormater = new SimpleDateFormat(dateFormat);
     // FIXME: added to access the FIN_PaymentSchedule and FIN_PaymentScheduleDetail tables to be
@@ -254,159 +257,191 @@ public class REM_AddRemittance {
                   psdIdSet);
               if (idsAmounts.get(selectedId).compareTo(BigDecimal.ZERO) != 0) {
                 FieldProviderFactory.setField(data[i], "finSelectedPaymentDetailId", selectedId);
-                FieldProviderFactory.setField(data[i], "paymentAmount", idsAmounts.get(selectedId)
-                    .toString());
+                FieldProviderFactory.setField(data[i], "paymentAmount",
+                    idsAmounts.get(selectedId).toString());
               }
             }
           }
         }
         FieldProviderFactory.setField(data[i], "finScheduledPaymentDetailId",
             FIN_PaymentScheduleDetails[i].getId());
-        if (FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule() != null)
+        if (FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule() != null) {
           FieldProviderFactory.setField(data[i], "orderPaymentScheduleId",
               FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule().getId());
-        else
+        } else {
           FieldProviderFactory.setField(data[i], "orderPaymentScheduleId", "");
-        if (FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule() != null)
-          FieldProviderFactory.setField(data[i], "orderNr", FIN_PaymentScheduleDetails[i]
-              .getOrderPaymentSchedule().getOrder().getDocumentNo());
-        else
+        }
+        if (FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule() != null) {
+          FieldProviderFactory.setField(data[i], "orderNr",
+              FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule().getOrder().getDocumentNo());
+        } else {
           FieldProviderFactory.setField(data[i], "orderNr", "");
-        if (FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule() != null)
-          FieldProviderFactory.setField(data[i], "invoiceNr", FIN_PaymentScheduleDetails[i]
-              .getInvoicePaymentSchedule().getInvoice().getDocumentNo());
-        else
+        }
+        if (FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule() != null) {
+          FieldProviderFactory.setField(data[i], "invoiceNr",
+              FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule()
+                  .getInvoice()
+                  .getDocumentNo());
+        } else {
           FieldProviderFactory.setField(data[i], "invoiceNr", "");
-        if (FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule() != null)
-          FieldProviderFactory.setField(data[i], "orderNrTrunc", FIN_PaymentScheduleDetails[i]
-              .getOrderPaymentSchedule().getOrder().getDocumentNo());
-        else
+        }
+        if (FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule() != null) {
+          FieldProviderFactory.setField(data[i], "orderNrTrunc",
+              FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule().getOrder().getDocumentNo());
+        } else {
           FieldProviderFactory.setField(data[i], "orderNrTrunc", "");
-        if (FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule() != null)
-          FieldProviderFactory.setField(data[i], "invoiceNrTrunc", FIN_PaymentScheduleDetails[i]
-              .getInvoicePaymentSchedule().getInvoice().getDocumentNo());
-        else
+        }
+        if (FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule() != null) {
+          FieldProviderFactory.setField(data[i], "invoiceNrTrunc",
+              FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule()
+                  .getInvoice()
+                  .getDocumentNo());
+        } else {
           FieldProviderFactory.setField(data[i], "invoiceNrTrunc", "");
-        if (FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule() != null)
+        }
+        if (FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule() != null) {
           FieldProviderFactory.setField(data[i], "invoicePaymentScheduleId",
               FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule().getId());
-        else
+        } else {
           FieldProviderFactory.setField(data[i], "invoicePaymentScheduleId", "");
+        }
         if (FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule() != null) {
-          FieldProviderFactory.setField(
-              data[i],
-              "expectedDate",
-              dateFormater.format(
-                  FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule().getExpectedDate())
+          FieldProviderFactory.setField(data[i], "expectedDate",
+              dateFormater
+                  .format(
+                      FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule().getExpectedDate())
+                  .toString());
+          FieldProviderFactory.setField(data[i], "dueDate",
+              dateFormater
+                  .format(FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule().getDueDate())
                   .toString());
-          FieldProviderFactory.setField(
-              data[i],
-              "dueDate",
-              dateFormater.format(
-                  FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule().getDueDate())
+          FieldProviderFactory.setField(data[i], "invoicedAmount",
+              FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule()
+                  .getInvoice()
+                  .getGrandTotalAmount()
                   .toString());
-          FieldProviderFactory.setField(data[i], "invoicedAmount", FIN_PaymentScheduleDetails[i]
-              .getInvoicePaymentSchedule().getInvoice().getGrandTotalAmount().toString());
-          FieldProviderFactory.setField(data[i], "expectedAmount", FIN_PaymentScheduleDetails[i]
-              .getInvoicePaymentSchedule().getAmount().toString());
+          FieldProviderFactory.setField(data[i], "expectedAmount",
+              FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule().getAmount().toString());
 
           // Truncate Business Partner
           String businessPartner = FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule()
-              .getInvoice().getBusinessPartner().getIdentifier();
-          String truncateBusinessPartner = (businessPartner.length() > 18) ? businessPartner
-              .substring(0, 15).concat("...").toString() : businessPartner;
+              .getInvoice()
+              .getBusinessPartner()
+              .getIdentifier();
+          String truncateBusinessPartner = (businessPartner.length() > 18)
+              ? businessPartner.substring(0, 15).concat("...").toString()
+              : businessPartner;
           FieldProviderFactory.setField(data[i], "businessPartnerName",
               (businessPartner.length() > 18) ? businessPartner : "");
           FieldProviderFactory.setField(data[i], "businessPartnerNameTrunc",
               truncateBusinessPartner);
 
           // Truncate Currency
-          String currency = FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule().getInvoice()
-              .getCurrency().getIdentifier();
-          String truncateCurrency = (currency.length() > 18) ? currency.substring(0, 15)
-              .concat("...").toString() : currency;
+          String currency = FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule()
+              .getInvoice()
+              .getCurrency()
+              .getIdentifier();
+          String truncateCurrency = (currency.length() > 18)
+              ? currency.substring(0, 15).concat("...").toString()
+              : currency;
           FieldProviderFactory.setField(data[i], "currencyName",
               (currency.length() > 18) ? currency : "");
           FieldProviderFactory.setField(data[i], "currencyNameTrunc", truncateCurrency);
 
           // Truncate Payment Method
           String paymentMethodName = FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule()
-              .getFinPaymentmethod().getName();
-          String truncatePaymentMethodName = (paymentMethodName.length() > 18) ? paymentMethodName
-              .substring(0, 15).concat("...").toString() : paymentMethodName;
+              .getFinPaymentmethod()
+              .getName();
+          String truncatePaymentMethodName = (paymentMethodName.length() > 18)
+              ? paymentMethodName.substring(0, 15).concat("...").toString()
+              : paymentMethodName;
           FieldProviderFactory.setField(data[i], "paymentMethodName",
               (paymentMethodName.length() > 18) ? paymentMethodName : "");
           FieldProviderFactory.setField(data[i], "paymentMethodNameTrunc",
               truncatePaymentMethodName);
 
-          if (FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule().getFINPaymentPriority() != null) {
-            FieldProviderFactory.setField(data[i], "gridLineColor", FIN_PaymentScheduleDetails[i]
-                .getInvoicePaymentSchedule().getFINPaymentPriority().getColor());
+          if (FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule()
+              .getFINPaymentPriority() != null) {
+            FieldProviderFactory.setField(data[i], "gridLineColor",
+                FIN_PaymentScheduleDetails[i].getInvoicePaymentSchedule()
+                    .getFINPaymentPriority()
+                    .getColor());
           }
         } else {
-          FieldProviderFactory.setField(
-              data[i],
-              "expectedDate",
-              dateFormater.format(
-                  FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule().getExpectedDate())
+          FieldProviderFactory.setField(data[i], "expectedDate",
+              dateFormater
+                  .format(FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule().getExpectedDate())
+                  .toString());
+          FieldProviderFactory.setField(data[i], "dueDate",
+              dateFormater
+                  .format(FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule().getDueDate())
                   .toString());
-          FieldProviderFactory.setField(
-              data[i],
-              "dueDate",
-              dateFormater.format(
-                  FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule().getDueDate()).toString());
           FieldProviderFactory.setField(data[i], "invoicedAmount", "");
-          FieldProviderFactory.setField(data[i], "expectedAmount", FIN_PaymentScheduleDetails[i]
-              .getOrderPaymentSchedule().getAmount().toString());
+          FieldProviderFactory.setField(data[i], "expectedAmount",
+              FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule().getAmount().toString());
 
           // Truncate Business Partner
           String businessPartner = FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule()
-              .getOrder().getBusinessPartner().getIdentifier();
-          String truncateBusinessPartner = (businessPartner.length() > 18) ? businessPartner
-              .substring(0, 15).concat("...").toString() : businessPartner;
+              .getOrder()
+              .getBusinessPartner()
+              .getIdentifier();
+          String truncateBusinessPartner = (businessPartner.length() > 18)
+              ? businessPartner.substring(0, 15).concat("...").toString()
+              : businessPartner;
           FieldProviderFactory.setField(data[i], "businessPartnerName",
               (businessPartner.length() > 18) ? businessPartner : "");
           FieldProviderFactory.setField(data[i], "businessPartnerNameTrunc",
               truncateBusinessPartner);
 
           // Truncate Currency
-          String currency = FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule().getOrder()
-              .getCurrency().getIdentifier();
-          String truncateCurrency = (currency.length() > 18) ? currency.substring(0, 15)
-              .concat("...").toString() : currency;
+          String currency = FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule()
+              .getOrder()
+              .getCurrency()
+              .getIdentifier();
+          String truncateCurrency = (currency.length() > 18)
+              ? currency.substring(0, 15).concat("...").toString()
+              : currency;
           FieldProviderFactory.setField(data[i], "currencyName",
               (currency.length() > 18) ? currency : "");
           FieldProviderFactory.setField(data[i], "currencyNameTrunc", truncateCurrency);
 
           // Truncate Payment Method
           String paymentMethodName = FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule()
-              .getFinPaymentmethod().getName();
-          String truncatePaymentMethodName = (paymentMethodName.length() > 18) ? paymentMethodName
-              .substring(0, 15).concat("...").toString() : paymentMethodName;
+              .getFinPaymentmethod()
+              .getName();
+          String truncatePaymentMethodName = (paymentMethodName.length() > 18)
+              ? paymentMethodName.substring(0, 15).concat("...").toString()
+              : paymentMethodName;
           FieldProviderFactory.setField(data[i], "paymentMethodName",
               (paymentMethodName.length() > 18) ? paymentMethodName : "");
           FieldProviderFactory.setField(data[i], "paymentMethodNameTrunc",
               truncatePaymentMethodName);
 
-          if (FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule().getFINPaymentPriority() != null) {
-            FieldProviderFactory.setField(data[i], "gridLineColor", FIN_PaymentScheduleDetails[i]
-                .getOrderPaymentSchedule().getFINPaymentPriority().getColor());
+          if (FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule()
+              .getFINPaymentPriority() != null) {
+            FieldProviderFactory.setField(data[i], "gridLineColor",
+                FIN_PaymentScheduleDetails[i].getOrderPaymentSchedule()
+                    .getFINPaymentPriority()
+                    .getColor());
           }
         }
-        FieldProviderFactory.setField(data[i], "outstandingAmount", FIN_PaymentScheduleDetails[i]
-            .getAmount().toString());
+        FieldProviderFactory.setField(data[i], "outstandingAmount",
+            FIN_PaymentScheduleDetails[i].getAmount().toString());
 
         String strPaymentAmt = "";
         String strDifference = "";
         if (firstLoad && (selectedScheduledPaymentDetails.contains(FIN_PaymentScheduleDetails[i]))
-            && remittance != null)
+            && remittance != null) {
           strPaymentAmt = getRemittanceLineAmount(FIN_PaymentScheduleDetails[i], remittance);
-        else
-          strPaymentAmt = vars.getNumericParameter("inpPaymentAmount"
-              + FIN_PaymentScheduleDetails[i].getId(), "");
-        if (!"".equals(strPaymentAmt))
+        } else {
+          strPaymentAmt = vars
+              .getNumericParameter("inpPaymentAmount" + FIN_PaymentScheduleDetails[i].getId(), "");
+        }
+        if (!"".equals(strPaymentAmt)) {
           strDifference = FIN_PaymentScheduleDetails[i].getAmount()
-              .subtract(new BigDecimal(strPaymentAmt)).toString();
+              .subtract(new BigDecimal(strPaymentAmt))
+              .toString();
+        }
         if (data[i].getField("paymentAmount") == null
             || "".equals(data[i].getField("paymentAmount"))) {
           FieldProviderFactory.setField(data[i], "paymentAmount", strPaymentAmt);
@@ -424,9 +459,11 @@ public class REM_AddRemittance {
   private static String getRemittanceLineAmount(FIN_PaymentScheduleDetail finPaymentScheduleDetail,
       Remittance remittance) {
     String amount = "";
-    for (RemittanceLine line : remittance.getREMRemittanceLineList())
-      if (line.getPaymentScheduleDetail() == finPaymentScheduleDetail)
+    for (RemittanceLine line : remittance.getREMRemittanceLineList()) {
+      if (line.getPaymentScheduleDetail() == finPaymentScheduleDetail) {
         amount = line.getAmount().toString();
+      }
+    }
 
     return amount;
   }
@@ -462,8 +499,8 @@ public class REM_AddRemittance {
   }
 
   private static RemittanceLine getNewRemittanceLine(Remittance remittance,
-      FIN_PaymentScheduleDetail paymentScheduleDetail, BigDecimal amount,
-      BigDecimal writeoffamount, GLItem glitem) {
+      FIN_PaymentScheduleDetail paymentScheduleDetail, BigDecimal amount, BigDecimal writeoffamount,
+      GLItem glitem) {
     final RemittanceLine newRemittanceLine = OBProvider.getInstance().get(RemittanceLine.class);
     newRemittanceLine.setOrganization(remittance.getOrganization());
     newRemittanceLine.setAmount(amount);
@@ -502,190 +539,139 @@ public class REM_AddRemittance {
     if ("".equals(isReceipt)) {
       return new ArrayList<FIN_PaymentScheduleDetail>();
     }
-    final StringBuilder whereClause = new StringBuilder();
     final Map<String, Object> parameters = new HashMap<>();
     // FIXME: added to access the FIN_PaymentSchedule and FIN_PaymentScheduleDetail tables to be
     // removed when new security implementation is done
     OBContext.setAdminMode();
     try {
 
-      whereClause.append(" as psd "); // pending scheduled payments //
-      whereClause.append(" left outer join psd.orderPaymentSchedule as ops");
-      whereClause.append(" left outer join ops.order as ord ");
-      whereClause.append(" left outer join ord.businessPartner as obp ");
-      whereClause.append(" left outer join ops.fINPaymentPriority as opriority ");
-      whereClause.append(" left outer join psd.invoicePaymentSchedule ips ");
-      whereClause.append(" left outer join ips.invoice as inv ");
-      whereClause.append(" left outer join inv.businessPartner as ibp ");
-      whereClause.append(" left outer join ips.fINPaymentPriority as ipriority ");
-      whereClause.append(" where psd.");
-      whereClause.append(FIN_PaymentScheduleDetail.PROPERTY_PAYMENTDETAILS);
-      whereClause.append(" is null");
-      whereClause.append(" and psd.");
-      whereClause.append(FIN_PaymentSchedule.PROPERTY_ORGANIZATION);
-      whereClause.append(".id in (");
-      whereClause.append(Utility.getInStrSet(OBContext.getOBContext()
-          .getOrganizationStructureProvider().getChildTree(organization.getId(), true)));
-      whereClause.append(")");
+      // @formatter:off
+      String whereClause = ""
+          + " as psd " // pending scheduled payments //
+          + " left outer join psd.orderPaymentSchedule as ops"
+          + " left outer join ops.order as ord "
+          + " left outer join ord.businessPartner as obp "
+          + " left outer join ops.fINPaymentPriority as opriority "
+          + " left outer join psd.invoicePaymentSchedule ips "
+          + " left outer join ips.invoice as inv "
+          + " left outer join inv.businessPartner as ibp "
+          + " left outer join ips.fINPaymentPriority as ipriority "
+          + " where psd.paymentDetails is null"
+          + " and psd.organization.id in :orgdsIds";
+
+      parameters.put("orgids", OBContext.getOBContext()
+          .getOrganizationStructureProvider()
+          .getChildTree(organization.getId(), true));
 
       // remove selected payments
       if (selectedScheduledPaymentDetails != null && selectedScheduledPaymentDetails.size() > 0) {
         String strSelectedPaymentDetails = Utility.getInStrList(selectedScheduledPaymentDetails);
-        whereClause.append(" and psd not in (");
-        whereClause.append(strSelectedPaymentDetails);
-        whereClause.append(")");
+        whereClause += " and psd not in (" + strSelectedPaymentDetails + ")";
       }
 
       // block schedule payments in other payment proposal
-      final OBCriteria<FIN_PaymentPropDetail> obc = OBDal.getInstance().createCriteria(
-          FIN_PaymentPropDetail.class);
+      final OBCriteria<FIN_PaymentPropDetail> obc = OBDal.getInstance()
+          .createCriteria(FIN_PaymentPropDetail.class);
       obc.add(Restrictions.isNotNull(FIN_PaymentPropDetail.PROPERTY_FINPAYMENTSCHEDULEDETAIL));
       if (obc.list() != null && obc.list().size() > 0) {
         List<FIN_PaymentScheduleDetail> aux = new ArrayList<FIN_PaymentScheduleDetail>();
         for (FIN_PaymentPropDetail ppd : obc.list()) {
           aux.add(ppd.getFINPaymentScheduledetail());
         }
-        whereClause.append(" and psd.id not in (" + Utility.getInStrList(aux) + ")");
+        whereClause += " and psd.id not in (" + Utility.getInStrList(aux) + ")";
       }
 
       // Transaction type filter
-      whereClause.append(" and (");
+      whereClause += " and (";
       if (strTransactionType.equals("I") || strTransactionType.equals("B")) {
-        whereClause.append(" (inv is not null");
+        whereClause += " (inv is not null";
         if (paymentMethod != null) {
-          whereClause.append(" and ips.");
-          whereClause.append(FIN_PaymentSchedule.PROPERTY_FINPAYMENTMETHOD);
-          whereClause.append(".id = '");
-          whereClause.append(paymentMethod.getId());
-          whereClause.append("'");
+          whereClause
+              += " and ips.finPaymentmethod.id = :paymentMethodId";
+          parameters.put("paymentMethodId", paymentMethod.getId());
         }
         if (remittance != null) {
-          whereClause.append(" and (");
-          whereClause.append("inv.");
-          whereClause.append(Invoice.PROPERTY_CURRENCY);
-          whereClause.append(".id = '");
-          whereClause.append(remittance.getFinancialAccount().getCurrency().getId());
-          whereClause.append("'");
+          whereClause
+              += " and ("
+              +  "inv.currency.id = :currencyId";
+          parameters.put("currencyId", remittance.getFinancialAccount().getCurrency().getId());
           // Select invoices in multiple currencies
           if (showAlternativeCurrency) {
-            whereClause.append(" or rem_showalternativecurrency('");
-            whereClause.append(remittance.getId());
-            whereClause.append("', null, inv.id, null)='Y'");
+            whereClause += " or rem_showalternativecurrency(:remittanceId, null, inv.id, null)='Y'";
+            parameters.put("remittanceId", remittance.getId());
           }
-          whereClause.append(")");
+          whereClause += ")";
         }
-        whereClause.append(")");
+        whereClause += ")";
         // Business Partner
         if (!"".equals(strBPartner)) {
-          whereClause.append(" and inv.");
-          whereClause.append(Invoice.PROPERTY_BUSINESSPARTNER);
-          whereClause.append(".id = '");
-          whereClause.append(strBPartner);
-          whereClause.append("'");
+          whereClause += " and inv.businessPartner.id = :strBPartner ";
+          parameters.put("strBPartner", strBPartner);
         }
         // IsReceipt
         if ("Y".equals(isReceipt) || "N".equals(isReceipt)) {
-          whereClause.append(" and inv.");
-          whereClause.append(Invoice.PROPERTY_SALESTRANSACTION);
-          whereClause.append(" = ");
-          whereClause.append("Y".equals(isReceipt));
+          whereClause += " and inv.salesTransaction = " + "Y".equals(isReceipt);
         }
       }
-      if (strTransactionType.equals("B"))
-        whereClause.append(" or ");
+      if (strTransactionType.equals("B")) {
+        whereClause += " or ";
+      }
       if (strTransactionType.equals("O") || strTransactionType.equals("B")) {
-        whereClause.append(" (ord is not null");
+        whereClause += " (ord is not null";
         if (paymentMethod != null) {
-          whereClause.append(" and ops.");
-          whereClause.append(FIN_PaymentSchedule.PROPERTY_FINPAYMENTMETHOD);
-          whereClause.append(".id = '");
-          whereClause.append(paymentMethod.getId());
-          whereClause.append("'");
+          whereClause += " and ops.finPaymentmethod.id = :paymentMethodId";
+          // same param name as above (as having same value)
+          parameters.put("paymentMethodId", paymentMethod.getId());
         }
         if (remittance != null) {
-          whereClause.append(" and (");
-          whereClause.append("ord.");
-          whereClause.append(org.openbravo.model.common.order.Order.PROPERTY_CURRENCY);
-          whereClause.append(".id = '");
-          whereClause.append(remittance.getFinancialAccount().getCurrency().getId());
-          whereClause.append("'");
+          whereClause
+              += " and ("
+              +  "ord.currency.id = :currencyId";
+          // same param name as above (as having same value)
+          parameters.put("currencyId", remittance.getFinancialAccount().getCurrency().getId());
           // Select orders in multiple currencies
           if (showAlternativeCurrency) {
-            whereClause.append(" or rem_showalternativecurrency('");
-            whereClause.append(remittance.getId());
-            whereClause.append("', null, null, ord.id)='Y'");
+            whereClause += " or rem_showalternativecurrency(:remittanceId, null, null, ord.id)='Y'";
+            // same param name as above (as having same value)
+            parameters.put("remittanceId", remittance.getId());
           }
-          whereClause.append(")");
+          whereClause += ")";
         }
-        whereClause.append(")");
+        whereClause += ")";
         // Business Partner
         if (!"".equals(strBPartner)) {
-          whereClause.append(" and ord.");
-          whereClause.append(Invoice.PROPERTY_BUSINESSPARTNER);
-          whereClause.append(".id = '");
-          whereClause.append(strBPartner);
-          whereClause.append("'");
+          whereClause += " and ord." + "businessPartner" + ".id = :strBPartner";
+          parameters.put("strBPartner", strBPartner);
         }
         // IsReceipt
         if ("Y".equals(isReceipt) || "N".equals(isReceipt)) {
-          whereClause.append(" and ord.");
-          whereClause.append(org.openbravo.model.common.order.Order.PROPERTY_SALESTRANSACTION);
-          whereClause.append(" = ");
-          whereClause.append("Y".equals(isReceipt));
+          whereClause += " and ord.salesTransaction = "  + "Y".equals(isReceipt);
         }
       }
-      whereClause.append(")");
+      whereClause += ")";
       // dateFrom
       if (dueDateFrom != null) {
-        whereClause.append(" and COALESCE(ips.");
-        whereClause.append(FIN_PaymentSchedule.PROPERTY_EXPECTEDDATE);
-        whereClause.append(", ops.");
-        whereClause.append(FIN_PaymentSchedule.PROPERTY_EXPECTEDDATE);
-        whereClause.append(") >= :dueDateFrom");
+        whereClause += " and COALESCE(ips.expectedDate, ops.expectedDate) >= :dueDateFrom";
         parameters.put("dueDateFrom", dueDateFrom);
       }
       // dateTo
       if (dueDateTo != null) {
-        whereClause.append(" and COALESCE(ips.");
-        whereClause.append(FIN_PaymentSchedule.PROPERTY_EXPECTEDDATE);
-        whereClause.append(", ops.");
-        whereClause.append(FIN_PaymentSchedule.PROPERTY_EXPECTEDDATE);
-        whereClause.append(") < :dueDateTo");
+        whereClause += " and COALESCE(ips.expectedDate, ops.expectedDate) < :dueDateTo";
         parameters.put("dueDateTo", dueDateTo);
       }
       // TODO: Add order to show first scheduled payments from invoices and later scheduled payments
       // from not invoiced orders.
-      whereClause.append(" order by");
-      whereClause.append(" COALESCE(ipriority.");
-      whereClause.append(PaymentPriority.PROPERTY_PRIORITY);
-      whereClause.append(", opriority.");
-      whereClause.append(PaymentPriority.PROPERTY_PRIORITY);
-      whereClause.append(")");
-      whereClause.append(", ");
-      whereClause.append(" COALESCE(ips.");
-      whereClause.append(FIN_PaymentSchedule.PROPERTY_EXPECTEDDATE);
-      whereClause.append(", ops.");
-      whereClause.append(FIN_PaymentSchedule.PROPERTY_EXPECTEDDATE);
-      whereClause.append(")");
-      whereClause.append(", COALESCE(");
-      whereClause.append("ibp.").append(BusinessPartner.PROPERTY_NAME);
-      whereClause.append(", obp.");
-      whereClause.append(BusinessPartner.PROPERTY_NAME);
-      whereClause.append(") desc");
-      whereClause.append(", COALESCE(inv.");
-      whereClause.append(Invoice.PROPERTY_DOCUMENTNO);
-      whereClause.append(", ord.");
-      whereClause.append(org.openbravo.model.common.order.Order.PROPERTY_DOCUMENTNO);
-      whereClause.append(")");
-      whereClause.append(", COALESCE(ord.");
-      whereClause.append(org.openbravo.model.common.order.Order.PROPERTY_DOCUMENTNO);
-      whereClause.append(", inv.");
-      whereClause.append(Invoice.PROPERTY_DOCUMENTNO);
-      whereClause.append(")");
-      whereClause.append(", psd.");
-      whereClause.append(FIN_PaymentScheduleDetail.PROPERTY_AMOUNT);
-      final OBQuery<FIN_PaymentScheduleDetail> obqPSD = OBDal.getInstance().createQuery(
-          FIN_PaymentScheduleDetail.class, whereClause.toString());
+      whereClause
+          += " order by"
+          +  " COALESCE(ipriority.priority, opriority.priority), "
+          +  " COALESCE(ips.expectedDate, ops.expectedDate), "
+          +  "COALESCE(ibp.name, obp.name) desc, "
+          +  "COALESCE(inv.documentNo, ord.documentNo), "
+          +  "COALESCE(ord.documentNo, inv.documentNo), "
+          +  "psd.amount";
+      // @formatter:on
+      final OBQuery<FIN_PaymentScheduleDetail> obqPSD = OBDal.getInstance()
+          .createQuery(FIN_PaymentScheduleDetail.class, whereClause);
 
       obqPSD.setNamedParameters(parameters);
       return obqPSD.list();
@@ -732,8 +718,8 @@ public class REM_AddRemittance {
       while (psds.hasMoreTokens()) {
         psdSet.add(psds.nextToken());
       }
-      BigDecimal recordAmount = new BigDecimal(vars.getNumericParameter(
-          "inpPaymentAmount" + record, ""));
+      BigDecimal recordAmount = new BigDecimal(
+          vars.getNumericParameter("inpPaymentAmount" + record, ""));
       HashMap<String, BigDecimal> recordsAmounts = calculateAmounts(recordAmount, psdSet);
       for (String psdId : psdSet) {
         selectedPaymentScheduleDetailsAmounts.put(psdId, recordsAmounts.get(psdId));
@@ -756,10 +742,11 @@ public class REM_AddRemittance {
     for (FIN_PaymentScheduleDetail paymentScheduleDetail : psds) {
       BigDecimal outstandingAmount = paymentScheduleDetail.getAmount();
       // Manage negative amounts
-      if ((remainingAmount.compareTo(BigDecimal.ZERO) > 0 && remainingAmount
-          .compareTo(outstandingAmount) >= 0)
-          || ((remainingAmount.compareTo(BigDecimal.ZERO) == -1 && outstandingAmount
-              .compareTo(BigDecimal.ZERO) == -1) && (remainingAmount.compareTo(outstandingAmount) <= 0))
+      if ((remainingAmount.compareTo(BigDecimal.ZERO) > 0
+          && remainingAmount.compareTo(outstandingAmount) >= 0)
+          || ((remainingAmount.compareTo(BigDecimal.ZERO) == -1
+              && outstandingAmount.compareTo(BigDecimal.ZERO) == -1)
+              && (remainingAmount.compareTo(outstandingAmount) <= 0))
           || (remainingAmount.compareTo(totalamount) == 0)) {
         recordsAmounts.put(paymentScheduleDetail.getId(), outstandingAmount);
         remainingAmount = remainingAmount.subtract(outstandingAmount);
@@ -774,9 +761,10 @@ public class REM_AddRemittance {
     return recordsAmounts;
   }
 
-  private static List<FIN_PaymentScheduleDetail> getOrderedPaymentScheduleDetails(Set<String> psdSet) {
-    OBCriteria<FIN_PaymentScheduleDetail> orderedPSDs = OBDal.getInstance().createCriteria(
-        FIN_PaymentScheduleDetail.class);
+  private static List<FIN_PaymentScheduleDetail> getOrderedPaymentScheduleDetails(
+      Set<String> psdSet) {
+    OBCriteria<FIN_PaymentScheduleDetail> orderedPSDs = OBDal.getInstance()
+        .createCriteria(FIN_PaymentScheduleDetail.class);
     orderedPSDs.add(Restrictions.in(FIN_PaymentScheduleDetail.PROPERTY_ID, psdSet));
     orderedPSDs.addOrderBy(FIN_PaymentScheduleDetail.PROPERTY_AMOUNT, true);
     return orderedPSDs.list();
@@ -785,12 +773,14 @@ public class REM_AddRemittance {
   public static HashMap<String, String> existLineInAnyRemittance(FIN_Payment payment) {
     OBCriteria<Remittance> rem = OBDal.getInstance().createCriteria(Remittance.class);
     rem.createAlias(Remittance.PROPERTY_REMITTANCETYPE, "rt");
-    rem.add(Restrictions.eq("rt." + RemittanceType.PROPERTY_PAYMENTMETHOD,
-        payment.getPaymentMethod()));
+    rem.add(
+        Restrictions.eq("rt." + RemittanceType.PROPERTY_PAYMENTMETHOD, payment.getPaymentMethod()));
     rem.add(Restrictions.eq(Remittance.PROPERTY_FINANCIALACCOUNT, payment.getAccount()));
     rem.add(Restrictions.eq(Remittance.PROPERTY_PROCESSED, false));
-    rem.add(Restrictions.in("organization.id", OBContext.getOBContext()
-        .getOrganizationStructureProvider().getParentTree(payment.getOrganization().getId(), true)));
+    rem.add(Restrictions.in("organization.id",
+        OBContext.getOBContext()
+            .getOrganizationStructureProvider()
+            .getParentTree(payment.getOrganization().getId(), true)));
 
     List<Remittance> openRemittances = rem.list();
 
@@ -813,8 +803,8 @@ public class REM_AddRemittance {
   }
 
   public static HashMap<String, String> existLineInSettledRemittance(FIN_Payment payment) {
-    OBCriteria<RemittanceLineCancel> remlc = OBDal.getInstance().createCriteria(
-        RemittanceLineCancel.class);
+    OBCriteria<RemittanceLineCancel> remlc = OBDal.getInstance()
+        .createCriteria(RemittanceLineCancel.class);
     remlc.add(Restrictions.eq(Remittance.PROPERTY_PAYMENT, payment));
     remlc.setMaxResults(1);
     RemittanceLineCancel settledLine = (RemittanceLineCancel) remlc.uniqueResult();
diff --git a/src/org/openbravo/module/remittance/process/REM_RemittanceProcess.java b/src/org/openbravo/module/remittance/process/REM_RemittanceProcess.java
index 3f52c61c545eed0bb5a6e692b7eff51b26cac46b..e42d6326053563aa096d62bc12c542f82425c14f 100644
--- a/src/org/openbravo/module/remittance/process/REM_RemittanceProcess.java
+++ b/src/org/openbravo/module/remittance/process/REM_RemittanceProcess.java
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2011-2022 Openbravo SLU
+ * All portions are Copyright (C) 2011-2023 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -441,7 +441,6 @@ public class REM_RemittanceProcess implements org.openbravo.scheduling.Process {
    */
   private void createGroupedPayments(Remittance remittance, boolean isDateGroup,
       boolean isInvoiceGroup) throws Exception {
-    StringBuilder whereClause = new StringBuilder();
     Remittance rem = remittance;
     FIN_PaymentMethod pm = rem.getRemittanceType().getPaymentMethod();
 
@@ -461,23 +460,26 @@ public class REM_RemittanceProcess implements org.openbravo.scheduling.Process {
         addRemittanceBankInstruction(rem, payment);
       }
     }
-    whereClause.append(" select remline.id from REM_RemittanceLine ");
-    // Get remittance lines ordered by business partner of the invoice/order
-    whereClause.append(" as remline join remline.paymentScheduleDetail as psd");
-    whereClause.append(" left outer join psd.orderPaymentSchedule as ops");
-    whereClause.append(" left outer join ops.order as ord");
-    whereClause.append(" left outer join psd.invoicePaymentSchedule as ips");
-    whereClause.append(" left outer join ips.invoice as inv");
-    whereClause.append(" where remline.remittance.id = :remittanceId");
-    whereClause.append(" order by coalesce(inv.currency, ord.currency), ");
-    whereClause.append(" coalesce(inv.businessPartner, ord.businessPartner), ");
-    whereClause.append(" coalesce(ips.expectedDate, ops.expectedDate), ");
-    whereClause.append(" coalesce(inv.salesTransaction, ord.salesTransaction), ");
-    whereClause.append(" coalesce(inv.id, ord.id) ");
+    // @formatter:off
+    String whereClause = ""
+        + " select remline.id from REM_RemittanceLine "
+       // Get remittance lines ordered by business partner of the invoice/order
+        + " as remline join remline.paymentScheduleDetail as psd"
+        + " left outer join psd.orderPaymentSchedule as ops"
+        + " left outer join ops.order as ord"
+        + " left outer join psd.invoicePaymentSchedule as ips"
+        + " left outer join ips.invoice as inv"
+        + " where remline.remittance.id = :remittanceId"
+        + " order by coalesce(inv.currency, ord.currency), "
+        + " coalesce(inv.businessPartner, ord.businessPartner), "
+        + " coalesce(ips.expectedDate, ops.expectedDate), "
+        + " coalesce(inv.salesTransaction, ord.salesTransaction), "
+        + " coalesce(inv.id, ord.id) ";
+    // @formatter:on
 
     final Query<String> remitanceLineQuery = OBDal.getInstance()
         .getSession()
-        .createQuery(whereClause.toString(), String.class);
+        .createQuery(whereClause, String.class);
     remitanceLineQuery.setParameter("remittanceId", rem.getId());
 
     List<String> lines = remitanceLineQuery.list();
@@ -1286,15 +1288,15 @@ public class REM_RemittanceProcess implements org.openbravo.scheduling.Process {
   private List<String> getRemittanceLines(String paymentId, String remittanceId) {
     OBContext.setAdminMode();
     try {
-      final StringBuilder whereClause = new StringBuilder();
-      whereClause.append(" select rl." + RemittanceLine.PROPERTY_ID);
-      whereClause.append(" from " + RemittanceLine.ENTITY_NAME + " as rl");
-      whereClause.append(" where rl." + RemittanceLine.PROPERTY_PAYMENT + ".id = :paymentId");
-      whereClause.append(" and rl." + RemittanceLine.PROPERTY_REMITTANCE + ".id = :remittanceId");
-      whereClause.append(" and rl." + RemittanceLine.PROPERTY_ACTIVE + " = true");
-      Query<String> query = OBDal.getInstance()
-          .getSession()
-          .createQuery(whereClause.toString(), String.class);
+      // @formatter:off
+      String whereClause = ""
+          + " select rl.id"
+          + " from REM_RemittanceLine as rl"
+          + " where rl.payment.id = :paymentId"
+          + " and rl.remittance.id = :remittanceId"
+          + " and rl.active = true";
+      // @formatter:on
+      Query<String> query = OBDal.getInstance().getSession().createQuery(whereClause, String.class);
       query.setParameter("paymentId", paymentId);
       query.setParameter("remittanceId", remittanceId);
       return query.list();
@@ -1434,14 +1436,14 @@ public class REM_RemittanceProcess implements org.openbravo.scheduling.Process {
   private List<String> getRemittanceLines(String remittanceId) {
     OBContext.setAdminMode();
     try {
-      final StringBuilder whereClause = new StringBuilder();
-      whereClause.append(" select rl." + RemittanceLine.PROPERTY_ID);
-      whereClause.append(" from " + RemittanceLine.ENTITY_NAME + " as rl");
-      whereClause.append(" where rl." + RemittanceLine.PROPERTY_REMITTANCE + ".id = :remittanceId");
-      whereClause.append(" and rl." + RemittanceLine.PROPERTY_ACTIVE + " = true");
-      Query<String> query = OBDal.getInstance()
-          .getSession()
-          .createQuery(whereClause.toString(), String.class);
+      // @formatter:off
+      String whereClause = ""
+          + " select rl.id"
+          + " from REM_RemittanceLine as rl"
+          + " where rl.remittance.id = :remittanceId"
+          + " and rl.active = true";
+      // @formatter:on
+      Query<String> query = OBDal.getInstance().getSession().createQuery(whereClause, String.class);
       query.setParameter("remittanceId", remittanceId);
       return query.list();
     } finally {
