教學:建立狀態更新工作流程

在這個端對端教學中,你會建立一個跨解式任務流程,追蹤專案狀態、將更新寫回資料庫,並將 Power BI 報告的通知貼到 Microsoft Teams。 該解決方案會完整記錄所有狀態更新,讓你能追蹤專案狀態隨時間的變化。 本教學示範如何將資料寫回與外部 API 呼叫結合,建立完整的通訊工作流程。

在本教學課程中,您將瞭解如何:

  • 在 Fabric 中建立一個 SQL 資料庫,並設有專案與狀態追蹤表,以維持完整歷史。
  • 設置一個變數函式庫來分別儲存設定。
  • 設定使用者資料功能,更新狀態、請求更新,以及向 Teams 發布通知。
  • 可選擇設置 Lakehouse 捷徑,並使用物化湖視圖來實現 Direct Lake 視圖。
  • 透過資料功能按鈕,將使用者資料功能與 Power BI 報告整合。

如果您沒有現有的 Fabric 容量, 請啟動 Fabric 試用版。

先決條件

  • Power BI Desktop。 如果您沒有在裝置上安裝Power BI Desktop,請遵循 取得Power BI Desktop中的指示。
  • 一個 Microsoft Teams 頻道,你可以有權限新增 webhooks。

概觀

此教學建立專案追蹤解決方案,使用者可直接從 Power BI 報告更新專案狀態。 當使用者更新狀態時,系統會:

  1. 將新狀態寫入 SQL 資料庫,並完整記錄所有狀態更新的歷史。
  2. 向 Microsoft Teams 發送自適應卡通知。
  3. 刷新報告以顯示更新後的資料。

備註

更新會在資料函式完成且報告頁面重新整理後出現在報告中——通常在幾秒內,視函式執行時間、查詢回應時間及網路狀況等因素而定。 在匯入儲存模式下,必須先重新整理語意模型,更新的數值才會顯示。

使用者流程

工作流程在報告使用者間形成持續的反饋迴圈:

  1. 透過 Teams 從報告請求更新 — 使用者在報告中選擇專案並發送狀態更新請求。 請求會發佈到 Teams,並附上報告連結。

  2. 在 Teams 收到通知並開啟報告 — 專案負責人會在 Teams 中看到通知,並選擇連結以開啟報告。

  3. 更新報告狀態 — 專案負責人選擇專案、選擇新狀態、新增備註,並選擇更新按鈕。

  4. 查看更新並發送通知 — 報告會顯示新狀態,並會向 Teams 發布通知確認變更。

建築

該解決方案將這些元件在 Microsoft Fabric 內連結起來:

組件 Purpose
Fabric SQL 資料庫 儲存專案與狀態更新紀錄,並包含完整歷史。 包含 Project 表格、Status updates 表格(維護所有變更的完整歷史)及 Project status 檢視。
湖畔屋 (選用) 提供直接湖檢視的 SQL 資料庫資料表捷徑。 當你需要實體化的湖景來做分析時,就用它。
變數函式庫 儲存組態值,如 Teams 的 webhook URL 與報告 URL。 更新數值時不必重新發佈函式。
使用者資料功能 Python 函式負責寫回 SQL 並透過自適應卡片向 Microsoft Teams 發布通知。
Power BI 語意模型 定義資料模型、關係與度量。 在 Power BI Desktop 中用報告建置,但在 Power BI 服務中作為獨立項目存在。
Power BI 報告 使用者介面讓使用者瀏覽專案、選擇新狀態,並透過資料功能按鈕觸發更新。
Microsoft Teams 接收帶有狀態變更及回報連結的自適應卡通知。

資料有兩個方向流動:

  • 讀取路徑:Power BI 會從 SQL 資料庫(透過 DirectQuery)或 Lakehouse(透過 Direct Lake)讀取資料,以顯示目前專案狀態。
  • 寫入路徑:當使用者選擇資料函式按鈕時,Power BI 會呼叫使用者資料函式,該函式會寫入 SQL 資料庫並發佈到 Teams。

建立 SQL 資料庫

此情境使用專案追蹤資料。 請依照「 在 Fabric 建立 SQL 資料庫 」中的步驟,在你的 Fabric 工作區建立新的 SQL 資料庫。

建立資料庫資料表

  1. 在你的 SQL 資料庫中,開啟一個新的查詢視窗。

  2. 執行以下 SQL 腳本來建立專案資料表:

    CREATE TABLE [Project] (
        [Project id] INT NOT NULL,
        [Project name] NVARCHAR(200) NOT NULL,
        [Product name] NVARCHAR(200),
        [Description] NVARCHAR(4000),
        [Priority] NVARCHAR(20),
        [Start date] DATE,
        [Target end date] DATE,
        [Budget] DECIMAL(18,2),
        [Project manager] NVARCHAR(100),
        [Department] NVARCHAR(100),
        [Created date] DATETIME2,
        [Created by] NVARCHAR(100),
        [Is active] BIT,
        CONSTRAINT PK_Project PRIMARY KEY NONCLUSTERED ([Project id])
    );
    
  3. 建立狀態更新表以追蹤狀態隨時間的變化:

    CREATE TABLE [Status updates] (
        [Update id] INT NOT NULL,
        [Project id] INT NOT NULL,
        [Status] NVARCHAR(50) NOT NULL,
        [Updated date] DATETIME2 NOT NULL,
        [Updated by] NVARCHAR(100) NOT NULL,
        [Notes] NVARCHAR(4000),
        CONSTRAINT PK_StatusUpdates PRIMARY KEY NONCLUSTERED ([Update id])
    );
    
  4. 建立一個檢視,回傳每個專案的最新狀態:

    CREATE VIEW [Project status] AS
    SELECT 
        p.[Project id],
        p.[Project name],
        COALESCE(ls.[Latest status], 'Not Started') AS [Latest status],
        ls.[Latest notes]
    FROM [Project] p
    LEFT JOIN (
        SELECT 
            [Project id],
            [Status] AS [Latest status],
            [Notes] AS [Latest notes],
            ROW_NUMBER() OVER (PARTITION BY [Project id] ORDER BY [Update id] DESC) AS RowNum
        FROM [Status updates]
    ) ls ON p.[Project id] = ls.[Project id] AND ls.RowNum = 1;
    
  5. 插入範例專案資料:

    INSERT INTO [Project] ([Project id], [Project name], [Product name], [Description], [Priority], [Start date], [Target end date], [Budget], [Project manager], [Department], [Created date], [Created by], [Is active])
    VALUES
    (1, 'Best Practices with Power BI - FabCon Atlanta', 'FabCon Atlanta', 'Session covering Power BI best practices for enterprise deployments', 'High', '2026-01-15', '2026-03-20', 5000.00, 'person1@somecompany.com', 'Developer Relations', '2026-01-15', 'Admin', 1),
    (2, 'Translytical Task Flows - Build', 'Microsoft Build', 'Deep dive into translytical workloads and real-time analytics patterns', 'Critical', '2026-02-01', '2026-05-19', 7500.00, 'person2@somecompany.com', 'Product Engineering', '2026-02-01', 'Admin', 1),
    (3, 'Advanced DAX Patterns - FabCon Barcelona', 'FabCon Barcelona', 'Workshop on complex DAX calculations and optimization techniques', 'High', '2026-03-01', '2026-09-15', 6000.00, 'person1@somecompany.com', 'Developer Relations', '2026-02-20', 'Admin', 1),
    (4, 'Semantic Modeling Deep Dive - Ignite', 'Microsoft Ignite', 'Comprehensive session on semantic model design and best practices', 'High', '2026-01-10', '2026-11-18', 8000.00, 'person2@somecompany.com', 'Product Engineering', '2026-01-10', 'Admin', 1),
    (5, 'Custom Visuals in Power BI - FabCon Atlanta', 'FabCon Atlanta', 'Hands-on lab for building custom visuals with the Power BI SDK', 'Medium', '2025-12-01', '2026-03-20', 4500.00, 'person1@somecompany.com', 'Developer Relations', '2025-12-01', 'Admin', 1),
    (6, 'TMDL for Version Control - Build', 'Microsoft Build', 'Session on using TMDL for semantic model source control and CI/CD', 'Critical', '2025-11-15', '2026-02-15', 5500.00, 'person2@somecompany.com', 'Product Engineering', '2025-11-15', 'Admin', 1),
    (7, 'Real-time Analytics with Power BI - Ignite', 'Microsoft Ignite', 'Showcase of Direct Lake and real-time streaming capabilities', 'High', '2026-02-10', '2026-11-18', 7000.00, 'person1@somecompany.com', 'Developer Relations', '2026-02-10', 'Admin', 1),
    (8, 'Semantic Modeling Workshop - FabCon Barcelona', 'FabCon Barcelona', 'Interactive workshop on building enterprise-grade semantic models', 'High', '2026-04-01', '2026-09-15', 6500.00, 'person2@somecompany.com', 'Product Engineering', '2026-02-25', 'Admin', 1);
    
  6. 插入範例狀態更新:

    INSERT INTO [Status updates] ([Update id], [Project id], [Status], [Updated date], [Updated by], [Notes])
    VALUES
    (1, 1, 'Not Started', '2026-01-15', 'person1@somecompany.com', 'Session abstract submitted and approved'),
    (2, 1, 'In Progress', '2026-01-25', 'person1@somecompany.com', 'Outline completed, starting slide deck'),
    (3, 1, 'In Progress', '2026-02-10', 'person1@somecompany.com', 'Demo environment setup in progress'),
    (4, 1, 'In Progress', '2026-02-25', 'person1@somecompany.com', 'First draft of presentation complete, scheduling dry run'),
    (5, 2, 'Not Started', '2026-02-01', 'person2@somecompany.com', 'Session proposal accepted for Build'),
    (6, 2, 'In Progress', '2026-02-08', 'person2@somecompany.com', 'Research phase - gathering customer scenarios'),
    (7, 2, 'In Progress', '2026-02-15', 'person2@somecompany.com', 'Architecture diagrams drafted'),
    (8, 2, 'In Progress', '2026-02-24', 'person2@somecompany.com', 'Building demo lakehouse environment'),
    (9, 3, 'Not Started', '2026-02-20', 'person1@somecompany.com', 'Call for speakers submission pending review'),
    (10, 4, 'Not Started', '2026-01-10', 'person2@somecompany.com', 'Initial brainstorming session with PM team'),
    (11, 4, 'In Progress', '2026-01-20', 'person2@somecompany.com', 'Content outline approved by leadership'),
    (12, 4, 'In Progress', '2026-02-05', 'person2@somecompany.com', 'Sample semantic models being developed'),
    (13, 5, 'Not Started', '2025-12-01', 'person1@somecompany.com', 'Lab environment requirements documented'),
    (14, 5, 'In Progress', '2025-12-15', 'person1@somecompany.com', 'SDK samples being prepared'),
    (15, 5, 'On Hold', '2026-01-10', 'person1@somecompany.com', 'Paused - waiting on SDK v5 release for new features'),
    (16, 6, 'Not Started', '2025-11-15', 'person2@somecompany.com', 'Session planning initiated'),
    (17, 6, 'In Progress', '2025-12-01', 'person2@somecompany.com', 'GitHub Actions workflow samples created'),
    (18, 6, 'In Progress', '2026-01-15', 'person2@somecompany.com', 'Dry run completed with internal team'),
    (19, 6, 'Completed', '2026-02-15', 'person2@somecompany.com', 'Session delivered at internal summit, ready for Build'),
    (20, 7, 'Not Started', '2026-02-10', 'person1@somecompany.com', 'Topic approved for Ignite breakout session'),
    (21, 7, 'In Progress', '2026-02-18', 'person1@somecompany.com', 'Eventstream demo scenarios identified'),
    (22, 7, 'In Progress', '2026-02-26', 'person1@somecompany.com', 'Direct Lake performance benchmarks in progress'),
    (23, 8, 'Not Started', '2026-02-25', 'person2@somecompany.com', 'Workshop format and duration confirmed');
    

建立一個變數函式庫

變數函式庫會將組態值與函式程式碼分開儲存。 這種分離帶來一大好處:你可以更新像是 webhook URL 或報告連結等數值,而不必編輯或重新發布你的使用者資料函式。

例如,如果您的 Teams 頻道變更或需要指向不同報告,更新變數函式庫值,變更即立即生效——無需程式碼變更。

  1. 在你的 Fabric 工作區中,選擇 + 新增項目。

  2. 向下捲動至 [開發資料] 區段,然後選取 [變數程式庫]。

  3. 將變數庫 ProjectVariables 命名並選擇 「建立」。

  4. 選擇 + 新變數 並新增以下變數:

    變數名稱 類型 說明
    TEAMS_WEBHOOK_URL 繩子 你的 Teams 傳入 webhook 的 URL
    POWERBI_REPORT_URL 繩子 您的 Power BI 報告網址(發布後新增)
  5. 加入每個變數後選擇 儲存 。

取得 Teams 的 webhook 網址

請依照 「建立 Incoming Webhook 」的步驟,為您的 Teams 頻道建立 webhook。 建立 webhook 後,複製 URL 並將其作為 TEAMS_WEBHOOK_URL 加入你的變數函式庫。

這很重要

任何擁有此網址的人都可以在你的 Teams 頻道發佈訊息。

建立使用者資料函式

建立一個使用者資料功能項目,負責狀態更新和 Teams 通知。

  1. 在你的 Fabric 工作區中,選擇 + 新項目>使用者資料函數。

  2. 將預設程式碼替換為以下 Python 程式碼:

    import fabric.functions as fn
    import logging
    from datetime import datetime
    
    udf = fn.UserDataFunctions()
    
    
    @udf.connection(argName="sqlDb", alias="ProjectTrackingDb")
    @udf.connection(argName="varLib", alias="ProjectVariables")
    @udf.function()
    def update_project_status(
        sqlDb: fn.FabricSqlConnection,
        varLib: fn.FabricVariablesClient,
        projectId: int,
        newStatus: str,
        updatedBy: str,
        notes: str,
        updatedDate: str
    ) -> str:
        """
        Updates the status of a project by inserting a new record 
        into the Status updates table and sends a Teams notification.
        """
        logging.info(f"Updating status for Project ID: {projectId}")
    
        # Parse and validate the date
        try:
            parsed_date = datetime.fromisoformat(updatedDate)
        except ValueError:
            raise fn.UserThrownError(
                f"Invalid date format. Use ISO format: '2026-02-27T14:30:00'",
                {"providedDate": updatedDate}
            )
    
        # Validate status value
        valid_statuses = ['Not Started', 'In Progress', 'On Hold', 'Completed', 'Cancelled']
        if newStatus not in valid_statuses:
            raise fn.UserThrownError(
                f"Invalid status. Must be one of: {', '.join(valid_statuses)}",
                {"providedStatus": newStatus}
            )
    
        connection = sqlDb.connect()
        cursor = connection.cursor()
    
        try:
            # Get the previous status
            cursor.execute("""
                SELECT TOP 1 [Status] 
                FROM [Status updates] 
                WHERE [Project id] = ? 
                ORDER BY [Update id] DESC
            """, (projectId,))
            prev_row = cursor.fetchone()
            previous_status = prev_row[0] if prev_row else "Not Started"
    
            # Get the next Update ID
            cursor.execute("SELECT ISNULL(MAX([Update id]), 0) + 1 FROM [Status updates]")
            next_update_id = cursor.fetchone()[0]
    
            # Verify the project exists
            cursor.execute("SELECT [Project name] FROM [Project] WHERE [Project id] = ?", (projectId,))
            project_row = cursor.fetchone()
    
            if not project_row:
                raise fn.UserThrownError(f"Project with ID {projectId} not found.")
    
            project_name = project_row[0]
    
            # Insert the new status update
            cursor.execute("""
                INSERT INTO [Status updates] 
                ([Update id], [Project id], [Status], [Updated date], [Updated by], [Notes])
                VALUES (?, ?, ?, ?, ?, ?)
            """, (next_update_id, projectId, newStatus, parsed_date, updatedBy, notes))
    
            connection.commit()
    
            # Send Teams notification
            _send_teams_update(varLib, project_name, previous_status, newStatus, updatedBy, notes)
    
            return f"Status updated for '{project_name}': {previous_status} → {newStatus}"
    
        except Exception as e:
            connection.rollback()
            raise
        finally:
            cursor.close()
            connection.close()
    
    
    def _send_teams_update(varLib, project_name, previous_status, new_status, updated_by, notes):
        """Helper function to send Teams notification."""
        import requests
        import json
    
        variables = varLib.getVariables()
        webhook_url = variables.get("TEAMS_WEBHOOK_URL")
        report_url = variables.get("POWERBI_REPORT_URL")
    
        if not webhook_url:
            return
    
        adaptive_card = {
            "type": "message",
            "attachments": [{
                "contentType": "application/vnd.microsoft.card.adaptive",
                "content": {
                    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
                    "type": "AdaptiveCard",
                    "version": "1.4",
                    "body": [
                        {
                            "type": "TextBlock",
                            "size": "Large",
                            "weight": "Bolder",
                            "text": "📋 Project Status Update"
                        },
                        {
                            "type": "FactSet",
                            "facts": [
                                {"title": "Project:", "value": project_name},
                                {"title": "Status:", "value": f"{previous_status} → {new_status}"},
                                {"title": "Updated By:", "value": updated_by}
                            ]
                        },
                        {
                            "type": "TextBlock",
                            "text": f"**Notes:** {notes}" if notes else "",
                            "wrap": True
                        }
                    ],
                    "actions": [
                        {"type": "Action.OpenUrl", "title": "View Project", "url": report_url}
                    ] if report_url else []
                }
            }]
        }
    
        requests.post(webhook_url, headers={"Content-Type": "application/json"}, 
                      data=json.dumps(adaptive_card), timeout=30)
    
    
    @udf.connection(argName="sqlDb", alias="ProjectTrackingDb")
    @udf.connection(argName="varLib", alias="ProjectVariables")
    @udf.function()
    def request_status_update(
        sqlDb: fn.FabricSqlConnection,
        varLib: fn.FabricVariablesClient,
        projectId: int,
        requestedBy: str,
        message: str
    ) -> str:
        """
        Sends a Teams notification requesting a status update for a project.
        """
        logging.info(f"Requesting status update for Project ID: {projectId}")
    
        connection = sqlDb.connect()
        cursor = connection.cursor()
    
        try:
            # Get project details
            cursor.execute("""
                SELECT [Project name], [Project manager] 
                FROM [Project] 
                WHERE [Project id] = ?
            """, (projectId,))
            project_row = cursor.fetchone()
    
            if not project_row:
                raise fn.UserThrownError(f"Project with ID {projectId} not found.")
    
            project_name = project_row[0]
            project_manager = project_row[1]
    
            # Get current status
            cursor.execute("""
                SELECT TOP 1 [Status], [Updated date]
                FROM [Status updates] 
                WHERE [Project id] = ? 
                ORDER BY [Update id] DESC
            """, (projectId,))
            status_row = cursor.fetchone()
            current_status = status_row[0] if status_row else "Not Started"
            last_updated = status_row[1].strftime("%Y-%m-%d") if status_row else "Never"
    
            # Send Teams notification
            _send_status_request(varLib, project_name, project_manager, 
                                current_status, last_updated, requestedBy, message)
    
            return f"Status update requested for '{project_name}' from {project_manager}"
    
        finally:
            cursor.close()
            connection.close()
    
    
    def _send_status_request(varLib, project_name, project_manager, current_status, 
                            last_updated, requested_by, message):
        """Helper function to send status update request via Teams."""
        import requests
        import json
    
        variables = varLib.getVariables()
        webhook_url = variables.get("TEAMS_WEBHOOK_URL")
        report_url = variables.get("POWERBI_REPORT_URL")
    
        if not webhook_url:
            return
    
        adaptive_card = {
            "type": "message",
            "attachments": [{
                "contentType": "application/vnd.microsoft.card.adaptive",
                "content": {
                    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
                    "type": "AdaptiveCard",
                    "version": "1.4",
                    "body": [
                        {
                            "type": "TextBlock",
                            "size": "Large",
                            "weight": "Bolder",
                            "text": "📢 Status Update Requested"
                        },
                        {
                            "type": "FactSet",
                            "facts": [
                                {"title": "Project:", "value": project_name},
                                {"title": "Owner:", "value": project_manager},
                                {"title": "Current Status:", "value": current_status},
                                {"title": "Last Updated:", "value": last_updated},
                                {"title": "Requested By:", "value": requested_by}
                            ]
                        },
                        {
                            "type": "TextBlock",
                            "text": f"**Message:** {message}" if message else "",
                            "wrap": True
                        }
                    ],
                    "actions": [
                        {"type": "Action.OpenUrl", "title": "Update Status", "url": report_url}
                    ] if report_url else []
                }
            }]
        }
    
        requests.post(webhook_url, headers={"Content-Type": "application/json"}, 
                      data=json.dumps(adaptive_card), timeout=30)
    
  3. 設定連接:

    • 選擇 設定 或連接面板。
    • 新增指向 Fabric SQL 資料庫的連線 ProjectTrackingDb 。
    • 新增指向你的變數函式庫的連線 ProjectVariables 。
  4. 選擇 發佈 以部署該函式。

備註

與 Power BI 資料功能按鈕一起使用的函式必須回傳一個字串()。-> str Power BI 會在函式執行後向使用者顯示此回傳值,並提供動作結果的回饋。

了解update_project_status函數

函 update_project_status 式會將新的狀態記錄寫入 SQL 資料庫,並發送 Teams 通知。 當使用者選擇報表中的更新按鈕時,會發生以下流程:

更新專案狀態時資料流的圖表:Power BI 呼叫函式,該函式會寫入 SQL 資料庫並發送 Teams 通知。

  1. Power BI 呼叫這個函式 ——資料功能按鈕會將參數(專案 ID、新狀態、筆記等)傳給使用者資料函式。

  2. 驗證輸入 - 函式會驗證日期格式,並檢查狀態值是否為允許選項之一。

  3. 查詢當前狀態 - 函式會從資料庫中取得先前的狀態和專案名稱。

  4. 插入新紀錄 - 在表格中插入 Status updates 一列,包含新的狀態、時間戳記和備註。

  5. 發送 Teams 通知 - 輔助功能 _send_teams_update 會向你的 Teams 頻道發布一張自適應卡片,顯示狀態變更。

  6. 回傳結果 - 函式回傳成功訊息,Power BI 會顯示給使用者。

了解request_status_update功能

這個 request_status_update 函式會發送 Teams 通知,請專案負責人提供狀態更新。 這個函式不會寫入資料庫——它只會傳送訊息。

請求狀態更新時資料流的圖表:Power BI 呼叫該函式,查詢專案細節並發送 Teams 通知。

  1. Power BI 呼叫函式 - 資料函式按鈕會將專案 ID、請求者名稱和訊息傳給函式。

  2. 查詢專案詳情 - 此函式會從資料庫中取得專案名稱、專案經理及當前狀態。

  3. 發送 Teams 通知 ——助手功能 _send_status_request 會在你的 Teams 頻道上發布一張自適應卡片,內含請求細節及一個「 更新專案狀態 」按鈕,該按鈕可連結回報告。

  4. 回傳結果 - 函式會回傳一則確認訊息,Power BI 會顯示給使用者。

(可選)設置 Lakehouse 捷徑以直接觀看湖景

Fabric SQL 資料庫將所有資料以 Delta 表格形式儲存在 OneLake 中,因此你可以直接在 SQL 資料庫資料表上建立 Direct Lake 語意模型。 然而,Direct Lake 無法讀取 SQL 資料庫的檢視資料,只能讀取資料表。 要用 Direct Lake 來使用視圖,先在 Lakehouse 中建立 SQL 資料庫資料表的捷徑,然後在那裡定義視圖。

建立 SQL 資料庫資料表的捷徑

  1. 在你的 Fabric 工作區中,建立一個新的 Lakehouse 並啟用結構。

  2. 在 Lakehouse Explorer 裡,右鍵點擊任何結構(例如 dbo),然後選擇 「新資料表」捷徑。

  3. 在 OneLake 目錄中,瀏覽你的 SQL 資料庫並選擇該 Project 表格。

  4. 重複此步驟以建立 Status updates 表格捷徑。

這些捷徑提供對底層 Delta 資料表的讀取存取,且不會重複資料。

截圖顯示 Lakehouse 新增捷徑和實體化湖景的選項。

建立具體化的湖景

在 Lakehouse 建立一個具體化的湖景,計算每個專案的最新狀態:

  1. 在 Lakehouse 中,選擇 「管理實體化湖泊視圖(預覽)」。

  2. 用 Spark SQL 開啟一本新的筆記本。

  3. 執行下列查詢:

    CREATE MATERIALIZED LAKE VIEW IF NOT EXISTS dbo.project_status AS
    SELECT 
        p.`Project id` AS ProjectId,
        p.`Project name` AS ProjectName,
        COALESCE(ls.LatestStatus, 'Not Started') AS LatestStatus,
        ls.LatestNotes
    FROM dbo.Project p
    LEFT JOIN (
        SELECT 
            `Project id` AS ProjectId,
            `Status` AS LatestStatus,
            `Notes` AS LatestNotes,
            ROW_NUMBER() OVER (PARTITION BY `Project id` ORDER BY `Update id` DESC) AS RowNum
        FROM dbo.`Status updates`
    ) ls ON p.`Project id` = ls.ProjectId AND ls.RowNum = 1;
    
  4. 請選擇「 排程>開啟 」並設定頻率來排程檢視刷新。

截圖顯示實體化的湖景時間表與建立選項。

備註

SQL 資料庫仍然是使用者資料函式的寫入目標。 Lakehouse 捷徑透過實體化的湖景提供唯讀存取分析資料。

建立 Power BI 報告

您可以使用 DirectQuery 或 Direct Lake 連接您的資料:

  • DirectQuery 到 SQL 資料庫:即時資料支援透過使用者定義的函式寫回。
  • Direct Lake 到 SQL 資料庫資料表:Fabric SQL 資料庫在 OneLake 中以 Delta 資料表儲存資料,因此 Direct Lake 可以直接讀取資料表。
  • 透過 Lakehouse 直接存取 Lake(用於視圖):Direct Lake 無法讀取 SQL 資料庫的視圖。 要用 Direct Lake 的視圖,先在 Lakehouse 裡建立 SQL 資料庫資料表的捷徑,然後在那裡定義具體化的湖泊視圖。

小提示

也可以使用匯入模式——儲存模式沒有限制。 在匯入時,語意模型必須先更新,更新的值才會出現在報告中。

選項A:透過DirectQuery連接

  1. 開啟 Power BI 桌面。

  2. 選擇 OneLake 目錄。

  3. 找到你的 Fabric SQL 資料庫。

  4. 選擇 連接 SQL 分析端點。

  5. 選擇 Project、 Status updates,以及 Project status 表格/檢視。

  6. 當被要求儲存模式時,選擇 DirectQuery。

截圖顯示 Power BI 中 DirectQuery 語意模型。

選項B:透過 Direct Lake 連接(用於分析效能)

  1. 在 Power BI 服務中,選擇 建立>OneLake 目錄。

  2. 找到你的湖畔小屋。

  3. 選擇捷徑表(Project, Status updates)及物化湖視圖(project_status)。

  4. 在網頁建模體驗中編輯語意模型,加入衡量與關係。

備註

在 Direct Lake 中,實體化湖景的欄位名稱沒有空格(例如, ProjectId 取代 Project id)。 將語意模型中的欄位重新命名,使其與你的度量相符。

顯示 Power BI 中 Direct Lake 語意模型的截圖。

建立狀態選項計算表

建立一個計算出的表格,提供按鈕切片器的狀態值。 請在 Power BI Desktop 執行這個 TMDL 腳本:

createOrReplace

	table 'Status Options'

		column Status
			summarizeBy: none
			isNameInferred
			sourceColumn: [Status]
			sortByColumn: 'Sort Order'

		column Description
			summarizeBy: none
			isNameInferred
			sourceColumn: [Description]

		column 'Sort Order'
			isHidden
			formatString: 0
			summarizeBy: sum
			isNameInferred
			sourceColumn: [Sort Order]

		column 'Status Color'
			summarizeBy: none
			isNameInferred
			sourceColumn: [Status Color]

		partition 'Status Options' = calculated
			mode: import
			source =
				DATATABLE(
				    "Status", STRING,
				    "Description", STRING,
				    "Sort Order", INTEGER,
				    "Status Color", STRING,
				    {
				        { "Not Started", "Project has been created but work has not begun", 1, "#808080" },
				        { "In Progress", "Active work is being performed on the project", 2, "#0078D4" },
				        { "On Hold", "Project is paused pending resources, decisions, or dependencies", 3, "#FFB900" },
				        { "Completed", "All project deliverables have been finished", 4, "#107C10" },
				        { "Cancelled", "Project has been terminated and will not be completed", 5, "#D13438" }
				    }
				)

建立支持措施

建立一個計算表來記錄支援資料功能按鈕的測量值。 請在 Power BI Desktop 執行這個 TMDL 腳本:

createOrReplace

	table 'Translytical task flow'

		/// Generates a preview of the Teams notification that will be sent when the user updates the status. Shows a warning if required selections are missing.
		measure 'Preview of status update' = ```
				VAR _ProjectId = SELECTEDVALUE(Project[Project id], 0)
				VAR _ProjectName = SELECTEDVALUE(Project[Project name], "")
				VAR _PreviousStatus = [Latest Status]
				VAR _NewStatus = SELECTEDVALUE('Status Options'[Status], "N/A")
				VAR _UpdatedBy = [Updated by]
				VAR _UpdatedDate = FORMAT(NOW(), "YYYY-MM-DD HH:mm")
				VAR _NL = UNICHAR(10)
				RETURN 
				IF(_ProjectId = 0 || _NewStatus = "N/A",
				    "⚠️ Select a project and new status to preview",
				    "📋 Teams Notification Preview" & _NL &
				    "━━━━━━━━━━━━━━━━━━━━" & _NL &
				    "Project: " & _ProjectName & _NL &
				    "Status: " & _PreviousStatus & " → " & _NewStatus & _NL &
				    "Updated By: " & _UpdatedBy & _NL &
				    "Date: " & _UpdatedDate & _NL &
				    "Notes: See above" & _NL &
				    "━━━━━━━━━━━━━━━━━━━━" & _NL &
				    "📨 This will be sent to Teams"
				)
				```

		/// Returns the email address of the current user. Used to track who made each status update.
		measure 'Updated by' = USERPRINCIPALNAME()

		/// Returns the most recent notes for the selected project. Only evaluates when a project is in scope.
		measure 'Latest notes' =
				IF(ISINSCOPE(Project[Project name]),
				LASTNONBLANKVALUE('Status updates'[Update id], MAX('Status updates'[Notes])),
				BLANK())

		/// Returns the most recent status for the selected project by finding the last non-blank status value.
		measure 'Latest status' =
				IF(HASONEVALUE(Project[Project id]),
				LASTNONBLANKVALUE('Status updates'[Update id], MAX('Status updates'[Status])),
				BLANK())

		/// Returns the Project ID when a single project is selected. Used as a parameter for the update_project_status and request_status_update functions.
		measure 'Selected project id' = SELECTEDVALUE(Project[Project id])
			formatString: 0

		/// Returns today's date in ISO format. Used as the timestamp for status updates.
		measure 'Updated date' = FORMAT(TODAY(), "yyyy-mm-dd")

		/// Provides dynamic text for the update button showing the selected project and new status.
		measure 'Update status button text' = "Update the status of " & SELECTEDVALUE(Project[Project name]) & " to " & SELECTEDVALUE('Status Options'[Status])

		column Value
			isHidden
			formatString: 0
			summarizeBy: sum
			isNameInferred
			sourceColumn: [Value]

		partition 'Translytical task flow' = calculated
			mode: import
			source = {1}

備註

此腳本建立帶有隱藏欄位的 Translytical task flow 表格。 隱藏所有欄位會將其轉換成度量表,該表會顯示一個特殊圖示,且總是出現在資料面板頂端,方便存取。

這些措施有多重目的:

量值 Purpose
Selected project id 當選取單一專案列時,會擷取專案 ID。 作為參數傳遞給使用者資料函式。
Updated by 透過 USERPRINCIPALNAME() 回傳目前使用者的電子郵件。 追蹤每項狀態更新的人。
Updated date 以 ISO 格式yyyy-mm-dd回傳函數時間戳參數的今日日期。
Update status button text 提供動態按鈕標籤,顯示所選專案及新狀態(例如「更新 Session ABC 狀態為進行中」)。
Latest status 顯示專案的最新狀態,用 LASTNONBLANKVALUE 來查找狀態更新表中最後一項。
Latest notes 顯示專案的最新筆記。 僅在特定專案屬於範疇時進行評估。
Preview of status update 在發送前會產生 Teams 通知的預覽,幫助使用者確認變更。 若缺少選項,會顯示警告。

設計報表

報告版面引導使用者完成清晰的工作流程:選擇專案、選擇新狀態、新增備註,然後執行更新。

截圖顯示完整的 Power BI 報告設計,包含專案表格、狀態切片器、筆記輸入和動作按鈕。

建立專案表

  1. 新增 表格 元素以顯示專案資訊。

  2. 將以下欄位從你的資料中加入:

    • Product name
    • Project name
    • Target end date
    • Description
    • Latest status (來自狀態或專案狀態表格/檢視畫面)
    • Latest notes
  3. 將標題設為 1) 選擇一個專案要更新。

  4. 請依 目標結束日期 由低到高排序,以優先顯示即將到來的截止日期。

建立按鈕切片器來選擇狀態

  1. 新增「按鈕切片器」視覺效果。

  2. 在 「值 」欄位,加上 Status Options[Status]。

  3. 在 標籤 欄位中,新增 FIRST(Status Options[Description]) 以顯示每個狀態下方的描述。

  4. 在 格式 面板中:

    • 將風格設定為卡片。
    • 將 方向 設定為 水平。
    • 將 最大格子 設為 5 格(每個狀態各一格)。
  5. 設定條件格式,讓每張卡片依欄位 Status Color 著色。

  6. 將標題設為 2) 選擇一個新的狀態。

新增筆記的輸入切片工具

  1. 新增 輸入選擇器,讓使用者輸入有關狀態更新的備註。

  2. 將標題設為 3)新增此狀態更新的備註。

  3. 新增一個輸入切片器,用於請求狀態更新按鈕所使用的訊息欄位。

  4. 將標題設為 或者發送訊息到 Teams 頻道。

小提示

給每個輸入切片器一個描述性的標題。 當你設定資料功能按鈕時,切片器會在參數選單中按標題排列,這有助於更方便地辨識正確的切片器。 設定完成後,如果需要,你可以在報表畫布上隱藏標題。

新增預覽表

  1. 新增一個只有一欄的 表格 視覺化:衡量值 [Preview of status update] 。

  2. 將標題設為 預覽更新。

這會讓使用者在發送 Teams 通知前看到他們的 Teams 通知會是什麼樣子。

新增資料功能按鈕

新增兩個按鈕:一個更新狀態,一個請求狀態更新。

更新狀態按鈕

  1. 在 「插入 」標籤中,選擇 按鈕>資料功能。

  2. 在 格式 面板中,設定按鈕文字:

    • 將 預設文字 設定為你的 [Update status button text] 度量,以便動態標註。
    • 把 停用文字 設成靜態文字,比如「先選擇專案、新狀態,並先新增備註」。
  3. 在動作中,選擇資料功能旁的條件格式化(fx)按鈕。 OneLake目錄已開啟。

  4. 找到並選取您已發佈的 update_project_status 函式。

    選擇函式後, 格式 面板會顯示其 工作區、 函式集和函式名稱,作為唯讀細節。

  5. 將函數參數對應

    參數 繫結類型 被綁定
    projectId 量值 [Selected project id] 衡量
    newStatus 切片器 按鈕切片視圖(啟用自動清除)
    updatedBy 量值 [Updated by] 衡量
    notes 切片器 輸入切片器視覺化(啟用自動清除)
    updatedDate 量值 [Updated date] 衡量
  6. 在「 格式 」面板的 「行動」中,啟用 「成功結果後重新整理報告」。 此設定會在函式成功執行後自動刷新報告頁面。

    小提示

    啟用 自動清除 切片軟體參數,讓按鈕切片器和筆記文字在使用者觸發功能後重置。

備註

「 成功結果後重新整理報告 」的切換,只有在函式成功執行時才會重新整理報告頁面。 對於 DirectQuery 和 Direct Lake 儲存模式,更新後的視覺化會透過語意模型向來源發送查詢,並回傳最新資料——通常在幾秒內,但確切時間會依資料函式執行時間、查詢回應時間及網路狀況等因素而定。 匯入模式中,語意模型必須分別刷新,更新值才會出現在報告中。

截圖顯示 Power BI 報告中更新專案狀態按鈕。

請求狀態更新按鈕

  1. 新增另一個 按鈕>資料功能。

  2. 在 格式 面板中,設定按鈕文字:

    • 將 預設文字 設為靜態文字,例如「將 Teams 訊息傳送到頻道」。
    • 將 「停用」文字 設定為「先選擇專案並輸入訊息」。
  3. 在動作中,選擇資料功能旁的條件格式化(fx)按鈕。 OneLake目錄已開啟。

  4. 找到並選取您已發布的 request_status_update 函式。

    選擇函式後, 格式 面板會顯示其 工作區、 函式集和函式名稱,作為唯讀細節。

  5. 將函數參數對應

    參數 繫結類型 被綁定
    projectId 量值 [Selected project id] 衡量
    requestedBy 量值 [Updated by] 衡量
    message 切片器 輸入切片器視覺化(啟用自動清除)
  6. 可選擇性地在「動作」的格式面板中啟用「成功後刷新報告」。

截圖顯示 Power BI 報告中傳送 Teams 訊息按鈕。

設定動態按鈕文字

在資料功能按鈕上使用動態文字,讓使用者清楚看到選擇按鈕時會發生什麼動作。 按鈕不顯示像「更新」這樣的通用標籤,而是顯示情境特定的文字,例如「將 ABC 會話狀態更新為進行中」。

要設定動態按鈕文字:

  1. 建立一個衡量指標來產生按鈕標籤。 例如,此指標結合了所選專案名稱與新狀態:

    Update status button text = 
        "Update the status of " & SELECTEDVALUE(Project[Project name]) & " to " & SELECTEDVALUE('Status Options'[Status])
    
  2. 在資料功能按鈕的 格式 選區中,展開 按鈕>文字。

  3. 將 預設文字 設定為你的動態度量([Update status button text])。

  4. 將 停用文字 設為靜態文字,告訴使用者需要選取哪些內容(例如「選擇專案、新狀態,並先新增備註」)。

按鈕會顯示停用的文字,直到所有所需參數都達到數值。 使用者完成選擇後,按鈕會顯示動態文字,描述具體動作。

截圖顯示按鈕格式窗格,設定動態文字時使用指標作為預設文字,停用狀態使用靜態文字。

(可選)新增鑽孔按鈕和頁面

你可以新增一個穿透頁面,以顯示所選專案的完整狀態更新歷史。

  1. 在 「插入 」標籤中,選擇「 按鈕>空白」。

  2. 在「Format」面板的「Button」下,設定文字:

    • 預設文字:「查看所有狀態更新」
    • 停用文字:「選擇專案以查看所有狀態更新」
  3. 在 動作中啟用該動作並設定:

    • 類型: 鑽孔式
    • 目的地:選擇您的狀態歷史頁面(在下一步建立)
  4. 新增一個頁面並命名 為狀態更新歷史。

  5. 在頁面的 格式 面板中,展開 頁面資訊 並啟用 鑽取 功能。 加入 Project[Product name] 作為鑽取字段。

  6. 新增視覺化以顯示狀態歷史:

    • 卡片:狀態更新總數
    • 按鈕切割器:依狀態分類
    • 表格:所有狀態更新(更新編號、更新日期、狀態、備註、更新人)
    • 線圖:隨時間更新活動
  7. 新增 返回按鈕, 讓使用者能返回主報告頁面。 在 「插入 」標籤中,選擇「 按鍵>返回」。

發佈報表

  1. 儲存你的報告並發佈到 Power BI 服務。

  2. 複製報表網址,然後將其作為變數加入到你的變數庫中 POWERBI_REPORT_URL。

測試工作流程

測試請求狀態更新流程

發佈後,您可以使用跨分析任務流程來請求狀態更新:

截圖顯示請求狀態更新的編號步驟:1) 選擇專案,2) 輸入訊息,3) 選擇將 Teams 訊息傳送至頻道,4) 查看確認,5) Teams 通知顯示,並顯示更新專案狀態按鈕。

  1. 選擇要更新的專案 - 在表格中選擇專案列來設定篩選條件。

  2. 或者向 Teams 頻道發送訊息 ——在輸入切片器中輸入訊息(例如:「我們可以收到最新消息嗎?」)。

  3. 選擇 「將 Teams 訊息傳送到頻道 」按鈕。

  4. 當動作成功完成時,會顯示「 請求已提交 的確認」。

  5. 請查看你的 Teams 頻道,尋找專案 狀態更新 自適應卡,並附上請求細節。

  6. 專案負責人可以在自適應卡中選擇 「更新專案狀態 」來開啟報告並更新狀態。

一張顯示 Teams 中 Adaptive Card 要求更新狀態通知的截圖,並帶有「更新專案狀態」按鈕。

測試更新狀態流程

發佈後,你可以使用轉解任務流程來更新專案狀態:

更新專案狀態的編號步驟截圖:1) 選擇專案,2) 選擇狀態,3) 新增備註,4) 選擇更新,5) 查看確認,6) Teams 通知出現。

  1. 選擇要更新的專案 - 在表格中選擇專案列來設定篩選條件。

  2. 新的狀態是什麼? - 使用按鈕切片器選擇新狀態(例如「 進行中」。

  3. 新增此狀態更新的備註 - 在輸入切片器中輸入備註(例如「開始錄製示範」)。

  4. 選擇 「更新 」按鈕,將狀態變更寫回湖屋並發送 Teams 通知。

  5. 當動作成功完成時,會顯示「 請求已提交 的確認」。

  6. 請查看你的 Teams 頻道,尋找專案 狀態更新 自適應卡,並附上狀態變更的詳細資訊。

在 Teams 中顯示狀態更新後自適應卡片通知的截圖。

Translytical 工作流程

報告視覺化

DAX 函式

Fabric 資料

Microsoft Teams