From 121aeb0c31b3afe8cf3f79b2f1f95630acf09827 Mon Sep 17 00:00:00 2001
From: jetxarri <javier.echarri@openbravo.com>
Date: Fri, 8 Oct 2021 08:08:51 +0200
Subject: [PATCH] Fixes issue NOE-5184: Delete free product type promotion
 calls if products not concerned

---
 .../engine/graal/GraalDiscountsExecutor.java  | 42 +++++++++++++++++++
 1 file changed, 42 insertions(+)

diff --git a/src/org/openbravo/discounts/engine/graal/GraalDiscountsExecutor.java b/src/org/openbravo/discounts/engine/graal/GraalDiscountsExecutor.java
index 08da027..fe03e05 100644
--- a/src/org/openbravo/discounts/engine/graal/GraalDiscountsExecutor.java
+++ b/src/org/openbravo/discounts/engine/graal/GraalDiscountsExecutor.java
@@ -16,6 +16,8 @@ import java.util.List;
 
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
+import org.codehaus.jettison.json.JSONArray;
+import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
 import org.graalvm.polyglot.Context;
 import org.graalvm.polyglot.Engine;
@@ -122,6 +124,8 @@ public class GraalDiscountsExecutor extends DiscountJSExecutor {
       t1 = System.currentTimeMillis();
       JSONObject result = jsonUtils.graalToJson(discounts);
 
+      result = removeHiddenDiscounts(result);
+
       return TicketResult.builder()
           .withTicketId(ticket.getId())
           .withNamespace(
@@ -134,4 +138,42 @@ public class GraalDiscountsExecutor extends DiscountJSExecutor {
           now - t, tr - t, t0 - tr, t1 - t0, now - t1);
     }
   }
+
+  private JSONObject removeHiddenDiscounts(JSONObject jsonObject) {
+    JSONArray filteredLines = new JSONArray();
+    JSONArray lines = jsonObject.optJSONArray("lines");
+    JSONObject result = new JSONObject();
+    try {
+      if (lines != null) {
+        for (int i = 0; i < lines.length(); i++) {
+          JSONObject line = lines.getJSONObject(i);
+
+          if (line.has("discounts")) {
+            JSONArray promotions = line.getJSONArray("discounts");
+            JSONArray filteredPromotions = new JSONArray();
+
+            for (int j = 0; j < promotions.length(); j++) {
+              if (!promotions.getJSONObject(j).has("hidden")
+                  || promotions.getJSONObject(j).getBoolean("hidden") == false) {
+                filteredPromotions.put(promotions.getJSONObject(j));
+              }
+            }
+
+            line.put("discounts", filteredPromotions);
+
+          }
+
+          if (line.getJSONArray("discounts").length() > 0) {
+            filteredLines.put(line);
+          }
+        }
+        result.put("lines", filteredLines);
+      }
+    } catch (JSONException e) {
+      // Should not happen
+      log.error("Problem trying to remove hidden discounts");
+    }
+
+    return result;
+  }
 }
-- 
2.31.0

