Redfish OEM Patch Route Handling

Extension of OEM route infra to support registration of handlers for OEM
patch requests. When patch request is made on a redfish resource, first
the main route handler will be called and if request patch payload
contains any OEM fragments then, registered OEM patch handler will be
called.

Tested
1. UT passes with new test cases added for OEM patch handling
2. Patch on FAN OEM property works as expected

```
Step 1: Creating new fan controller...
Create PATCH data:
{
  "Oem": {
    "OpenBmc": {
      "Fan": {
        "FanControllers": {
          "Fan_TEST_391715": {
            "FFGainCoefficient": 2.0,
            "Zones": [
              {
                "@odata.id": "/redfish/v1/Managers/bmc#/Oem/OpenBmc/Fan/FanZones/Zone_1"
              }
            ]
          }
        }
      }
    }
  }
}

HTTP Response Code (PATCH /redfish/v1/Managers/bmc): 200

HTTP Response Code (GET /redfish/v1/Managers/bmc): 200
✓ Fan controller created successfully

Step 2: Updating the fan controller...
Update PATCH data:
{
  "Oem": {
    "OpenBmc": {
      "Fan": {
        "FanControllers": {
          "Fan_TEST_391715": {
            "FFGainCoefficient": 3.0
          }
        }
      }
    }
  }
}

HTTP Response Code (PATCH /redfish/v1/Managers/bmc): 200

HTTP Response Code (GET /redfish/v1/Managers/bmc): 200

Final Configuration:
{
  "@odata.id": "/redfish/v1/Managers/bmc#/Oem/OpenBmc/Fan/FanControllers/Fan_TEST_391715",
  "@odata.type": "#OpenBMCManager.v1_0_0.Manager.FanController",
  "FFGainCoefficient": 3.0,
  "Zones": [
    {
      "@odata.id": "/redfish/v1/Managers/bmc#/Oem/OpenBmc/Fan/FanZones/Zone_1"
    }
  ]
}
✓ Fan controller updated successfully
```

Test Summary
```
[+] Tests DateTime update after NTP disable. Payload: {DateTime: <date-string>}. Expects: 204 success, validates date matches update.: PASSED
[-] Tests invalid property in request. Payload: {InvalidProperty: 'value', DateTime: <date-string>}. Expects: 400 PropertyUnknown error, validates DateTime unchanged.: PASSED
[-] Tests fan controller with invalid property. Payload: Oem/OpenBmc/Fan/FanControllers with InvalidProperty. Expects: 400 PropertyUnknown error, fan not created.: PASSED
[-] Tests empty PATCH request. Payload: {}. Expects: 400 MalformedJSON error.: PASSED
[-] Tests malformed fan controller JSON. Payload: Fan property as string instead of object. Expects: 400 PropertyValueTypeError error.: PASSED
[-] Tests DateTime with wrong type. Payload: {DateTime: 12345}. Expects: 400 PropertyValueTypeError error, DateTime unchanged.: PASSED
[-] Tests PATCH to invalid manager path. Payload: Valid DateTime and fan update to /invalid_bmc. Expects: 404 ResourceNotFound error.: PASSED
[+] Tests fan controller creation. Payload: Oem/OpenBmc/Fan/FanControllers with FFGainCoefficient and Zones. Expects: 200 success with success message.: PASSED
[-] Tests fan controller without required Zones. Payload: Oem/OpenBmc/Fan/FanControllers with only FFGainCoefficient. Expects: 500 InternalError, fan not created.: PASSED
[+] Tests combined DateTime and fan update. Payload: DateTime and Oem/OpenBmc/Fan/FanControllers. Expects: 200 success with success message.: PASSED
[-] Tests PATCH with wrong Content-Type header. Payload: Valid DateTime update with text/plain content-type. Expects: 400 UnrecognizedRequestBody error.: PASSED
[+] Tests fan controller creation and update. Payload: Create with FFGainCoefficient=2.0, then update to 3.0. Expects: 200 success for both operations, verifies all properties.: PASSED
```

Change-Id: Ib2498b6a4db0343d5d4a405a5a8e4d78f615bed8
Signed-off-by: Rohit PAI <rohitpai77@gmail.com>
diff --git a/redfish-core/include/redfish.hpp b/redfish-core/include/redfish.hpp
index f6628eb..c2e336e 100644
--- a/redfish-core/include/redfish.hpp
+++ b/redfish-core/include/redfish.hpp
@@ -52,6 +52,10 @@
         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) const
     {
         auto subReq = std::make_shared<SubRequest>(req);
+        if (!subReq->needHandling())
+        {
+            return;
+        }
         oemRouter.handle(subReq, asyncResp);
     }
 
diff --git a/redfish-core/include/sub_request.hpp b/redfish-core/include/sub_request.hpp
index 8c846ae..df8cf70 100644
--- a/redfish-core/include/sub_request.hpp
+++ b/redfish-core/include/sub_request.hpp
@@ -3,8 +3,10 @@
 #pragma once
 
 #include "http_request.hpp"
+#include "parsing.hpp"
 
 #include <boost/beast/http/verb.hpp>
+#include <nlohmann/json.hpp>
 
 #include <string>
 #include <string_view>
@@ -17,7 +19,29 @@
   public:
     explicit SubRequest(const crow::Request& req) :
         url_(req.url().encoded_path()), method_(req.method())
-    {}
+    {
+        // Extract OEM payload if present
+        if (req.method() == boost::beast::http::verb::patch ||
+            req.method() == boost::beast::http::verb::post)
+        {
+            nlohmann::json reqJson;
+            if (parseRequestAsJson(req, reqJson) != JsonParseResult::Success)
+            {
+                return;
+            }
+
+            auto oemIt = reqJson.find("Oem");
+            if (oemIt != reqJson.end() && oemIt->is_object())
+            {
+                const nlohmann::json::object_t* oemObj =
+                    oemIt->get_ptr<const nlohmann::json::object_t*>();
+                if (oemObj != nullptr && !oemObj->empty())
+                {
+                    payload_ = *oemObj;
+                }
+            }
+        }
+    }
 
     std::string_view url() const
     {
@@ -29,9 +53,32 @@
         return method_;
     }
 
+    const nlohmann::json::object_t& payload() const
+    {
+        return payload_;
+    }
+
+    bool needHandling() const
+    {
+        if (method_ == boost::beast::http::verb::get)
+        {
+            return true;
+        }
+
+        if ((method_ == boost::beast::http::verb::patch ||
+             method_ == boost::beast::http::verb::post) &&
+            !payload_.empty())
+        {
+            return true;
+        }
+
+        return false;
+    }
+
   private:
     std::string url_;
     boost::beast::http::verb method_;
+    nlohmann::json::object_t payload_;
 };
 
 } // namespace redfish
diff --git a/redfish-core/lib/managers.hpp b/redfish-core/lib/managers.hpp
index 72b091c..85b4044 100644
--- a/redfish-core/lib/managers.hpp
+++ b/redfish-core/lib/managers.hpp
@@ -15,7 +15,6 @@
 #include "generated/enums/resource.hpp"
 #include "http_request.hpp"
 #include "logging.hpp"
-#include "openbmc/openbmc_managers.hpp"
 #include "persistent_data.hpp"
 #include "query.hpp"
 #include "redfish.hpp"
@@ -917,47 +916,6 @@
                     return;
                 }
 
-                if (pidControllers || fanControllers || fanZones ||
-                    stepwiseControllers || profile)
-                {
-                    if constexpr (BMCWEB_REDFISH_OEM_MANAGER_FAN_DATA)
-                    {
-                        std::vector<
-                            std::pair<std::string,
-                                      std::optional<nlohmann::json::object_t>>>
-                            configuration;
-                        if (pidControllers)
-                        {
-                            configuration.emplace_back(
-                                "PidControllers", std::move(pidControllers));
-                        }
-                        if (fanControllers)
-                        {
-                            configuration.emplace_back(
-                                "FanControllers", std::move(fanControllers));
-                        }
-                        if (fanZones)
-                        {
-                            configuration.emplace_back("FanZones",
-                                                       std::move(fanZones));
-                        }
-                        if (stepwiseControllers)
-                        {
-                            configuration.emplace_back(
-                                "StepwiseControllers",
-                                std::move(stepwiseControllers));
-                        }
-                        auto pid = std::make_shared<SetPIDValues>(
-                            asyncResp, std::move(configuration), profile);
-                        pid->run();
-                    }
-                    else
-                    {
-                        messages::propertyUnknown(asyncResp->res, "Oem");
-                        return;
-                    }
-                }
-
                 if (activeSoftwareImageOdataId)
                 {
                     setActiveFirmwareImage(asyncResp,
@@ -968,6 +926,8 @@
                 {
                     setDateTime(asyncResp, *datetime);
                 }
+
+                RedfishService::getInstance(app).handleSubRoute(req, asyncResp);
             });
 }
 
diff --git a/redfish-core/lib/openbmc/openbmc_managers.hpp b/redfish-core/lib/openbmc/openbmc_managers.hpp
index bf0e791..b8bacc3 100644
--- a/redfish-core/lib/openbmc/openbmc_managers.hpp
+++ b/redfish-core/lib/openbmc/openbmc_managers.hpp
@@ -1502,10 +1502,75 @@
     }
 }
 
+inline void handlePatchManagerOpenBmc(
+    const SubRequest& req, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
+    const std::string& /*managerId*/)
+{
+    nlohmann::json::object_t payload = req.payload();
+
+    std::optional<nlohmann::json::object_t> pidControllers;
+    std::optional<nlohmann::json::object_t> fanControllers;
+    std::optional<nlohmann::json::object_t> fanZones;
+    std::optional<nlohmann::json::object_t> stepwiseControllers;
+    std::optional<std::string> profile;
+
+    if (!json_util::readJsonObject(
+            payload, asyncResp->res, "OpenBmc/Fan/PidControllers",
+            pidControllers, "OpenBmc/Fan/FanControllers", fanControllers,
+            "OpenBmc/Fan/FanZones", fanZones, "OpenBmc/Fan/StepwiseControllers",
+            stepwiseControllers, "OpenBmc/Fan/Profile", profile))
+    {
+        return;
+    }
+
+    if (pidControllers || fanControllers || fanZones || stepwiseControllers ||
+        profile)
+    {
+        if constexpr (BMCWEB_REDFISH_OEM_MANAGER_FAN_DATA)
+        {
+            std::vector<
+                std::pair<std::string, std::optional<nlohmann::json::object_t>>>
+                configuration;
+
+            if (pidControllers)
+            {
+                configuration.emplace_back("PidControllers",
+                                           std::move(pidControllers));
+            }
+            if (fanControllers)
+            {
+                configuration.emplace_back("FanControllers",
+                                           std::move(fanControllers));
+            }
+            if (fanZones)
+            {
+                configuration.emplace_back("FanZones", std::move(fanZones));
+            }
+            if (stepwiseControllers)
+            {
+                configuration.emplace_back("StepwiseControllers",
+                                           std::move(stepwiseControllers));
+            }
+
+            auto pid = std::make_shared<SetPIDValues>(
+                asyncResp, std::move(configuration), profile);
+            pid->run();
+        }
+        else
+        {
+            messages::propertyUnknown(asyncResp->res, "Oem");
+            return;
+        }
+    }
+}
+
 inline void requestRoutesOpenBmcManager(RedfishService& service)
 {
     REDFISH_SUB_ROUTE<"/redfish/v1/Managers/<str>/#/Oem/OpenBmc">(
         service, HttpVerb::Get)(handleGetManagerOpenBmc);
+
+    REDFISH_SUB_ROUTE<"/redfish/v1/Managers/<str>/#/Oem/OpenBmc">(
+        service, HttpVerb::Patch)(handlePatchManagerOpenBmc);
 }
 
 } // namespace redfish
diff --git a/test/redfish-core/include/redfish_oem_routing_test.cpp b/test/redfish-core/include/redfish_oem_routing_test.cpp
index 9f9bfdb..dae7e79 100644
--- a/test/redfish-core/include/redfish_oem_routing_test.cpp
+++ b/test/redfish-core/include/redfish_oem_routing_test.cpp
@@ -6,11 +6,13 @@
 #include "verb.hpp"
 
 #include <boost/beast/http/verb.hpp>
+#include <nlohmann/json.hpp>
 
 #include <memory>
 #include <string>
 #include <string_view>
 #include <system_error>
+#include <utility>
 
 #include <gtest/gtest.h>
 
@@ -66,5 +68,101 @@
     EXPECT_TRUE(standardCalled);
 }
 
+TEST(OemRouter, PatchHandlerWithJsonObject)
+{
+    std::error_code ec;
+    App app;
+    RedfishService service(app);
+
+    // Callback handlers
+    bool callback1Called = false;
+    auto patchCallback1 =
+        [&callback1Called](
+            const SubRequest& req,
+            [[maybe_unused]] const std::shared_ptr<bmcweb::AsyncResp>&
+                asyncResp,
+            [[maybe_unused]] const std::string& param) {
+            callback1Called = true;
+
+            const nlohmann::json::object_t& payload = req.payload();
+            auto oemFooIt = payload.find("OemFoo");
+            ASSERT_NE(oemFooIt, payload.end());
+            ASSERT_TRUE(oemFooIt->second.is_object());
+
+            auto keyIt = oemFooIt->second.find("OemFooKey");
+            ASSERT_NE(keyIt, oemFooIt->second.end());
+            EXPECT_EQ(keyIt.value(), "fooValue");
+        };
+
+    bool callback2Called = false;
+    auto patchCallback2 =
+        [&callback2Called](
+            const SubRequest& req,
+            [[maybe_unused]] const std::shared_ptr<bmcweb::AsyncResp>&
+                asyncResp,
+            [[maybe_unused]] const std::string& param) {
+            callback2Called = true;
+
+            const nlohmann::json::object_t& payload = req.payload();
+            auto oemBarIt = payload.find("OemBar");
+            ASSERT_NE(oemBarIt, payload.end());
+            ASSERT_TRUE(oemBarIt->second.is_object());
+
+            auto keyIt = oemBarIt->second.find("OemBarKey");
+            ASSERT_NE(keyIt, oemBarIt->second.end());
+            EXPECT_EQ(keyIt.value(), "barValue");
+        };
+
+    bool standardCalled = false;
+    auto standardCallback =
+        [&standardCalled,
+         &service](const crow::Request& req,
+                   const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
+                   const std::string& bar) {
+            service.handleSubRoute(req, asyncResp);
+            standardCalled = true;
+            EXPECT_EQ(bar, "bar");
+        };
+
+    // Need the normal route registered for OEM to work
+    BMCWEB_ROUTE(app, "/foo/<str>/")
+        .methods(boost::beast::http::verb::patch)(standardCallback);
+
+    REDFISH_SUB_ROUTE<"/foo/<str>/#/Oem/OemFoo">(service, HttpVerb::Patch)(
+        patchCallback1);
+    REDFISH_SUB_ROUTE<"/foo/<str>/#/Oem/OemBar">(service, HttpVerb::Patch)(
+        patchCallback2);
+
+    app.validate();
+    service.validate();
+
+    {
+        constexpr std::string_view reqUrl = "/foo/bar";
+        // OEM payload
+        nlohmann::json reqBody = {{"Oem",
+                                   {{"OemFoo", {{"OemFooKey", "fooValue"}}},
+                                    {"OemBar", {{"OemBarKey", "barValue"}}}}}};
+
+        // Create request with the body string
+        std::shared_ptr<crow::Request> req = std::make_shared<crow::Request>(
+            crow::Request::Body{
+                boost::beast::http::verb::patch, reqUrl, 11,
+                reqBody.dump() // Pass body string directly in the constructor
+            },
+            ec);
+
+        req->addHeader("Content-Type", "application/json");
+
+        std::shared_ptr<bmcweb::AsyncResp> asyncResp =
+            std::make_shared<bmcweb::AsyncResp>();
+
+        app.handle(req, asyncResp);
+    }
+
+    EXPECT_TRUE(standardCalled);
+    EXPECT_TRUE(callback1Called);
+    EXPECT_TRUE(callback2Called);
+}
+
 } // namespace
 } // namespace redfish