codeant-ai-for-open-source[bot] commented on code in PR #43480:
URL: https://github.com/apache/superset/pull/43480#discussion_r3846268574


##########
superset/mcp_service/chart/plugins/interactive_pivot.py:
##########
@@ -0,0 +1,225 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Preset AG Grid interactive pivot chart plugin."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any, ClassVar
+
+from superset.extensions import feature_flag_manager
+from superset.mcp_service.chart.chart_utils import (
+    _add_adhoc_filters,
+    _summarize_filters,
+    add_currency_format,
+    create_metric_object,
+)
+from superset.mcp_service.chart.plugin import BaseChartPlugin
+from superset.mcp_service.chart.schemas import ColumnRef, 
InteractivePivotChartConfig
+from superset.mcp_service.chart.validation.dataset_validator import 
DatasetValidator
+from superset.mcp_service.common.error_schemas import ChartGenerationError
+
+AG_GRID_PIVOT_FEATURE_FLAG = "AG_GRID_PIVOT_TABLE_ENABLED"
+_AG_GRID_AGGREGATION = {
+    "AVG": "avg",
+    "MIN": "min",
+    "MAX": "max",
+}
+
+
+def _metric_label(metric: dict[str, Any] | str) -> str:
+    """Return the label AG Grid uses as a metric column identifier."""
+    return metric if isinstance(metric, str) else str(metric["label"])
+
+
+def _grid_aggregation(metric: ColumnRef) -> str:
+    """Map a Superset metric aggregate to AG Grid's group rollup function."""
+    return _AG_GRID_AGGREGATION.get((metric.aggregate or "SUM").upper(), "sum")
+
+
+def map_interactive_pivot_config(
+    config: InteractivePivotChartConfig,
+) -> dict[str, Any]:
+    """Map the MCP config to Preset's ``ag-grid-pivot-table`` form data."""
+    metrics = [create_metric_object(metric) for metric in config.metrics]
+    rows = [column.name for column in config.rows]
+    columns = [column.name for column in config.columns]
+
+    form_data: dict[str, Any] = {
+        "viz_type": "ag-grid-pivot-table",
+        # The Preset control panel stores every dimension in groupby. AG Grid's
+        # persisted state assigns each one to the Rows or Column Labels bucket.
+        "groupby": [*rows, *columns],
+        "metrics": metrics,
+        "row_limit": config.row_limit,
+        "order_desc": config.sort_descending,
+        "rowGroupCounts": config.show_row_group_counts,
+        "rowTotals": config.show_row_totals,
+        "colTotals": config.show_column_totals,
+        "colSubTotals": config.show_column_subtotals,
+        "valueFormat": config.value_format,
+        "allow_render_html": config.allow_render_html,
+        "expand_pivot_groups": config.expand_pivot_groups,
+        "pivot_table_state": {
+            "rowGroup": {"groupColIds": rows},
+            "pivot": {"pivotMode": True, "pivotColIds": columns},
+            "aggregation": {
+                "aggregationModel": [
+                    {
+                        "colId": _metric_label(mapped_metric),
+                        "aggFunc": _grid_aggregation(metric),
+                    }
+                    for metric, mapped_metric in zip(
+                        config.metrics, metrics, strict=True
+                    )
+                ]
+            },
+        },
+    }
+
+    if config.time_grain:
+        # Preset's hidden temporal_columns_lookup control identifies temporal
+        # dimensions in groupby, and its buildQuery applies this grain to each
+        # one. A single granularity_sqla is neither required nor sufficient for
+        # a pivot that can contain multiple temporal dimensions.
+        form_data["time_grain_sqla"] = config.time_grain.value

Review Comment:
   **Suggestion:** The pivot state never identifies which grouped dimensions 
are temporal: setting only `time_grain_sqla` is insufficient because the form 
data does not include `granularity_sqla` or `temporal_columns_lookup`. As a 
result, `time_grain` is ignored or cannot be applied to the intended row/column 
dimensions, so generated pivots with temporal grouping do not honor the 
requested grain. [logic error]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ Interactive Pivot temporal grouping can ignore requested grain.
   - ⚠️ Generated pivot rows or columns may use raw timestamps.
   - ❌ Time-based pivot analysis can return incorrect aggregation buckets.
   ```
   </details>
   
   [![Use CodeAnt 
Skill](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/use-codeant-skill-flat-v2.svg)](https://docs.codeant.ai/cli/resolve-pr-comments-skill)
 [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=7b16070e86f2477dbea0925718389a9b&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=7b16070e86f2477dbea0925718389a9b&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/mcp_service/chart/plugins/interactive_pivot.py
   **Line:** 95:100
   **Comment:**
        *Logic Error: The pivot state never identifies which grouped dimensions 
are temporal: setting only `time_grain_sqla` is insufficient because the form 
data does not include `granularity_sqla` or `temporal_columns_lookup`. As a 
result, `time_grain` is ignored or cannot be applied to the intended row/column 
dimensions, so generated pivots with temporal grouping do not honor the 
requested grain.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve 
this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask 
user if the user wants to fix the rest of the comments as well. if said yes, 
then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43480&comment_hash=84ebda3fc179dcd794af33efc285d2104d422249f888b6758ec9bb4f5592381d&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43480&comment_hash=84ebda3fc179dcd794af33efc285d2104d422249f888b6758ec9bb4f5592381d&reaction=dislike'>👎</a>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to