<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
  <channel>
    <title>Translytical Task Flow Gallery topics</title>
    <link>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/bd-p/pbi_translyticalgallery</link>
    <description>Translytical Task Flow Gallery topics</description>
    <pubDate>Fri, 04 Dec 2026 18:04:45 GMT</pubDate>
    <dc:creator>pbi_translyticalgallery</dc:creator>
    <dc:date>2026-12-04T18:04:45Z</dc:date>
    <item>
      <title>Generic Commentary Writeback in Power BI using Fabric User Data Functions</title>
      <link>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Generic-Commentary-Writeback-in-Power-BI-using-Fabric-User-Data/m-p/5288670#M39</link>
      <description>&lt;P class=""&gt;Business users often need to explain &lt;EM&gt;why&lt;/EM&gt; a number changed, not just view the number.&lt;/P&gt;&lt;P class=""&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;These explanations usually end up in Excel, emails, Teams messages, or PowerPoint and become disconnected from the actual Power BI report context.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;I built a generic commentary writeback framework using &lt;STRONG&gt;Microsoft Fabric User Data Functions&lt;/STRONG&gt;.&lt;/P&gt;&lt;P class=""&gt;The idea is simple:&lt;/P&gt;&lt;PRE&gt;&lt;STRONG&gt;Selected business context + metric + period = one unique comment context.&lt;/STRONG&gt;&lt;/PRE&gt;&lt;P&gt;&amp;nbsp;&lt;img /&gt;&lt;/P&gt;&lt;P&gt;A user can select a period and metric, choose a row in a matrix or use report slicers, enter a comment, and save it directly from Power BI.&lt;/P&gt;&lt;P&gt;For example:&lt;/P&gt;&lt;P&gt;&lt;span class="lia-unicode-emoji" title=":direct_hit:"&gt;🎯&lt;/span&gt;&lt;EM&gt;Target achieved at 104.5% — performance is above plan due to stronger volume and improved customer mix.&lt;/EM&gt;&lt;/P&gt;&lt;H3&gt;&lt;STRONG&gt;What makes it generic?&lt;/STRONG&gt;&lt;/H3&gt;&lt;P&gt;Instead of hardcoding Cost Center, Profit Center, Customer, Material, and every other dimension into the writeback function, Power BI dynamically creates a &lt;STRONG&gt;grain key&lt;/STRONG&gt; from the current report context.&lt;/P&gt;&lt;P&gt;This means the same framework can support commentary at different levels, such as Cost Center + Profit Center or Cost Center + Profit Center + Material, without redesigning the writeback function for every combination.&lt;/P&gt;&lt;H3&gt;&lt;STRONG&gt;Versioning and audit&lt;/STRONG&gt;&lt;/H3&gt;&lt;P&gt;Comments are stored in a versioned backend table. Every insert, update, or delete creates a new version.&lt;/P&gt;&lt;P&gt;A latest-comment view returns only the current active comment to Power BI, while the complete history remains available for audit and traceability.&lt;/P&gt;&lt;P&gt;I used Databricks as the backend for this demo, but the same design can be extended to Fabric Warehouse, Azure SQL, or another suitable SQL-based storage layer.&lt;/P&gt;&lt;H3&gt;&lt;STRONG&gt;Why I built this&lt;/STRONG&gt;&lt;/H3&gt;&lt;P&gt;The goal was to bring business commentary closer to the data itself and make explanations contextual, reusable, and auditable.&lt;/P&gt;&lt;P&gt;This pattern can be useful for finance variance commentary, forecast assumptions, sales performance notes, planning annotations, and other enterprise reporting scenarios.&lt;/P&gt;&lt;P&gt;The most interesting part for me was using &lt;STRONG&gt;Fabric User Data Functions with Power BI Translytical Task Flows&lt;/STRONG&gt; to turn a report from a read-only analytical experience into an actionable workflow.&lt;/P&gt;&lt;P&gt;&lt;img /&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;EM&gt;Would love to hear how others are approaching commentary and writeback scenarios in Power BI and Microsoft Fabric.&lt;/EM&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;a data-lia-user-mentions="" data-lia-user-uid="29711" data-lia-user-login="slindsay" class="lia-mention lia-mention-user"&gt;slindsay&lt;/a&gt;&amp;nbsp;&lt;a data-lia-user-mentions="" data-lia-user-uid="1261729" data-lia-user-login="Praful_Potphode" class="lia-mention lia-mention-user"&gt;Praful_Potphode&lt;/a&gt;&amp;nbsp;&lt;a data-lia-user-mentions="" data-lia-user-uid="685422" data-lia-user-login="tharunkumarRTK" class="lia-mention lia-mention-user"&gt;tharunkumarRTK&lt;/a&gt;&amp;nbsp;&lt;a data-lia-user-mentions="" data-lia-user-uid="1345926" data-lia-user-login="Natarajan_M" class="lia-mention lia-mention-user"&gt;Natarajan_M&lt;/a&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Mon, 13 Jul 2026 04:33:15 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Generic-Commentary-Writeback-in-Power-BI-using-Fabric-User-Data/m-p/5288670#M39</guid>
      <dc:creator>hardiksri</dc:creator>
      <dc:date>2026-07-13T04:33:15Z</dc:date>
    </item>
    <item>
      <title>Intelliventra – Smart Event Management Application</title>
      <link>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Intelliventra-Smart-Event-Management-Application/m-p/4812085#M30</link>
      <description>&lt;P&gt;&lt;STRONG&gt;Intelliventra&lt;/STRONG&gt; lets participants easily browse all sessions and add them to their personal agenda. Attendees can view session details such as time, room, track, and speaker. The page also allows attendees to add,remove sessions. It is designed to be simple, clear, and works for any event, from small workshops to large conferences.&lt;/P&gt;</description>
      <pubDate>Mon, 01 Sep 2025 20:37:35 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Intelliventra-Smart-Event-Management-Application/m-p/4812085#M30</guid>
      <dc:creator>PrachiJain_2025</dc:creator>
      <dc:date>2025-09-01T20:37:35Z</dc:date>
    </item>
    <item>
      <title>Accounting Process Flow Automation by Translytical Flow</title>
      <link>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Accounting-Process-Flow-Automation-by-Translytical-Flow/m-p/4811909#M29</link>
      <description>&lt;P&gt;Sales Commission Process in a Marketing Company&lt;/P&gt;&lt;P&gt;In an organization offering marketing solutions to lending institutions, the commission process for a sales order was complex, relying on shared spreadsheets with inputs and approvals from multiple departments. Implementing a live dashboard with a translytical flow streamlined the process, reducing the workflow time from 10 days to 2 days.&lt;/P&gt;&lt;P&gt;Commissions are paid based on:&lt;/P&gt;&lt;UL&gt;&lt;LI&gt;# of sales appointments&lt;/LI&gt;&lt;LI&gt;Other data from Zohobooks&lt;/LI&gt;&lt;LI&gt;Approval from CFO&lt;/LI&gt;&lt;LI&gt;Final Processing of Payment by finance/accountant&lt;/LI&gt;&lt;/UL&gt;&lt;P&gt;With a set of dash boards powered by an SQL database with translytical functions , we made the&amp;nbsp; recording of sales appointments and approvals at multiple steps and the subsequent sales commission payment kickoff and notification seamless. Direct query is used for quick reflection of the write backs (apointment times and apporval status changes). User data functions are called from power BI buttons to achieve this. Power automate flow is used to&amp;nbsp; send email notifications which is invoked by a button click from dashbaord. The users were most thrilled because they could see the commission outflow immediately reflected in the Cashflow forecasts.&lt;BR /&gt;&lt;BR /&gt;Process Flow:&lt;BR /&gt;Sales appointments enetered by respective sales people -&amp;gt;Approval from CFO -&amp;gt;Processing of sales commission payment by accountant and sending email notifications&lt;BR /&gt;&lt;BR /&gt;User Data Function used given here:&lt;BR /&gt;&lt;BR /&gt;&lt;BR /&gt;&lt;BR /&gt;&lt;/P&gt;&lt;DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;import&lt;/SPAN&gt;&lt;SPAN&gt; fabric.functions &lt;/SPAN&gt;&lt;SPAN&gt;as&lt;/SPAN&gt;&lt;SPAN&gt; fn&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;import&lt;/SPAN&gt;&lt;SPAN&gt; logging&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;from&lt;/SPAN&gt;&lt;SPAN&gt; datetime &lt;/SPAN&gt;&lt;SPAN&gt;import&lt;/SPAN&gt;&lt;SPAN&gt; datetime&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;udf = fn.UserDataFunctions()&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;@udf&lt;/SPAN&gt;&lt;SPAN&gt;.connection(argName=&lt;/SPAN&gt;&lt;SPAN&gt;"sqlDB1"&lt;/SPAN&gt;&lt;SPAN&gt;, alias=&lt;/SPAN&gt;&lt;SPAN&gt;"TWFDB"&lt;/SPAN&gt;&lt;SPAN&gt;)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;@udf&lt;/SPAN&gt;&lt;SPAN&gt;.function()&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;def&lt;/SPAN&gt;&lt;SPAN&gt; create_appointment(&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; sqlDB1: fn.FabricSqlConnection,&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; fullname: &lt;/SPAN&gt;&lt;SPAN&gt;str&lt;/SPAN&gt;&lt;SPAN&gt;,&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; startdate: &lt;/SPAN&gt;&lt;SPAN&gt;str&lt;/SPAN&gt;&lt;SPAN&gt;,&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; starttime: &lt;/SPAN&gt;&lt;SPAN&gt;str&lt;/SPAN&gt;&lt;SPAN&gt;,&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; durationminutes: &lt;/SPAN&gt;&lt;SPAN&gt;int&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;) -&amp;gt; &lt;/SPAN&gt;&lt;SPAN&gt;str&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;if&lt;/SPAN&gt;&lt;SPAN&gt; sqlDB1 &lt;/SPAN&gt;&lt;SPAN&gt;is&lt;/SPAN&gt; &lt;SPAN&gt;None&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;raise&lt;/SPAN&gt;&lt;SPAN&gt; fn.UserThrownError(&lt;/SPAN&gt;&lt;SPAN&gt;"Connection injection failed. Check alias 'TWFDB' in UDF connections."&lt;/SPAN&gt;&lt;SPAN&gt;)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;# Validate / normalize&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;if&lt;/SPAN&gt; &lt;SPAN&gt;not&lt;/SPAN&gt;&lt;SPAN&gt; fullname &lt;/SPAN&gt;&lt;SPAN&gt;or&lt;/SPAN&gt;&lt;SPAN&gt; fullname.strip() == &lt;/SPAN&gt;&lt;SPAN&gt;""&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;raise&lt;/SPAN&gt;&lt;SPAN&gt; fn.UserThrownError(&lt;/SPAN&gt;&lt;SPAN&gt;"Full name is required."&lt;/SPAN&gt;&lt;SPAN&gt;)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;try&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; dur = &lt;/SPAN&gt;&lt;SPAN&gt;int&lt;/SPAN&gt;&lt;SPAN&gt;(durationminutes)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;except&lt;/SPAN&gt;&lt;SPAN&gt; ValueError:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;raise&lt;/SPAN&gt;&lt;SPAN&gt; fn.UserThrownError(&lt;/SPAN&gt;&lt;SPAN&gt;"Duration must be a whole number of minutes."&lt;/SPAN&gt;&lt;SPAN&gt;)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;if&lt;/SPAN&gt;&lt;SPAN&gt; dur &amp;lt;= &lt;/SPAN&gt;&lt;SPAN&gt;0&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;raise&lt;/SPAN&gt;&lt;SPAN&gt; fn.UserThrownError(&lt;/SPAN&gt;&lt;SPAN&gt;"Duration must be &amp;gt; 0."&lt;/SPAN&gt;&lt;SPAN&gt;)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; t = (starttime &lt;/SPAN&gt;&lt;SPAN&gt;or&lt;/SPAN&gt; &lt;SPAN&gt;""&lt;/SPAN&gt;&lt;SPAN&gt;).strip() &lt;/SPAN&gt;&lt;SPAN&gt;or&lt;/SPAN&gt; &lt;SPAN&gt;"09:00:00"&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;if&lt;/SPAN&gt;&lt;SPAN&gt; t.count(&lt;/SPAN&gt;&lt;SPAN&gt;":"&lt;/SPAN&gt;&lt;SPAN&gt;) == &lt;/SPAN&gt;&lt;SPAN&gt;1&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; t += &lt;/SPAN&gt;&lt;SPAN&gt;":00"&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;elif&lt;/SPAN&gt;&lt;SPAN&gt; t.count(&lt;/SPAN&gt;&lt;SPAN&gt;":"&lt;/SPAN&gt;&lt;SPAN&gt;) != &lt;/SPAN&gt;&lt;SPAN&gt;2&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;raise&lt;/SPAN&gt;&lt;SPAN&gt; fn.UserThrownError(&lt;/SPAN&gt;&lt;SPAN&gt;"Time must be HH:mm or HH:mm:ss."&lt;/SPAN&gt;&lt;SPAN&gt;)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;try&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; start_datetime = datetime.strptime(f&lt;/SPAN&gt;&lt;SPAN&gt;"{startdate} {t}"&lt;/SPAN&gt;&lt;SPAN&gt;, &lt;/SPAN&gt;&lt;SPAN&gt;"%Y-%m-%d %H:%M:%S"&lt;/SPAN&gt;&lt;SPAN&gt;)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;except&lt;/SPAN&gt;&lt;SPAN&gt; ValueError:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;raise&lt;/SPAN&gt;&lt;SPAN&gt; fn.UserThrownError(&lt;/SPAN&gt;&lt;SPAN&gt;"Invalid date or time format. Expected YYYY-MM-DD and HH:mm[:ss]."&lt;/SPAN&gt;&lt;SPAN&gt;)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; created_date = datetime.now()&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; conn = cur = &lt;/SPAN&gt;&lt;SPAN&gt;None&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;try&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; conn = sqlDB1.connect()&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; conn.autocommit = &lt;/SPAN&gt;&lt;SPAN&gt;False&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; cur = conn.cursor()&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;# Upsert salesperson&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; cur.execute(&lt;/SPAN&gt;&lt;SPAN&gt;"SELECT SalespersonID FROM dbo.Salesperson WHERE FullName = ?"&lt;/SPAN&gt;&lt;SPAN&gt;, (fullname,))&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; row = cur.fetchone()&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;if&lt;/SPAN&gt;&lt;SPAN&gt; row:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; sp_id = &lt;/SPAN&gt;&lt;SPAN&gt;int&lt;/SPAN&gt;&lt;SPAN&gt;(row[&lt;/SPAN&gt;&lt;SPAN&gt;0&lt;/SPAN&gt;&lt;SPAN&gt;])&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;else&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;try&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; cur.execute(&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;"INSERT INTO dbo.Salesperson (FullName) OUTPUT INSERTED.SalespersonID VALUES (?)"&lt;/SPAN&gt;&lt;SPAN&gt;,&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; (fullname,)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; )&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; sp_id = &lt;/SPAN&gt;&lt;SPAN&gt;int&lt;/SPAN&gt;&lt;SPAN&gt;(cur.fetchone()[&lt;/SPAN&gt;&lt;SPAN&gt;0&lt;/SPAN&gt;&lt;SPAN&gt;])&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;except&lt;/SPAN&gt;&lt;SPAN&gt; Exception:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; cur.execute(&lt;/SPAN&gt;&lt;SPAN&gt;"SELECT SalespersonID FROM dbo.Salesperson WHERE FullName = ?"&lt;/SPAN&gt;&lt;SPAN&gt;, (fullname,))&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; sp_id = &lt;/SPAN&gt;&lt;SPAN&gt;int&lt;/SPAN&gt;&lt;SPAN&gt;(cur.fetchone()[&lt;/SPAN&gt;&lt;SPAN&gt;0&lt;/SPAN&gt;&lt;SPAN&gt;])&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; statusvar = &lt;/SPAN&gt;&lt;SPAN&gt;"Entry"&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;# Insert appointment&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; cur.execute(&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;"""&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; INSERT INTO dbo.Appointment (SalespersonID, StartDate, DurationMinutes, Status, CreatedDate)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; OUTPUT INSERTED.AppointmentID&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; VALUES (?, ?, ?, ?, ?)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; """&lt;/SPAN&gt;&lt;SPAN&gt;,&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; (sp_id, start_datetime, dur, statusvar, created_date)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; )&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; appt_id = &lt;/SPAN&gt;&lt;SPAN&gt;int&lt;/SPAN&gt;&lt;SPAN&gt;(cur.fetchone()[&lt;/SPAN&gt;&lt;SPAN&gt;0&lt;/SPAN&gt;&lt;SPAN&gt;])&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; conn.commit()&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;return&lt;/SPAN&gt;&lt;SPAN&gt; f&lt;/SPAN&gt;&lt;SPAN&gt;"&lt;span class="lia-unicode-emoji" title=":white_heavy_check_mark:"&gt;✅&lt;/span&gt; Appointment {appt_id} created for {fullname} at {start_datetime} ({dur} min)."&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;except&lt;/SPAN&gt;&lt;SPAN&gt; fn.UserThrownError:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;raise&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;except&lt;/SPAN&gt;&lt;SPAN&gt; Exception &lt;/SPAN&gt;&lt;SPAN&gt;as&lt;/SPAN&gt;&lt;SPAN&gt; e:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; logging.exception(&lt;/SPAN&gt;&lt;SPAN&gt;"create_appointment failed"&lt;/SPAN&gt;&lt;SPAN&gt;)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;try&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;if&lt;/SPAN&gt;&lt;SPAN&gt; conn:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; conn.rollback()&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;except&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;pass&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;raise&lt;/SPAN&gt;&lt;SPAN&gt; fn.UserThrownError(f&lt;/SPAN&gt;&lt;SPAN&gt;"&lt;span class="lia-unicode-emoji" title=":cross_mark:"&gt;❌&lt;/span&gt; Failed to create appointment: {str(e)}"&lt;/SPAN&gt;&lt;SPAN&gt;)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;finally&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;try&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;if&lt;/SPAN&gt;&lt;SPAN&gt; cur:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; cur.close()&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;except&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;pass&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;try&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;if&lt;/SPAN&gt;&lt;SPAN&gt; conn:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; conn.close()&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;except&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;pass&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;BR /&gt;&lt;BR /&gt;&lt;BR /&gt;&lt;BR /&gt;&lt;BR /&gt;&lt;BR /&gt;&lt;BR /&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;@udf&lt;/SPAN&gt;&lt;SPAN&gt;.connection(argName=&lt;/SPAN&gt;&lt;SPAN&gt;"sqlDB1"&lt;/SPAN&gt;&lt;SPAN&gt;, alias=&lt;/SPAN&gt;&lt;SPAN&gt;"TWFDB"&lt;/SPAN&gt;&lt;SPAN&gt;)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;@udf&lt;/SPAN&gt;&lt;SPAN&gt;.function()&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;def&lt;/SPAN&gt;&lt;SPAN&gt; approve_appointment_by_cfo(&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; sqlDB1: fn.FabricSqlConnection,&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; appointmentid: &lt;/SPAN&gt;&lt;SPAN&gt;int&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;) -&amp;gt; &lt;/SPAN&gt;&lt;SPAN&gt;str&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;if&lt;/SPAN&gt;&lt;SPAN&gt; sqlDB1 &lt;/SPAN&gt;&lt;SPAN&gt;is&lt;/SPAN&gt; &lt;SPAN&gt;None&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;raise&lt;/SPAN&gt;&lt;SPAN&gt; fn.UserThrownError(&lt;/SPAN&gt;&lt;SPAN&gt;"Connection injection failed. Check alias 'TWFDB' in UDF connections."&lt;/SPAN&gt;&lt;SPAN&gt;)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; conn = cur = &lt;/SPAN&gt;&lt;SPAN&gt;None&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;try&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; conn = sqlDB1.connect()&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; conn.autocommit = &lt;/SPAN&gt;&lt;SPAN&gt;False&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; cur = conn.cursor()&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;# Check if appointment exists&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; cur.execute(&lt;/SPAN&gt;&lt;SPAN&gt;"SELECT AppointmentID FROM dbo.Appointment WHERE AppointmentID = ?"&lt;/SPAN&gt;&lt;SPAN&gt;, (appointmentid,))&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;if&lt;/SPAN&gt; &lt;SPAN&gt;not&lt;/SPAN&gt;&lt;SPAN&gt; cur.fetchone():&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;raise&lt;/SPAN&gt;&lt;SPAN&gt; fn.UserThrownError(f&lt;/SPAN&gt;&lt;SPAN&gt;"No appointment found with ID {appointmentid}."&lt;/SPAN&gt;&lt;SPAN&gt;)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;# Update status to CFOApproved&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; cur.execute(&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;"""&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; UPDATE dbo.Appointment&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; SET Status = 'CFOApproved'&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; WHERE AppointmentID = ?&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; """&lt;/SPAN&gt;&lt;SPAN&gt;,&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; (appointmentid,)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; )&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; conn.commit()&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;return&lt;/SPAN&gt;&lt;SPAN&gt; f&lt;/SPAN&gt;&lt;SPAN&gt;"&lt;span class="lia-unicode-emoji" title=":white_heavy_check_mark:"&gt;✅&lt;/span&gt; Appointment {appointmentid} status updated to CFOApproved."&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;except&lt;/SPAN&gt;&lt;SPAN&gt; fn.UserThrownError:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;raise&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;except&lt;/SPAN&gt;&lt;SPAN&gt; Exception &lt;/SPAN&gt;&lt;SPAN&gt;as&lt;/SPAN&gt;&lt;SPAN&gt; e:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; logging.exception(&lt;/SPAN&gt;&lt;SPAN&gt;"approve_appointment_by_cfo failed"&lt;/SPAN&gt;&lt;SPAN&gt;)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;try&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;if&lt;/SPAN&gt;&lt;SPAN&gt; conn:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; conn.rollback()&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;except&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;pass&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;raise&lt;/SPAN&gt;&lt;SPAN&gt; fn.UserThrownError(f&lt;/SPAN&gt;&lt;SPAN&gt;"&lt;span class="lia-unicode-emoji" title=":cross_mark:"&gt;❌&lt;/span&gt; Failed to update appointment: {str(e)}"&lt;/SPAN&gt;&lt;SPAN&gt;)&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;finally&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;try&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;if&lt;/SPAN&gt;&lt;SPAN&gt; cur:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; cur.close()&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;except&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;pass&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;try&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;if&lt;/SPAN&gt;&lt;SPAN&gt; conn:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; conn.close()&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;except&lt;/SPAN&gt;&lt;SPAN&gt;:&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;/SPAN&gt;&lt;SPAN&gt;pass&lt;/SPAN&gt;&lt;/DIV&gt;&lt;BR /&gt;&lt;BR /&gt;&lt;/DIV&gt;</description>
      <pubDate>Fri, 29 Aug 2025 18:08:28 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Accounting-Process-Flow-Automation-by-Translytical-Flow/m-p/4811909#M29</guid>
      <dc:creator>Julit_Insight</dc:creator>
      <dc:date>2025-08-29T18:08:28Z</dc:date>
    </item>
    <item>
      <title>Vacation Tracker</title>
      <link>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Vacation-Tracker/m-p/4810680#M25</link>
      <description>&lt;P&gt;Code Repo :&amp;nbsp;&lt;A href="https://github.com/NandanHegde15/MSFTFabric-Projects/blob/main/Vacation%20tracker/User%20Data%20Function.py" target="_blank" rel="noopener"&gt;https://github.com/NandanHegde15/MSFTFabric-Projects/blob/main/Vacation%20tracker/User%20Data%20Function.py&lt;/A&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Work Flow:&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;The code implements a &lt;STRONG data-start="107" data-end="136"&gt;Vacation Tracker workflow&lt;/STRONG&gt; in Microsoft Fabric using &lt;STRONG data-start="163" data-end="196"&gt;User Defined Functions (UDFs)&lt;/STRONG&gt;.&lt;BR data-start="197" data-end="200" /&gt;It enables employees to &lt;STRONG data-start="224" data-end="272"&gt;submit&lt;/STRONG&gt;&amp;nbsp; and the Supervisor of that employee to &lt;STRONG&gt;approve&lt;/STRONG&gt;,&lt;STRONG data-start="224" data-end="272"&gt; or reject vacation requests &lt;/STRONG&gt; based on notification received.&amp;nbsp;validates requests, checks &lt;STRONG data-start="341" data-end="360"&gt;public holidays&lt;/STRONG&gt;, uses &lt;STRONG data-start="367" data-end="383"&gt;Azure OpenAI&lt;/STRONG&gt; for recommendations, and sends &lt;STRONG data-start="415" data-end="432"&gt;notifications&lt;/STRONG&gt; (via email + SMS).&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Employee&lt;BR /&gt;│&lt;BR /&gt;│ (Submit Request: EmployeeId, StartDate, EndDate, Reason, Priority)&lt;BR /&gt;▼&lt;BR /&gt;Vacation Request UDF (vacation_tracker_request)&lt;BR /&gt;│&lt;BR /&gt;├─► Validate input (dates, reason, priority flag)&lt;BR /&gt;│&lt;BR /&gt;├─► SQL MERGE into VacationTracker&lt;BR /&gt;│&lt;BR /&gt;├─► Fetch Employee &amp;amp; Supervisor details from SQL&lt;BR /&gt;│&lt;BR /&gt;├─► Call Nager.Date API → Get holidays&lt;BR /&gt;│&lt;BR /&gt;├─► Query SQL → Past 12 months leave history&lt;BR /&gt;│&lt;BR /&gt;├─► Build prompt → Call Azure OpenAI GPT&lt;BR /&gt;│ │&lt;BR /&gt;│ └─► AI Suggestion (approve/reject context)&lt;BR /&gt;│&lt;BR /&gt;├─► Notify Supervisor:&lt;BR /&gt;│ • Email via Logic App (Approve / Reject buttons → Power BI report link)&lt;BR /&gt;│ • SMS via Twilio (if priority = Yes)&lt;BR /&gt;│&lt;BR /&gt;▼&lt;BR /&gt;Supervisor Action (Approve / Reject)&lt;BR /&gt;│&lt;BR /&gt;├─► If Approve → vacation_tracker_approval UDF&lt;BR /&gt;│ • Update SQL (status = Approved, reason, modified date)&lt;BR /&gt;│ • Notify Employee (Approval Email via Logic App)&lt;BR /&gt;│&lt;BR /&gt;└─► If Reject → vacation_tracker_rejection UDF&lt;BR /&gt;• Update SQL (status = Rejected, reason, modified date)&lt;BR /&gt;• Notify Employee (Rejection Email via Logic App)&lt;BR /&gt;&lt;BR /&gt;&lt;BR /&gt;&lt;BR /&gt;&lt;BR /&gt;Employee Page : Governed by RLS (Every employee would see his/her own details and can raise a Vacation request)&lt;/P&gt;
&lt;P&gt;#Data Function 1&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Supervisor would be able to see all details of his resources :&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Supervisor would receive an email and in case of High priority receive an SMS with AI sugesstion based on past data and public holiday in range :&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Based on Approve or Reject decision, Supervisor would be redirected to either Approval page or rejection page&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;#Data Function 2&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;#Data Function 3&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Based on approval/Rejection, Backend database and the Direct Query report would be updated and the employee would receive an email notification :&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Mon, 13 Oct 2025 17:49:24 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Vacation-Tracker/m-p/4810680#M25</guid>
      <dc:creator>NandanHegde</dc:creator>
      <dc:date>2025-10-13T17:49:24Z</dc:date>
    </item>
    <item>
      <title>Wallet Watch Analytics: Expense Tracker</title>
      <link>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Wallet-Watch-Analytics-Expense-Tracker/m-p/4808750#M19</link>
      <description>&lt;P&gt;&lt;STRONG&gt;Introduction:&lt;/STRONG&gt;&lt;BR /&gt;WalletWise Analytics is a smart personal expense tracking application that combines the power of Microsoft Fabric and Power BI to create an intelligent expense tracking system.&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;What It Does:&lt;BR /&gt;- Track Expenses in Real-time: Add your daily expenses directly from a Power BI dashboard and watch your balance update instantly&lt;BR /&gt;- Monitor Account Balance: See your current balance on a live card that updates every time you spend money&lt;BR /&gt;- Email Notifications: Get email alerts sent to your inbox when your balance gets dangerously low&lt;BR /&gt;- Monthly Salary Management: Automatically adds $8,000 monthly salary to keep your account funded&lt;BR /&gt;- Expense Control: View all your expenses in a table and visualize the spending&lt;BR /&gt;- Write-back Functionality: Enter expense data through Power BI that immediately saves to your database&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Full Demo Video:&lt;/P&gt;
&lt;P&gt;&lt;A href="https://youtu.be/RJ6nBKp-pC8" target="_self"&gt;Click Here&lt;/A&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Steps Used:&lt;/P&gt;
&lt;P&gt;Step 1: Database Setup&lt;BR /&gt;- Created two tables in Fabric SQL Database: Expense table and Bank table&lt;BR /&gt;- Added sample data to test the system&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;Step 2: User Data Functions&lt;BR /&gt;- Built smart functions that can add expenses, add salary, and send email alerts&lt;BR /&gt;- Connected these functions to the database to read and write data&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Step 3: Power BI Dashboard&lt;BR /&gt;- Created a user-friendly dashboard with cards showing balance and alerts&lt;BR /&gt;- Added input controls where users can type expense details&lt;BR /&gt;- Built a table showing all expenses&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Step 4: Write-back Buttons&lt;BR /&gt;- Added "Add Expense" button that saves data to the database when clicked&lt;BR /&gt;- Added "Add Salary" button that adds $8,000 monthly credit&lt;BR /&gt;- Added "Send Email" button for email alerts&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Step 5: Smart Notifications&lt;BR /&gt;- Set up email notifications for critical balance levels&lt;BR /&gt;- Made the system update in real-time when changes happen&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Why I Came Up With This:&lt;BR /&gt;I created this project to solve a common problem many people face: Losing track of their spending and running out of money unexpectedly. This project showcases the power of translytical flows - where analytical tools like Power BI can write data back to databases, creating a seamless experience between viewing data and updating it.&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;UDF:&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Adding Expense&lt;/STRONG&gt;&lt;/P&gt;
&lt;LI-CODE lang="python"&gt;import fabric.functions as fn
from datetime import datetime
udf = fn.UserDataFunctions()
@udf.connection(argName="sqlDB", alias="YOUR_CONNECTION_ALIAS")
@udf.function()
def write_expense(sqlDB: fn.FabricSqlConnection, expenseDate: str, description: str, amount: float, category: str) -&amp;gt; str:
    # Error handling
    if amount &amp;lt;= 0:
        raise fn.UserThrownError("Amount must be greater than 0", {"Amount": amount})
    
    if len(description) &amp;gt; 255:
        raise fn.UserThrownError("Description too long (max 255 characters)", {"Description": description})
    
    # Establish connection
    connection = sqlDB.connect()
    cursor = connection.cursor()
    
    try:
        # Insert into Expense table
        expense_query = "INSERT INTO Expense (ExpenseDate, Description, Amount, Category) VALUES (?, ?, ?, ?)"
        cursor.execute(expense_query, expenseDate, description, amount, category)
        
        # Insert corresponding debit into Bank table
        bank_query = "INSERT INTO Bank (TransactionDate, Description, Amount, TransactionType) VALUES (?, ?, ?, ?)"
        bank_description = f"Expense: {description}"
        cursor.execute(bank_query, expenseDate, bank_description, -amount, 'Debit')
        
        # Commit transaction
        connection.commit()
        
        return f"Expense ${amount} for '{description}' added successfully"
        
    except Exception as e:
        connection.rollback()
        raise fn.UserThrownError(f"Failed to add expense: {str(e)}")
    
    finally:
        cursor.close()
        connection.close()&lt;/LI-CODE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Add $8000 Monthly Salary&lt;/STRONG&gt;&lt;/P&gt;
&lt;LI-CODE lang="python"&gt;@udf.connection(argName="sqlDB", alias="YOUR_CONNECTION_ALIAS")
@udf.function()
def add_salary(sqlDB: fn.FabricSqlConnection) -&amp;gt; str:
    connection = sqlDB.connect()
    cursor = connection.cursor()
    
    try:
        # Add fixed $8000 salary to Bank table with current date
        current_date = datetime.now().strftime('%Y-%m-%d')
        salary_query = "INSERT INTO Bank (TransactionDate, Description, Amount, TransactionType) VALUES (?, ?, ?, ?)"
        cursor.execute(salary_query, current_date, 'Monthly Salary', 8000.00, 'Credit')
        connection.commit()
        
        return "Monthly salary $8000 added successfully"
        
    except Exception as e:
        connection.rollback()
        raise fn.UserThrownError(f"Failed to add salary: {str(e)}")
    
    finally:
        cursor.close()
        connection.close()&lt;/LI-CODE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Send Email when balance drops below $100&lt;/STRONG&gt;&lt;/P&gt;
&lt;P&gt;Configuration Setup (Detailed Steps)&lt;BR /&gt;Part A: Get SendGrid API Key&lt;/P&gt;
&lt;P&gt;&lt;U&gt;Create SendGrid Account:&lt;/U&gt;&lt;/P&gt;
&lt;P&gt;- Go to &lt;A href="https://sendgrid.com/" target="_blank" rel="noopener"&gt;https://sendgrid.com/&lt;/A&gt;&lt;BR /&gt;- Click "Start for Free" or "Sign Up"&lt;BR /&gt;- Fill out registration form with your details&lt;BR /&gt;- Verify your email address&lt;/P&gt;
&lt;P&gt;&lt;U&gt;Access SendGrid Dashboard:&lt;/U&gt;&lt;/P&gt;
&lt;P&gt;- Log into your SendGrid account&lt;BR /&gt;- You'll see the main dashboard&lt;/P&gt;
&lt;P&gt;&lt;U&gt;Create API Key:&lt;/U&gt;&lt;/P&gt;
&lt;P&gt;- In the left sidebar, click "Settings"&lt;BR /&gt;- Click "API Keys"&lt;BR /&gt;- Click "Create API Key" button&lt;BR /&gt;- Choose "Restricted Access" (recommended)&lt;BR /&gt;- Give it a name like "Fabric-Expense-Tracker"&lt;BR /&gt;- Under "Mail Send", select "Full Access"&lt;BR /&gt;- Click "Create &amp;amp; View"&lt;BR /&gt;- IMPORTANT: Copy the API key immediately (it won't be shown again)&lt;BR /&gt;- Store it securely (you'll need this for the code)&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Part B: Update Your Function Code&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;LI-CODE lang="python"&gt;import fabric.functions as fn
import logging
from flask import Flask
from flask_mail import Mail, Message
from datetime import datetime

udf = fn.UserDataFunctions()

# Flask Mail Configuration
app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.sendgrid.net'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USERNAME'] = 'apikey'
app.config['MAIL_PASSWORD'] = 'YOUR_SENDGRID_API_KEY_HERE'  # Replace with your actual API key
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_DEFAULT_SENDER'] = 'your-email@domain.com'  # Replace with your email
mail = Mail(app)

@udf.connection(argName="sqlDB", alias="YOUR_CONNECTION_ALIAS")  # Replace with your alias
@udf.function()
def check_balance_and_notify(sqlDB: fn.FabricSqlConnection, recipientemail: str) -&amp;gt; str:
    """Function to manually check balance and send notification if needed"""
    connection = sqlDB.connect()
    cursor = connection.cursor()
    
    try:
        # Get current balance
        balance_query = "SELECT SUM(Amount) FROM Bank"
        cursor.execute(balance_query)
        current_balance = cursor.fetchone()[0] or 0
        
        if current_balance &amp;lt; 100:
            send_low_balance_email(current_balance, recipientemail)
            return f"🚨 CRITICAL: Balance is ${current_balance:.2f}. Email notification sent to {recipientemail}"
        else:
            return f"✅ Balance OK: ${current_balance:.2f}. No notification needed."
            
    except Exception as e:
        raise fn.UserThrownError(f"Failed to check balance: {str(e)}")
    
    finally:
        cursor.close()
        connection.close()

def send_low_balance_email(balance: float, recipient_email: str):
    """Send low balance alert email - SIMPLIFIED VERSION"""
    try:
        current_time = datetime.now()
        
        # Simple text email instead of complex HTML
        email_text = f"""
CRITICAL: Low Balance Alert!

Your account balance has dropped below $100!

Current Balance: ${balance:.2f}
Date: {current_time.strftime('%Y-%m-%d')}
Time: {current_time.strftime('%H:%M:%S')}

Please add funds to your account immediately to avoid any issues.
        """
        
        with app.app_context():
            msg = Message(
                subject="🚨 CRITICAL: Account Balance Alert - Action Required",
                recipients=[recipient_email],
                body=email_text
            )
            mail.send(msg)
            
        logging.info(f"Low balance email sent to {recipient_email}. Balance: ${balance:.2f}")
        
    except Exception as e:
        logging.error(f"Failed to send email: {str(e)}")
        raise fn.UserThrownError(f"Failed to send notification email: {str(e)}")&lt;/LI-CODE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Other Use Cases That Can Be Implemented:&lt;/STRONG&gt;&lt;BR /&gt;- Student Budget Manager: Track tuition, books, food, and living expenses for students&lt;BR /&gt;- Travel Expense Tracker: Monitor trip expenses, daily spending limits, and travel budgets&lt;BR /&gt;- Investment Portfolio Monitor: Track investments, gains, losses, and portfolio alerts&lt;BR /&gt;- Healthcare Expense Tracker: Track medical bills, insurance claims, and health-related spending&lt;/P&gt;</description>
      <pubDate>Mon, 13 Oct 2025 17:49:42 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Wallet-Watch-Analytics-Expense-Tracker/m-p/4808750#M19</guid>
      <dc:creator>Santhanalakshmi</dc:creator>
      <dc:date>2025-10-13T17:49:42Z</dc:date>
    </item>
    <item>
      <title>Dynamic Power BI Experiences</title>
      <link>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Dynamic-Power-BI-Experiences/m-p/4808192#M18</link>
      <description>&lt;P&gt;I created a Power BI learning game to demonstrate how &lt;STRONG&gt;Translytical and UDF capabilities can transform user journey and user experience&lt;/STRONG&gt; in Power BI to boost adoption.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;img /&gt;&lt;/P&gt;&lt;P&gt; &lt;/P&gt;&lt;P&gt;&lt;img /&gt;&lt;/P&gt;&lt;P&gt;&lt;img /&gt;&lt;/P&gt;&lt;P&gt;  &lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;STRONG&gt;I focused on the following Translytical use cases:&lt;/STRONG&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;STRONG&gt;1. Registration and State Management&lt;/STRONG&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;The game begins with an &lt;U&gt;engagement action&lt;/U&gt; : players choose to start and see their email recognized. This creates commitment to the learning experience. A UDF populates the SQL database table with active players, notifications, timestamps, avatars, progress, and points. Using DAX to control transparency based on written columns, the registration menu "disappears" for active players but reappears for new users opening the Power BI report.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;STRONG&gt;2. Notification Management&lt;/STRONG&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;I created &lt;U&gt;personalized progress with guided steps&lt;/U&gt; to direct users through the prepared journey. Notifications attract player attention and explain game rules. This approach applies to any business report (eg: pushing notifications about report readiness, data accuracy, issues, guidance, etc. significantly boosts adoption). Users can dismiss notifications to avoid spam from already-consumed information.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;STRONG&gt;3. Custom Time-Based Scoring&lt;/STRONG&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;To demonstrate this functionality, users are guided to click a specific item and select an avatar. Avatar selection triggers a UDF that calculates progression speed and &lt;U&gt;assigns scores based on time spent&lt;/U&gt;. This enables progress tracking and maintains learning engagement.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;STRONG&gt;Result:&lt;/STRONG&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;These three combined UDFs showcase new possibilities for user experience, storytelling and user journey design, accessibility and engagement levels &lt;STRONG&gt;that boost adoption&lt;/STRONG&gt;. The report is fully personalized based on each player's progress, allowing players to start from where they left off. This showcases an example of &lt;STRONG&gt;personalized journey tracking&lt;/STRONG&gt;.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;STRONG&gt;Impact:&lt;/STRONG&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;While gamification provides an excellent confidence boost and aids change management, these techniques extend far beyond gaming scenarios. By combining state management, notification handling, and adaptive scoring, organizations can create engaging user journeys that drive adoption and sustained usage. The techniques showcased here provide a foundation for any scenario requiring user engagement, progress tracking, and personalized experiences.&lt;/P&gt;&lt;P&gt;&lt;BR /&gt;&lt;STRONG&gt;UDF used:&lt;/STRONG&gt;&lt;/P&gt;&lt;P&gt;&lt;STRONG&gt;TRANSLYTICAL GAMING FRAMEWORK - UDF #1 of 3&lt;/STRONG&gt;&lt;BR /&gt;Purpose: User registration and state management for personalized Power BI experiences&lt;BR /&gt;Business Value: Enables session persistence and user journey tracking&lt;/P&gt;&lt;P&gt;&lt;BR /&gt;&lt;STRONG&gt;insert_gaming_user&lt;/STRONG&gt;&lt;/P&gt;&lt;LI-CODE lang="markup"&gt;import fabric.functions as fn
from datetime import datetime

# Create the UserDataFunctions instance
udf = fn.UserDataFunctions()

@udf.connection(argName="sqlDB", alias="AlexSQL")
@udf.function()
def insert_gaming_user(sqlDB: fn.FabricSqlConnection, userPrincipalName: str) -&amp;gt; str:
    """
    Insert a new gaming user record with default values including timestamp
    
    Args:
        sqlDB: Connection to the Fabric SQL database
        userPrincipalName: The user's principal name from DAX (e.g., from USERPRINCIPALNAME())
        
    Returns:
        str: Success message for Power BI
    """
    
    try:
        # Input validation
        if not userPrincipalName or userPrincipalName.strip() == "":
            raise fn.UserThrownError("User principal name cannot be empty.")
        
        # Clean the input
        userName = userPrincipalName.strip()
        
        # Get current timestamp for when UDF is executed
        current_timestamp = datetime.now()
        
        # Establish connection to the SQL database
        connection = sqlDB.connect()
        cursor = connection.cursor()
        
        # Check if user already exists (optional - remove if you want duplicates)
        check_query = "SELECT COUNT(*) FROM [dbo].[Gaming] WHERE [UserName] = ?"
        cursor.execute(check_query, userName)
        user_count = cursor.fetchone()[0]
        
        if user_count &amp;gt; 0:
            cursor.close()
            connection.close()
            raise fn.UserThrownError(f"User '{userName}' already exists in the gaming table.")
        
        # Generate next ID (since you're using INT NOT NULL PRIMARY KEY)
        # Get the maximum existing ID and add 1
        id_query = "SELECT ISNULL(MAX([Id]), 0) + 1 FROM [dbo].[Gaming]"
        cursor.execute(id_query)
        next_id = cursor.fetchone()[0]
        
        # Insert the new gaming user record with extended columns including Points and Avatar ID
        insert_query = """
            INSERT INTO [dbo].[Gaming] (
                [Id], [UserName], [BeginID], [NotificationStart], [TimeStamp], 
                [Level1], [L1_TimeStamp], [Level2], [L2_TimeStamp], 
                [Points], [ChallengePoints], [Avatar ID]
            ) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        """
        
        # Execute the insert with specified values
        # TimeStamp = current datetime, Points and ChallengePoints = 0, Avatar ID = 2, other new columns = NULL
        cursor.execute(insert_query, (
            next_id,           # Id
            userName,          # UserName
            1,                 # BeginID
            0,                 # NotificationStart
            current_timestamp, # TimeStamp (current datetime)
            None,              # Level1 (NULL)
            None,              # L1_TimeStamp (NULL)
            None,              # Level2 (NULL)
            None,              # L2_TimeStamp (NULL)
            0,                 # Points (set to 0)
            0,                 # ChallengePoints (set to 0)
            2                  # Avatar ID (set to 2)
        ))
        
        # Commit the transaction
        connection.commit()
        
        # Close connections
        cursor.close()
        connection.close()
        
        return f"Successfully added user '{userName}' to gaming table with ID {next_id} and Avatar ID 2 at {current_timestamp.strftime('%Y-%m-%d %H:%M:%S')}"
        
    except fn.UserThrownError:
        # Re-raise user errors as-is
        raise
    except Exception as e:
        # Handle any other database errors
        raise fn.UserThrownError(f"Database error occurred: {str(e)}")&lt;/LI-CODE&gt;&lt;P&gt;&lt;BR /&gt;&lt;STRONG&gt;TRANSLYTICAL GAMING FRAMEWORK - UDF #2 of 3&lt;/STRONG&gt;&lt;BR /&gt;Purpose: Notification management and user engagement flow control&lt;BR /&gt;Business Value: Enables dismissible notifications and prevents information spam, applicable to any business report requiring guided user experiences&lt;/P&gt;&lt;P&gt;&lt;BR /&gt;&lt;STRONG&gt;update_notification_status&lt;/STRONG&gt;&lt;/P&gt;&lt;LI-CODE lang="markup"&gt;import fabric.functions as fn

# Create the UserDataFunctions instance
udf = fn.UserDataFunctions()

@udf.connection(argName="sqlDB", alias="AlexSQL")
@udf.function()
def update_notification_status(sqlDB: fn.FabricSqlConnection, userPrincipalName: str) -&amp;gt; str:
    """
    Update the NotificationStart column to 1 for an existing user
    
    Args:
        sqlDB: Connection to the Fabric SQL database
        userPrincipalName: The user's principal name from DAX (e.g., from USERPRINCIPALNAME())
        
    Returns:
        str: Success message for Power BI
    """
    
    try:
        # Input validation
        if not userPrincipalName or userPrincipalName.strip() == "":
            raise fn.UserThrownError("User principal name cannot be empty.")
        
        # Clean the input
        userName = userPrincipalName.strip()
        
        # Establish connection to the SQL database
        connection = sqlDB.connect()
        cursor = connection.cursor()
        
        # Check if user exists
        check_query = "SELECT COUNT(*) FROM [dbo].[Gaming] WHERE [UserName] = ?"
        cursor.execute(check_query, userName)
        user_count = cursor.fetchone()[0]
        
        if user_count == 0:
            cursor.close()
            connection.close()
            raise fn.UserThrownError(f"User '{userName}' does not exist in the gaming table.")
        
        # Update the NotificationStart column to 1
        update_query = """
            UPDATE [dbo].[Gaming] 
            SET [NotificationStart] = 1 
            WHERE [UserName] = ?
        """
        
        # Execute the update
        cursor.execute(update_query, userName)
        
        # Commit the transaction
        connection.commit()
        
        # Close connections
        cursor.close()
        connection.close()
        
        return f"Successfully updated NotificationStart to 1 for user '{userName}'"
        
    except fn.UserThrownError:
        # Re-raise user errors as-is
        raise
    except Exception as e:
        # Handle any other database errors
        raise fn.UserThrownError(f"Database error occurred: {str(e)}")&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;STRONG&gt;TRANSLYTICAL GAMING FRAMEWORK - UDF #3 of 3&lt;/STRONG&gt;&lt;BR /&gt;Purpose: Custom time-based scoring and progress tracking with avatar personalization&lt;BR /&gt;Business Value: Measures user engagement speed and rewards timely interactions, adaptable for training completion, task performance, and user adoption metrics&lt;/P&gt;&lt;P&gt;&lt;BR /&gt;&lt;STRONG&gt;complete_level1_challenge&lt;/STRONG&gt;&lt;/P&gt;&lt;LI-CODE lang="markup"&gt;import fabric.functions as fn
from datetime import datetime

# Create the UserDataFunctions instance
udf = fn.UserDataFunctions()

@udf.connection(argName="sqlDB", alias="AlexSQL")
@udf.function()
def complete_level1_challenge(sqlDB: fn.FabricSqlConnection, userPrincipalName: str, selectedAvatar: int) -&amp;gt; str:
"""
Complete Level 1 challenge, assign points based on time difference, and update Avatar ID

Args:
sqlDB: Connection to the Fabric SQL database
userPrincipalName: The user's principal name from DAX (e.g., from USERPRINCIPALNAME())
selectedAvatar: The selected avatar ID from DAX measure

Returns:
str: Success message with points awarded for Power BI
"""

try:
# Input validation
if not userPrincipalName or userPrincipalName.strip() == "":
raise fn.UserThrownError("User principal name cannot be empty.")

if selectedAvatar is None:
raise fn.UserThrownError("Selected Avatar cannot be empty.")

# Clean the input
userName = userPrincipalName.strip()

# Get current timestamp for L1_TimeStamp
current_timestamp = datetime.now()

# Establish connection to the SQL database
connection = sqlDB.connect()
cursor = connection.cursor()

# Check if user exists and get their initial TimeStamp
check_query = """
SELECT [TimeStamp], [L1_TimeStamp]
FROM [dbo].[Gaming]
WHERE [UserName] = ?
"""
cursor.execute(check_query, userName)
result = cursor.fetchone()

if not result:
cursor.close()
connection.close()
raise fn.UserThrownError(f"User '{userName}' does not exist in the gaming table.")

initial_timestamp = result[0]
existing_l1_timestamp = result[1]

# Check if Level 1 challenge already completed
if existing_l1_timestamp is not None:
cursor.close()
connection.close()
raise fn.UserThrownError(f"User '{userName}' has already completed Level 1 challenge.")

# Check if initial TimeStamp exists
if initial_timestamp is None:
cursor.close()
connection.close()
raise fn.UserThrownError(f"User '{userName}' does not have an initial TimeStamp.")

# Calculate time difference
time_diff = current_timestamp - initial_timestamp
total_minutes = time_diff.total_seconds() / 60

# Determine points based on time difference
# GAMING MECHANICS: Time-based scoring rewards faster completion
# &amp;lt; 10 min = 20 pts (expert), &amp;lt; 1 hour = 10 pts (good), etc.
if total_minutes &amp;lt; 10:
points = 20
time_category = "&amp;lt; 10 minutes"
elif total_minutes &amp;lt; 60: # &amp;lt; 1 hour
points = 10
time_category = "&amp;lt; 1 hour"
elif total_minutes &amp;lt; 1440: # &amp;lt; 1 day (24 hours * 60 minutes)
points = 5
time_category = "&amp;lt; 1 day"
else: # more than 1 day
points = 3
time_category = "&amp;gt; 1 day"

# Update L1_TimeStamp, Level1 points, and Avatar ID
update_query = """
UPDATE [dbo].[Gaming]
SET [L1_TimeStamp] = ?, [Level1] = ?, [Avatar ID] = ?
WHERE [UserName] = ?
"""

# Execute the update
cursor.execute(update_query, (current_timestamp, points, selectedAvatar, userName))

# Commit the transaction
connection.commit()

# Close connections
cursor.close()
connection.close()

return f"Level 1 completed for '{userName}': {points} points awarded ({time_category}), Avatar ID updated to {selectedAvatar} at {current_timestamp.strftime('%Y-%m-%d %H:%M:%S')}"

except fn.UserThrownError:
# Re-raise user errors as-is
raise
except Exception as e:
# Handle any other database errors
raise fn.UserThrownError(f"Database error occurred: {str(e)}")&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;If this Translytical entry resonates with you, I'd love to connect!&lt;/P&gt;&lt;P&gt;&lt;STRONG&gt;Please give it a &lt;span class="lia-unicode-emoji" title=":red_heart:"&gt;❤️&lt;/span&gt; if you found it valuable&lt;/STRONG&gt;, &lt;STRONG&gt;and feel free to reach out on LinkedIn&lt;/STRONG&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;A href="https://www.linkedin.com/in/alexandru-badiu/" target="_blank" rel="noopener"&gt;Alexandru Badiu | LinkedIn&lt;/A&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Best regards,&lt;/P&gt;&lt;P&gt;Alexandru Badiu&lt;/P&gt;</description>
      <pubDate>Tue, 26 Aug 2025 15:44:41 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Dynamic-Power-BI-Experiences/m-p/4808192#M18</guid>
      <dc:creator>Alex87</dc:creator>
      <dc:date>2025-08-26T15:44:41Z</dc:date>
    </item>
    <item>
      <title>Decrypting data on the fly</title>
      <link>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Decrypting-data-on-the-fly/m-p/4807321#M17</link>
      <description>&lt;P&gt;&lt;SPAN&gt;This project addresses the performance and scalability challenges of working with data encrypted by legacy systems. By modernizing the data pipeline using Microsoft Fabric, we transitioned from resource-intensive batch jobs to a streamlined, translytical flow. Data is ingested into Delta Tables, compared efficiently using delta logic, and decrypted on-the-fly via Python UDFs integrated into SQL—enabling direct use in Power BI without burdening the database. This approach improves system responsiveness, reduces storage overhead, and enhances security by supporting encryption at rest and in transit.&lt;/SPAN&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;SPAN&gt;The decryption algorithm presented below was chosen at random; any decryption algorithm could replace the one displayed.&lt;/SPAN&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="python"&gt;@udf(returnType=StringType())
def app_decrypt(cipher_text):
    if not cipher_text:
        return ''
    try:
        # This is not our actual encryption algorithm; for display only!
        import base64
        from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
        from cryptography.hazmat.backends import default_backend
        from cryptography.hazmat.primitives import padding
        from cryptography.fernet import Fernet

        fernet = Fernet(FERNET_KEY)
        decrypted = fernet.decrypt(cipher_text.encode())
        return decrypted.decode('utf-8')
        return decrypted.decode('utf-8')
    except Exception:
        return "{Decrypt Error}"&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Mon, 25 Aug 2025 20:31:38 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Decrypting-data-on-the-fly/m-p/4807321#M17</guid>
      <dc:creator>jwshock</dc:creator>
      <dc:date>2025-08-25T20:31:38Z</dc:date>
    </item>
    <item>
      <title>Add Commentary to Financial Reports using Translytical</title>
      <link>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Add-Commentary-to-Financial-Reports-using-Translytical/m-p/4806042#M16</link>
      <description>&lt;P&gt;&lt;U&gt;&lt;img /&gt;&lt;/U&gt;&lt;/P&gt;&lt;P&gt;&lt;U&gt;Business Need: Add commentary to live reports easily&lt;/U&gt;&lt;/P&gt;&lt;P&gt;As a financial modeling and BI analyst, I serve business users who want to indicate the effect of market and external factors on some financial and operational metrics. It could be mentioning the impact of tariffs on 2025 cost of sales or that a lawsuit is the reason for a sudden stock price crash or a sudden change of vendor is the cause of a spike in inventory holding days.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;U&gt;Before Translytical: Exporting Power BI reports to PDF or PowerPoint to add those comments&lt;/U&gt;&lt;/P&gt;&lt;P&gt;Most business users end up doing this outside of Power BI. The few occasions we had tried to give them a way to put this comment into a DB has proven less instantaneous enough for the users, and they stopped using the DB based solution. They preferred to export the Power BI report to PDF or PowerPoint and then do their annotations and commentary.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;U&gt;With Translytical: Users can now add comments and instantly see it displayed in their reports&lt;/U&gt;&lt;/P&gt;&lt;P&gt;Translytical addresses the major need for instantly capturing the comments and unlimited updates to those comments. I find the business users of my reports feeling satisfied with the translytical based solutions.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;U&gt;This Showcase: Add live commentary to financial reports on Power BI&lt;/U&gt;&lt;/P&gt;&lt;P&gt;We will be building a solution that allows business users to add the comments they want to about different financial metrics they track for their investment monitoring and decision-making needs. The code and reports are deliberately made simple and easy to replicate so that you can see how easy it is to add these values without a lot of technical work.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;U&gt;Needed Resources:&lt;/U&gt;&lt;/P&gt;&lt;OL&gt;&lt;LI&gt;Company Metrics table (provided in the attached Excel file)&lt;/LI&gt;&lt;LI&gt;Metrics Order table&amp;nbsp;(provided in the attached Excel file)&lt;/LI&gt;&lt;LI&gt;Company Comments table (autogenerated via Dataflow Gen2 group by on the Company Metrics table, see the query codes below)&lt;/LI&gt;&lt;/OL&gt;&lt;P&gt;&lt;img /&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;You can easily use Dataflow Gen2 to load the two tables and generate the third table. I uploaded the file to a Lakehouse storage and then pointed Dataflow Gen2 to the file there. The M query codes are below:&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="markup"&gt;Metrics Order Table
let
  Source = Lakehouse.Contents(null),
  Navigation = Source{[workspaceId = &amp;lt;your-workspace-id&amp;gt;]}[Data],
  #"Navigation 1" = Navigation{[lakehouseId = &amp;lt;your-lakehouse-id&amp;gt;]}[Data],
  #"Navigation 2" = #"Navigation 1"{[Id = "Files", ItemKind = "Folder"]}[Data],
  #"Navigation 3" = #"Navigation 2"{[Name = "translytical - source tables.xlsx"]}[Content],
  #"Imported Excel workbook" = Excel.Workbook(#"Navigation 3", null, true),
  #"Navigation 4" = #"Imported Excel workbook"{[Item = "Metrics Order", Kind = "Sheet"]}[Data],
  #"Promoted headers" = Table.PromoteHeaders(#"Navigation 4", [PromoteAllScalars = true]),
  #"Changed column type" = Table.TransformColumnTypes(#"Promoted headers", {{"Metric", type text}, {"Position", Int64.Type}})
in
  #"Changed column type"&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="markup"&gt;Company Metrics Table
let
  Source = Lakehouse.Contents(null),
  Navigation = Source{[workspaceId = &amp;lt;your-workspace-id&amp;gt;]}[Data],
  #"Navigation 1" = Navigation{[lakehouseId = &amp;lt;your-lakehouse-id&amp;gt;]}[Data],
  #"Navigation 2" = #"Navigation 1"{[Id = "Files", ItemKind = "Folder"]}[Data],
  #"Navigation 3" = #"Navigation 2"{[Name = "translytical - source tables.xlsx"]}[Content],
  #"Imported Excel workbook" = Excel.Workbook(#"Navigation 3", null, true),
  #"Navigation 4" = #"Imported Excel workbook"{[Item = "Company Metrics", Kind = "Sheet"]}[Data],
  #"Promoted headers" = Table.PromoteHeaders(#"Navigation 4", [PromoteAllScalars = true]),
  #"Changed column type" = Table.TransformColumnTypes(#"Promoted headers", {{"ID", Int64.Type}, {"Company", type text}, {"Check", Int64.Type}, {"Metric", type text}, {"Year", Int64.Type}, {"Value", type number}, {"Comment", type text}}),
  #"Removed columns" = Table.RemoveColumns(#"Changed column type", {"Comment"}),
  #"Inserted Merged Column" = Table.AddColumn(#"Removed columns", "RelationshipKey", each Text.Combine({[Company], " ", [Metric]}), type text)
in
  #"Inserted Merged Column"&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="markup"&gt;Company Comments Table
let
  Source = Lakehouse.Contents(null),
  Navigation = Source{[workspaceId = &amp;lt;your-workspace-id&amp;gt;]}[Data],
  #"Navigation 1" = Navigation{[lakehouseId = &amp;lt;your-lakehouse-id&amp;gt;]}[Data],
  #"Navigation 2" = #"Navigation 1"{[Id = "Files", ItemKind = "Folder"]}[Data],
  #"Navigation 3" = #"Navigation 2"{[Name = "translytical - source tables.xlsx"]}[Content],
  #"Imported Excel workbook" = Excel.Workbook(#"Navigation 3", null, true),
  #"Navigation 4" = #"Imported Excel workbook"{[Item = "Company Metrics", Kind = "Sheet"]}[Data],
  #"Promoted headers" = Table.PromoteHeaders(#"Navigation 4", [PromoteAllScalars = true]),
  #"Changed column type" = Table.TransformColumnTypes(#"Promoted headers", {{"ID", Int64.Type}, {"Company", type text}, {"Check", Int64.Type}, {"Metric", type text}, {"Year", Int64.Type}, {"Value", type number}, {"Comment", type text}}),
  #"Removed columns" = Table.RemoveColumns(#"Changed column type", {"Value", "Year", "Check"}),
  #"Grouped rows" = Table.Group(#"Removed columns", {"Company", "Metric", "Comment"}, {{"ID", each List.Max([ID]), type nullable Int64.Type}}),
  #"Reordered columns" = Table.ReorderColumns(#"Grouped rows", {"ID", "Company", "Metric", "Comment"}),
  #"Inserted Merged Column" = Table.AddColumn(#"Reordered columns", "RelationshipKey", each Text.Combine({[Company], " ", [Metric]}), type text)
in
  #"Inserted Merged Column"&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Set the Dataflow Gen2 to load the tables into a Fabric SQL database. In my case I had created a Fabric SQL Database called &lt;EM&gt;translytical_sql&lt;/EM&gt; so I simply pointed the Dataflow Gen 2 destination settings to that SQL DB and that it creates a new table for each.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;img /&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;img /&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Now that the needed source tables are set up, we can move on to creating the user data function. After creating the function, ensure you add the SQL DB connection via managed connection and then you can use my code below.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;img /&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Don't bother trying to rename the default function that shows when you click "Add Function", it will change once you rename what's right after def in your code (the Python function name). Ensure the alias is same as your managed connection alias (see image above for mine).&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="python"&gt;#insert_comment function

import fabric.functions as fn

udf = fn.UserDataFunctions()

@udf.connection(argName='sqlDB', alias='translyticalsql')
@udf.function()

def insert_comment(sqlDB: fn.FabricSqlConnection, metricId: int, metric: str, company: str, comment: str) -&amp;gt; str:
    '''
    Description: Inserts a comment into the SQL table of the financials.
    
    Args:
        sqlDB (fn.FabricSqlConnection): Fabric SQL database connection.
        metric_id (int): metric id (primary key).
        comment (str): the comment to add
    
    Returns:
        str: Confirmation message about data insertion.
        
    '''

    # Set up the connection to the SQL database
    connection = sqlDB.connect()
    cursor = connection.cursor()
 
    # Insert the comment into the company metrics table
    add_comment_query = "UPDATE [dbo].[CompanyComments] SET [comment] = ? WHERE [ID] = ?;"
    cursor.execute(add_comment_query, (comment, metricId))

    # Commit the transaction
    connection.commit()

    # Close the connection
    cursor.close()
    connection.close()               
    return f'Financial metric "{metric}" for company "{company}" was updated with the following comment: {comment}'&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;With the function done, you can now move to the final part: doing the Power BI report. I have attached the actual Power BI report. The major things to remember are:&lt;/P&gt;&lt;OL&gt;&lt;LI&gt;Enable translytical in preview settings&lt;/LI&gt;&lt;LI&gt;Use Text slicer for the comment entry box&lt;/LI&gt;&lt;LI&gt;Enter a name in the Text slicer's General Settings' title field. That name gets picked up in the button action settings. You can turn the title display off after that.&lt;/LI&gt;&lt;LI&gt;Add a regular button as the clickable visual that triggers the function&lt;/LI&gt;&lt;LI&gt;Set metricid in the action fields for the button to maximum [ID] for [CompanyMetrics][ID]. That's how my table structure is set up to work properly vis-a-vis the comment posting.&lt;/LI&gt;&lt;LI&gt;You can set metric and company to first or last, doesn't matter. But use the fields from [CompanyMetrics] table&lt;/LI&gt;&lt;LI&gt;Add a placeholder to the Text Slicer and a tooltip to the button.&lt;/LI&gt;&lt;LI&gt;Lastly, disable the filter interaction of the "Metric for Comment" slicer on the main report table.&amp;nbsp;&lt;/LI&gt;&lt;/OL&gt;&lt;P&gt;&lt;img /&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;And that's all! You can test on your Power BI desktop app before publishing to the web service.&lt;/P&gt;&lt;P&gt;&lt;img /&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Enjoy your first/new business relevant translytical!&lt;/P&gt;</description>
      <pubDate>Tue, 26 Aug 2025 17:50:59 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Add-Commentary-to-Financial-Reports-using-Translytical/m-p/4806042#M16</guid>
      <dc:creator>michaelolafusi</dc:creator>
      <dc:date>2025-08-26T17:50:59Z</dc:date>
    </item>
    <item>
      <title>IoT Defect Tracking and Resolution from PBI report</title>
      <link>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/IoT-Defect-Tracking-and-Resolution-from-PBI-report/m-p/4804799#M15</link>
      <description>&lt;H2&gt;&lt;FONT color="#000000"&gt;&lt;STRONG&gt;Scenario description: IoT-Driven Maintenance with Power BI Writeback&lt;/STRONG&gt;&lt;/FONT&gt;&lt;/H2&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;STRONG&gt;Overview&lt;/STRONG&gt;&lt;BR /&gt;In this workflow, industrial equipment is fitted with IoT sensors streaming operational metrics (temperature, vibration, pressure, etc.) into a real-time event stream. An event processor (Activator) continuously evaluates incoming readings against expected patterns. If a defect or anomaly is detected, the system:&lt;/P&gt;&lt;OL&gt;&lt;LI&gt;&lt;P&gt;Sends an instant notification to the maintenance worker’s mobile device.&lt;/P&gt;&lt;/LI&gt;&lt;LI&gt;&lt;P&gt;Creates a new defect tracking record in the operational SQL database with initial details.&lt;/P&gt;&lt;/LI&gt;&lt;/OL&gt;&lt;P&gt;After performing the repair, the maintenance worker accesses a Power BI maintenance dashboard. Here, they can:&lt;/P&gt;&lt;UL&gt;&lt;LI&gt;&lt;P&gt;Review the defect record (with sensor data snapshots, alerts, and location).&lt;/P&gt;&lt;/LI&gt;&lt;LI&gt;&lt;P&gt;Document the defect resolution, root cause, and parts replaced.&lt;/P&gt;&lt;/LI&gt;&lt;LI&gt;&lt;P&gt;Submit this information directly back to the SQL defect tracking table via a &lt;STRONG&gt;User Data Function (UDF)&lt;/STRONG&gt;.&lt;/P&gt;&lt;/LI&gt;&lt;/UL&gt;&lt;P&gt;&lt;img /&gt;&lt;/P&gt;&lt;P&gt; &lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;The UDF securely updates the operational database in real time, eliminating the need for separate maintenance forms or manual syncing. This ensures that historical defect data stays complete, accurate, and available for both operational and analytical purposes.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Here is the code used for this scenario to update the defect after resolving it through workforce:&lt;/P&gt;&lt;LI-CODE lang="markup"&gt;import fabric.functions as fn

udf = fn.UserDataFunctions()

# ===============================
# UDF: update_defect_resolution
# ===============================

# Take a defect id, resolver, resoltuion notes and parts replaced (Status will be set automatically to "closed" as this is the intended action) as input parameters
# Write the data back to the SQL database
# Users will provide these parameters in the PowerBI report
@udf.connection(argName="sqlDB",alias="&amp;lt;Your DB alias from connections&amp;gt;") 
@udf.function() 
def update_defect_resolution(sqlDB: fn.FabricSqlConnection, 
                            defectid: int,
                            resolvedby: str,
                            resolutionnotes: str,
                            partsreplaced: str) -&amp;gt; str:
    """
    Updates defect tracking record in the operational SQL database.
    Status is default set to "Closed" if a resolution is entered.

    Parameters:
    -----------
    defectid : int
        Unique identifier of the defect record.
    resolvedby : str
        Name or ID of the maintenance worker.
    resolutionnotes : str
        Description of how the defect was resolved.
    partsreplaced : str
        Comma-separated list of parts replaced.

    Returns:
    --------
    str
        "Defect resolution updated successfully."
    """

    try:
        # Establish a connection to the SQL database  
        connection = sqlDB.connect() 
        cursor = connection.cursor() 

        # Update query
        query = """
        UPDATE [maintenance_demo].[defect_tracking]
        SET resolved_by = ?,
            resolution_notes = ?,
            parts_replaced = ?,
            status = 'Closed',
            resolution_timestamp = GETUTCDATE()
        WHERE defect_id = ?
        """

        # Execute update
        cursor.execute(query, (resolvedby, resolutionnotes, partsreplaced, defectid))
        
        # Commit the transaction 
        connection.commit() 
        cursor.close() 
        connection.close() 

        return "Defect resolution updated successfully."

    except Exception as e:
        return {
            "defect_id": defectid,
            "status": "Error",
            "message": str(e)
        }&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;SPAN&gt;Feel free to use this code as inspiration for your own scenarios!&lt;/SPAN&gt;&lt;/P&gt;</description>
      <pubDate>Mon, 25 Aug 2025 08:25:27 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/IoT-Defect-Tracking-and-Resolution-from-PBI-report/m-p/4804799#M15</guid>
      <dc:creator>Mauro89</dc:creator>
      <dc:date>2025-08-25T08:25:27Z</dc:date>
    </item>
    <item>
      <title>Handling Multi-Row Inputs for Translytical Task Flows</title>
      <link>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Handling-Multi-Row-Inputs-for-Translytical-Task-Flows/m-p/4794940#M14</link>
      <description>&lt;DIV class="lia-align-justify"&gt;&lt;SPAN&gt;This post offers a practical guide to passing multiple rows of data from a Power BI report to a User-Defined Function (UDF) using translytical task flows. The solution leverages the &lt;/SPAN&gt;&lt;STRONG&gt;TOJSON()&lt;/STRONG&gt;&lt;SPAN&gt;&amp;nbsp;DAX function to overcome the limitation of scalar-only inputs from slicers.&lt;/SPAN&gt;&lt;/DIV&gt;
&lt;DIV class="lia-align-justify"&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;DIV&gt;
&lt;H1&gt;&lt;SPAN&gt;Translytical Task Flows&lt;/SPAN&gt;&lt;/H1&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;DIV&gt;
&lt;DIV&gt;&lt;SPAN&gt;At their core translytical task flows allow buttons within your Power BI reports to trigger a UDF. Within the button definition you map a button, list, or text slicer; a data field; or measures from the report to the input parameters of the UDF. However, a key limitation is that when using a slicer, you can only pass a single (scalar) value. If a user selects multiple items, the button becomes inactive, preventing the UDF from being called. But with a measures, you are able to pass tabular data a string, with the help of the seldomly used DAX function &lt;/SPAN&gt;&lt;STRONG&gt;TOJSON()&lt;/STRONG&gt;&lt;SPAN&gt;.&lt;/SPAN&gt;&lt;/DIV&gt;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;DIV&gt;
&lt;H1&gt;&lt;SPAN&gt;Sudoku&lt;/SPAN&gt;&lt;/H1&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;DIV&gt;&lt;SPAN&gt;This example uses a Sudoku game built with Power BI to demonstrate the solution. The game state is stored in a Fabric SQL database, and UDFs are used to manage game actions.&lt;/SPAN&gt;&lt;/DIV&gt;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;DIV&gt;&lt;SPAN&gt;&lt;SPAN&gt;&lt;img /&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/DIV&gt;
&lt;DIV&gt;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;DIV&gt;&lt;SPAN&gt;The game UI consists of several components:&lt;/SPAN&gt;&lt;/DIV&gt;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;STRONG&gt;Game Selection:&lt;/STRONG&gt;&lt;SPAN&gt;&amp;nbsp;A slicer to select a game template.&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN&gt;&lt;STRONG&gt;Game Grid:&lt;/STRONG&gt;&amp;nbsp;&lt;/SPAN&gt;&lt;SPAN&gt;A button slicer representing the 81 cells of the Sudoku board. Each button uses a DAX-generated SVG to display numbers and pencil marks.&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN&gt;&lt;STRONG&gt;Number Selector:&lt;/STRONG&gt;&amp;nbsp;&lt;/SPAN&gt;&lt;SPAN&gt;A button slicer for selecting the number to enter (1-9).&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;STRONG&gt;Pen/Pencil Buttons:&lt;/STRONG&gt;&lt;SPAN&gt;&amp;nbsp;Buttons that trigger UDFs to enter numbers or pencil marks into the selected cell(s).&lt;/SPAN&gt;&lt;/LI&gt;
&lt;/UL&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;DIV&gt;&lt;SPAN&gt;The architecture is as follow:&lt;/SPAN&gt;&lt;/DIV&gt;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;DIV&gt;&lt;SPAN&gt;&lt;SPAN&gt;&lt;img /&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;DIV&gt;
&lt;DIV&gt;&lt;SPAN&gt;The Pen and Pencil buttons are mapped to the &lt;STRONG&gt;p&lt;/STRONG&gt;&lt;/SPAN&gt;&lt;STRONG&gt;osition&lt;/STRONG&gt;&lt;SPAN&gt;&lt;STRONG&gt;&amp;nbsp;&lt;/STRONG&gt;from the grid button slicer and the &lt;/SPAN&gt;&lt;STRONG&gt;value&lt;/STRONG&gt;&lt;SPAN&gt;&amp;nbsp;from the value selector button slicer. This works perfectly for a single cell selection.&lt;/SPAN&gt;&lt;/DIV&gt;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;DIV&gt;&lt;SPAN&gt;&lt;SPAN&gt;&lt;SPAN&gt;&lt;img /&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;DIV&gt;
&lt;DIV&gt;&lt;SPAN&gt;Generally in Sudoku, you want to mark two or more cells simultaneously when entering pencil marks. However when we select more than one cell, the Pen and Pencil buttons becomes inactive:&lt;/SPAN&gt;&lt;/DIV&gt;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;DIV&gt;&lt;SPAN&gt;&lt;SPAN&gt;&lt;img /&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;DIV&gt;
&lt;H1&gt;&lt;SPAN&gt;Using TOJSON() to Pass Tabular Data&lt;/SPAN&gt;&lt;/H1&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;DIV&gt;
&lt;DIV&gt;&lt;SPAN&gt;To enable multi-cell input, we need a method to generate a single string that encapsulates information about multiple selected positions. For those familiar with REST APIs, calling the UDF in this context is analogous to a POST request, where the JSON format is the preferred payload.&lt;/SPAN&gt;&lt;/DIV&gt;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;DIV&gt;&lt;SPAN&gt;Fortunately, DAX provides a perfect solution: the built-in &lt;/SPAN&gt;&lt;STRONG&gt;TOJSON()&lt;/STRONG&gt;&lt;SPAN&gt;&lt;STRONG&gt;&amp;nbsp;&lt;/STRONG&gt;function. This function generates a JSON string from a given table. We can create a DAX measure that generates a JSON string containing all the selected grid positions.&lt;/SPAN&gt;&lt;/DIV&gt;
&lt;DIV&gt;&lt;LI-CODE lang="markup"&gt;Selected Positions = 
IF(
    ISFILTERED( 'Grid Position'[Position] ),
    TOJSON( VALUES( 'Grid Position'[Position] ) )
)&lt;/LI-CODE&gt;
&lt;DIV&gt;
&lt;DIV&gt;&lt;SPAN&gt;This provides the following output:&lt;/SPAN&gt;&lt;/DIV&gt;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;DIV&gt;&lt;SPAN&gt;&lt;SPAN&gt;&lt;img /&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;DIV&gt;
&lt;DIV&gt;&lt;SPAN&gt;We can update the mapping from the position provided by the grid button slicer, to the DAX measure:&lt;/SPAN&gt;&lt;/DIV&gt;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;DIV&gt;&lt;SPAN&gt;&lt;SPAN&gt;&lt;img /&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;DIV&gt;
&lt;H1&gt;&lt;SPAN&gt;Handling the JSON in the UDF&lt;/SPAN&gt;&lt;/H1&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;DIV&gt;&lt;SPAN&gt;The Python code in the UDF can then parse this string back into a list of positions to be processed.&lt;/SPAN&gt;&lt;/DIV&gt;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;DIV&gt;&lt;LI-CODE lang="python"&gt;import fabric.functions as fn
import json
from datetime import datetime

udf = fn.UserDataFunctions()
    
@udf.connection(argName="sqlDB", alias="Game")
@udf.function()
def toggle_pencil_mark(sqlDB: fn.FabricSqlConnection, gameId: int, position: str, pencilValue: int) -&amp;gt; str:
    """
    Toggle a pencil mark in a Sudoku cell
    
    Args:
        gameId: The game ID
        position: JSON string with cell positions
        pencilValue: Pencil mark value (1-9)
        
    Returns:
        JSON string with operation result
    """
    # Parse positions from JSON
    positions_data = json.loads(position)
    positions = [pos[0] for pos in positions_data["data"]]
    
    ## Open connection and SQL database and write values to cells
    conn = sqlDB.connect()
    cursor = conn.cursor()
    
    processed_positions = []
    last_action_type = None
    last_is_active = False
    
    for pos in positions:
        # Skip cells with values
        cursor.execute("SELECT CurrentValue FROM GameState WHERE GameId = ? AND Position = ?", (gameId, pos))
        if cursor.fetchone()[0] is not None:
            continue
        
        # Toggle pencil mark
        cursor.execute("EXEC sp_TogglePencilMark ?, ?, ?", (gameId, pos, pencilValue))
        conn.commit()
        
        # Check if added or removed
        cursor.execute("SELECT IsActive FROM PencilMarks WHERE GameId = ? AND Position = ? AND PencilValue = ?", 
                      (gameId, pos, pencilValue))
        is_active = cursor.fetchone()[0]
        last_action_type = "added" if is_active else "removed"
        last_is_active = is_active
        
        processed_positions.append(pos)
    
    cursor.close()
    conn.close()
    
    return json.dumps({
        "status": "SUCCESS",
        "message": f"Pencil mark {pencilValue} {last_action_type} at position(s) {processed_positions}",
        "game_id": gameId,
        "positions_processed": processed_positions,
        "pencil_value": pencilValue,
        "is_active": last_is_active,
        "action_type": last_action_type,
        "action_time": datetime.now().isoformat()
    })&lt;/LI-CODE&gt;
&lt;DIV&gt;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;DIV&gt;&lt;SPAN&gt;By parsing the JSON string, the UDF can now iterate through the list of positions and perform the required database operations for each one. This allows players to mark multiple cells with the same pencil value simultaneously.&lt;/SPAN&gt;&lt;/DIV&gt;
&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;
&lt;DIV&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;SPAN&gt;This approach is highly versatile and can be used as a template for any scenario where you need to pass multiple selected items from a Power BI report to a UDF.&lt;/SPAN&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;SPAN&gt;More in-depth details can be found at these blog posts:&lt;/SPAN&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;A href="https://evaluationcontext.github.io/posts/sudoku/" target="_self"&gt;&lt;SPAN&gt;Translytical Sudoku&lt;/SPAN&gt;&lt;/A&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;A href="https://evaluationcontext.github.io/posts/translytical-rows/" target="_self"&gt;&lt;SPAN&gt;Handling Multi-Row Inputs for Translytical Task Flows&lt;/SPAN&gt;&lt;/A&gt;&lt;/LI&gt;
&lt;/UL&gt;
&lt;/DIV&gt;
&lt;DIV&gt;&lt;BR /&gt;
&lt;DIV&gt;&lt;SPAN&gt;Hope this example is useful and sparks some ideas!&lt;/SPAN&gt;&lt;/DIV&gt;
&lt;/DIV&gt;
&lt;/DIV&gt;
&lt;/DIV&gt;
&lt;/DIV&gt;
&lt;/DIV&gt;
&lt;/DIV&gt;
&lt;/DIV&gt;
&lt;/DIV&gt;
&lt;/DIV&gt;
&lt;/DIV&gt;
&lt;/DIV&gt;
&lt;/DIV&gt;
&lt;/DIV&gt;
&lt;/DIV&gt;
&lt;/DIV&gt;
&lt;/DIV&gt;
&lt;/DIV&gt;
&lt;/DIV&gt;
&lt;/DIV&gt;
&lt;/DIV&gt;</description>
      <pubDate>Mon, 13 Oct 2025 17:49:55 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Handling-Multi-Row-Inputs-for-Translytical-Task-Flows/m-p/4794940#M14</guid>
      <dc:creator>Deku</dc:creator>
      <dc:date>2025-10-13T17:49:55Z</dc:date>
    </item>
    <item>
      <title>Custom AI integration</title>
      <link>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Custom-AI-integration/m-p/4702823#M8</link>
      <description>&lt;P&gt;You can enable custom-tailored AI assistance directly on your report or kick off AI-powered custom workflows.&lt;BR /&gt;&lt;BR /&gt;&lt;/P&gt;
&lt;P&gt;Example, you can integrate Azure OpenAI into your report to help plan your next proposal while factoring in context from the report.&amp;nbsp;You simply select the influencer and click the ‘Generate AI Suggestion’ button, which runs a Fabric User data function that instantly provides an Azure OpenAI response based on a fully customizable prompt.&lt;BR /&gt;&lt;BR /&gt;&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;SPAN&gt;Here is the Python code for the user data function that powers this scenario:&amp;nbsp;&lt;/SPAN&gt;&lt;/P&gt;
&lt;LI-CODE lang="python"&gt;import fabric.functions as fn
import logging
import openai

udf = fn.UserDataFunctions()
@udf.connection(argName="sqlDB",alias="Translytical")
@udf.function()
def AISuggestion(sqlDB: fn.FabricSqlConnection, company: str) -&amp;gt; str :
    logging.info('Python UDF trigger function processed a request.')

    # Establish a connection to the SQL database
    connection = sqlDB.connect()
    cursor = connection.cursor()

    #Get offer status for the company 
    SQL_read_Command = "SELECT * FROM [dbo].[CompanyStatus] WHERE Company = ?"
    cursor.execute(SQL_read_Command, company)
    record = cursor.fetchone()    
    customer_name = record[0]
    last_comment = record[10]
    
    #Submit prompt to Azure OpenAI and get an AI suggestion
    prompt = "Respond with a short plan that is under 240 characters: I work at Contoso Outdoors, and we collaborate with influencers by offering them offers for custom designed bikes. Pretend we want to collab with the following influencer: " + customer_name +" from company: " + company + ". Here's a comment about their latest feedback " + last_comment + "."
    deployment = "gpt-4o"
    openai_client = openai.AzureOpenAI(
     api_key='&amp;lt;API Key here&amp;gt;',
     api_version = "2025-01-01-preview",
     azure_endpoint = "https://sico-oai-eus2.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2025-01-01-preview"
    )
    response = openai_client.chat.completions.create(
        model=deployment,
        messages=[
            {"role": "user", "content": prompt}
        ]
    )
    result = response.choices[0].message.content

    #Check if there is an exisiting AI suggestion for the company 
    SQL_read_Command = "SELECT * FROM [dbo].[AISuggestions] WHERE Company = ?"
    cursor.execute(SQL_read_Command, company)

    if cursor.fetchone():
        #if there is an existing AI suggestion record for the company, update just the AI suggestion
        SQL_update_command = "UPDATE [dbo].[AISuggestions] SET [AI_suggestion] = ? WHERE [Company] = ?;"
        Existing_Suggestion = (result, company)
        cursor.execute(SQL_update_command, Existing_Suggestion)
                    
    else:
        #if there is NOT an existing AI suggestion record for the company, add a new record
        SQL_insert_command = "INSERT INTO [dbo].[AISuggestions](Name, Company, AI_suggestion) VALUES(?, ?, ?);"
        New_Suggestion = (customer_name, company, result)
        cursor.execute(SQL_insert_command, New_Suggestion)
            
    # Commit the transaction
    connection.commit()
    
    # Close the connection
    cursor.close()
    connection.close()

    return f"Generated Azure OpenAI suggestion for collaboration ideas with " + customer_name + " from " + company + "."&lt;/LI-CODE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;SPAN&gt;Feel free to use this code as inspiration for your own custom AI integration scenarios!&lt;/SPAN&gt;&lt;/P&gt;</description>
      <pubDate>Fri, 23 May 2025 15:21:48 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Custom-AI-integration/m-p/4702823#M8</guid>
      <dc:creator>SujataNarayana</dc:creator>
      <dc:date>2025-05-23T15:21:48Z</dc:date>
    </item>
    <item>
      <title>Approval workflows</title>
      <link>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Approval-workflows/m-p/4702782#M7</link>
      <description>&lt;P&gt;You can allow users to kick-off approval workflows to enable admins or specific users to approve or reject various requests.&lt;BR /&gt;&lt;BR /&gt;&lt;/P&gt;
&lt;P&gt;For example, on the report below non-admin users can propose a discount and submit it as request such that an admin will be notified of the request.&lt;BR /&gt;&lt;BR /&gt;&lt;img /&gt;&lt;BR /&gt;&lt;BR /&gt;&lt;SPAN&gt;The admin will get the discount request in a Teams channel, and when they click approve, they are redirected to a separate admin report that is automatically filtered to the right data and shows the requested discount percentage. The admin can do the final review and apply the requested discount.&lt;BR /&gt;&lt;BR /&gt;&lt;img /&gt;&lt;BR /&gt;&lt;BR /&gt;This approval workflow scenarios requires two user data functions to:&lt;/SPAN&gt;&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;&lt;SPAN&gt;Send a request : Request for an admin to approve a discount&lt;/SPAN&gt;&lt;/LI&gt;
&lt;LI&gt;&lt;SPAN&gt;Approve a request: Admin can apply the discount&lt;/SPAN&gt;&lt;/LI&gt;
&lt;/UL&gt;
&lt;P&gt;&lt;SPAN&gt;Here is the user data function for the&amp;nbsp;&lt;STRONG&gt;Send a request&lt;/STRONG&gt;&amp;nbsp;scenario:&amp;nbsp;&lt;/SPAN&gt;&lt;/P&gt;
&lt;LI-CODE lang="python"&gt;import fabric.functions as fn
import logging
import requests

# Initialize the UserDataFunctions
udf = fn.UserDataFunctions()

#This function is designed for sending an approval request message to a specific Microsoft Teams channel using the Microsoft Graph API
@udf.function()
def RequestDiscount(user: str, comment: str, discount: float, revenue: float, URLfilter: str) -&amp;gt; str :

    logging.info('Python UDF trigger function processed a request.')
    try:
        
        # Define the endpoint URL for Microsoft Graph API to send a message to Teams
        team_id = "&amp;lt;team id&amp;gt;"  # Replace with your actual team ID
        channel_id = "&amp;lt;channel id&amp;gt;"  # Replace with your actual channel ID
        url = f"https://graph.microsoft.com/v1.0/teams/{team_id}/channels/{channel_id}/messages"
         

        # Define the headers including the authorization token
        headers = {
            "Authorization": "&amp;lt;auth token here&amp;gt;",  
            "Content-Type": "application/json"
        }
          

        Discountpercent = str(discount) + "%"
        Discountdollars = '${:,.2f}'.format(((discount/100) * revenue))
       
        ApprovalURL = "&amp;lt;Report URL here&amp;gt;" + URLfilter + "%20and%20DiscountValues%2FValues%20eq%20" + str(discount) #add your report URL here
        
        # Define the message body with HTML links
        #I only configured an approval flow for demo purposes. You will need to add reject action as well or remove this option.
        message_body = f"""
            &amp;lt;div&amp;gt;
                &amp;lt;strong&amp;gt;Discount Request from {user}&amp;lt;/strong&amp;gt;&amp;lt;br&amp;gt;
                &amp;lt;p&amp;gt;Discount percentage: {Discountpercent}&amp;lt;/p&amp;gt; 
                &amp;lt;p&amp;gt;Discount total: {Discountdollars}&amp;lt;/p&amp;gt;
                &amp;lt;p&amp;gt;Comment: {comment}&amp;lt;/p&amp;gt;
                &amp;lt;p&amp;gt;
                    &amp;lt;a href={ApprovalURL} target="_blank"&amp;gt;Approve&amp;lt;/a&amp;gt;  |   
                    &amp;lt;a href="https://example.com/reject" target="_blank"&amp;gt;Reject&amp;lt;/a&amp;gt; 
                &amp;lt;/p&amp;gt;
            &amp;lt;/div&amp;gt;
        """

        # Define the payload
        payload = {
            "body": {
                "content": message_body,
                "contentType": "html"
            }
        }
        
        # Make the POST request to the Microsoft Graph API
        response = requests.post(url, headers=headers, json=payload)
      
        # Check if the request was successful
        if response.status_code == 201:
            return "Approval request successfully posted in Teams."
        else:
            raise fn.UserThrownError("Failed to post approval request.", {"Status code": response.status_code}, {"Response": response.text})  
            
    except Exception as e:
        raise fn.UserThrownError("We ran into an issue.", {"Error:": str(e)})&lt;/LI-CODE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;SPAN&gt;Here is the user data function for the &lt;STRONG&gt;Approve a&amp;nbsp;request&lt;/STRONG&gt;&amp;nbsp;scenario:&amp;nbsp;&lt;/SPAN&gt;&lt;/P&gt;
&lt;LI-CODE lang="python"&gt;import fabric.functions as fn
import logging

udf = fn.UserDataFunctions()

@udf.connection(argName="sqlDB", alias="Translytical")
@udf.function()
def ApproveDiscount(sqlDB: fn.FabricSqlConnection, opportunities: str, discountinput: float, comment: str)-&amp;gt;str :
     
    logging.info('Python UDF trigger function processed a request.')
    
    connection = sqlDB.connect()
    cursor = connection.cursor()

    if (discount &amp;lt; 0):
        raise fn.UserThrownError("Discount cannot be negative")
    if (discount &amp;gt; 1):
        discount = discount / 100
    if (discount &amp;gt; 0.50):
        raise fn.UserThrownError("Discount cannot exceed 50%")

    # SQL update command
    SQL_update_command = "UPDATE [dbo].[Opportunity] SET [Discount] = " + str(discount) + " WHERE Opportunity_Number IN (" + opportunities + ")"
    cursor.execute(SQL_update_command)
                           
    # Commit the transaction
    connection.commit()

    # Close the connection
    cursor.close()
    connection.close()
    
    try:
        # Define the endpoint URL for Microsoft Graph API to send a message to Teams
        team_id = "&amp;lt;team id&amp;gt;"  # Replace with your actual team ID
        channel_id = "&amp;lt;channel id&amp;gt;"  # Replace with your actual channel ID
        url = f"https://graph.microsoft.com/v1.0/teams/{team_id}/channels/{channel_id}/messages"
         

        # Define the headers including the authorization token
        headers = {
            "Authorization": "&amp;lt;auth token here&amp;gt;",  
            "Content-Type": "application/json"
        }
                  
  
        # Define the message body with comment
        message_body = f"""
            &amp;lt;div&amp;gt;
                &amp;lt;strong&amp;gt;Approved Discount Request&amp;lt;/strong&amp;gt;&amp;lt;br&amp;gt;
                &amp;lt;p&amp;gt;Comment: {comment}&amp;lt;/p&amp;gt;
            &amp;lt;/div&amp;gt;
        """

        # Define the payload
        payload = {
            "body": {
                "content": message_body,
                "contentType": "html"
            }
        }
        
        # Make the POST request to the Microsoft Graph API
        response = requests.post(url, headers=headers, json=payload)
      
        # Check if the request was successful
        if response.status_code == 201:
            return "Discount has been approved and applied. Team has been notified."
        else:
            raise fn.UserThrownError("Failed to post approval request.", {"Status code": response.status_code}, {"Response": response.text})  
            
    except Exception as e:
        raise fn.UserThrownError("We ran into an issue.", {"Error:": str(e)})&lt;/LI-CODE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;SPAN&gt;Feel free to use this code as inspiration for your approval workflow scenarios!&lt;/SPAN&gt;&lt;/P&gt;</description>
      <pubDate>Fri, 23 May 2025 15:24:28 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Approval-workflows/m-p/4702782#M7</guid>
      <dc:creator>SujataNarayana</dc:creator>
      <dc:date>2025-05-23T15:24:28Z</dc:date>
    </item>
    <item>
      <title>Dynamic email notifications</title>
      <link>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Dynamic-email-notifications/m-p/4702505#M6</link>
      <description>&lt;P&gt;You can trigger dynamic notifications to raise awareness or promote a call to action.&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;In this example report, changing an offer status to ‘Accepted’ will automatically send a dynamic marketing email to the partner company’s point of contact.&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;SPAN&gt;Here is the Python code for the user data function that powers this scenario:&amp;nbsp;&lt;/SPAN&gt;&lt;/P&gt;
&lt;LI-CODE lang="python"&gt;import fabric.functions as fn
import logging
import requests
from flask import Flask
from flask_mail import Mail, Message

udf = fn.UserDataFunctions()
app = Flask(__name__) 
mail = Mail(app) # instantiate the mail class 

# configuration of mail 
app.config['MAIL_SERVER']='smtp.sendgrid.net'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USERNAME'] = 'apikey'
app.config['MAIL_PASSWORD'] = '&amp;lt;your API key here&amp;gt;'
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_DEFAULT_SENDER'] = '&amp;lt;your email here&amp;gt;'
mail = Mail(app) 

html_email = """ &amp;lt;Your HTML email here&amp;gt;
"""

@udf.connection(argName="sqlDB",alias="Translytical")
@udf.function()

def get_data_write_to_sql_db_send_email(sqlDB: fn.FabricSqlConnection, company: str, status: str, date:str, comment: str) -&amp;gt; str:
    logging.info('Python UDF trigger function processed a request.')    

    # Error handling for no status selected or no company input
    if(status=="" or len(status) &amp;lt; 1):
        raise fn.UserThrownError("The status isn't valid.", {"status:": status})

    if(company=="" or len(company) &amp;lt; 1):
        raise fn.UserThrownError("The company isn't valid.", {"company:": company})          
    
    #Call External API to get Company contact information
    url = "https://dummy-json.mock.beeceptor.com/users"
    response = requests.get(url)

    if response.status_code == 200:
        Jsondata = response.json()

        for i in Jsondata:
            #Check if company contact is registered in the external system
            if i['company'] == company:

                # Combine timestamp with comment
                comment_value = date + " - " + comment

                # Get customer contact and put in format based on if updating an record or adding new record
                Existing_Partner_data = (i['name'], i['username'], i['email'], i['address'], i['zip'], i['state'], i['country'], i['phone'], status, comment_value, company)
                New_Partner_data = (i['name'], company, i['username'], i['email'], i['address'], i['zip'], i['state'], i['country'], i['phone'], status, comment_value)

                # Establish a connection to the SQL database
                connection = sqlDB.connect()
                cursor = connection.cursor()

                #Check if there is a status record for the company 
                SQL_read_Command = "SELECT * FROM [dbo].[CompanyStatus] WHERE Company = ?"
                cursor.execute(SQL_read_Command, company)
                if cursor.fetchone():
                    #if there is a status record for the company, update the status and contact info
                    SQL_update_command = "UPDATE [dbo].[CompanyStatus] SET [Name] = ?, [Username] = ?, [Email] = ?, [Address] = ?, [Zip] = ?, [State] = ?, [Country] = ?, [Phone] = ?, [Status] = ?, [Comment] =  ? WHERE [Company] = ?;"
                    cursor.execute(SQL_update_command, Existing_Partner_data)
                    
                else:
                    #if there is not a status record for the company, add new record
                    SQL_insert_command = "INSERT INTO [dbo].[CompanyStatus](Name, Company, Username, Email, Address, Zip, State, Country, Phone, Status, Comment) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"
                    cursor.execute(SQL_insert_command, New_Partner_data)
            
                # Commit the transaction
                connection.commit()

                # Close the connection
                cursor.close()
                connection.close()
                
                #If status is set to accepted, send an email to company contact
                #Note: this is hard-coded to a temp working email for demo purposes
                if(status == "Accepted"):
                  with app.app_context():
                      msg = Message (company + " x Contoso collab time!",
                                      recipients = ['&amp;lt;Email here&amp;gt;'] #I put a static temp email here but you can make this dynamic
                                  )
                      msg.html = html_email
                      mail.send(msg)
                      return "Accepted collab offer with " + company + ", and " + i['name'] + " will be notified shortly."

                return "Collab with " + company + " is now " + status.lower() + "."

        #if reached here in the code, then the company contact is NOT registered in the external system, throw error   
        raise fn.UserThrownError("The company is not a registered partner.", {"company:": company})&lt;/LI-CODE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;SPAN&gt;Feel free to use this code as inspiration for your own dynamic notification scenario!&lt;/SPAN&gt;&lt;/P&gt;</description>
      <pubDate>Fri, 23 May 2025 15:25:10 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Dynamic-email-notifications/m-p/4702505#M6</guid>
      <dc:creator>SujataNarayana</dc:creator>
      <dc:date>2025-05-23T15:25:10Z</dc:date>
    </item>
    <item>
      <title>Augment data on the fly</title>
      <link>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Augment-data-on-the-fly/m-p/4702500#M5</link>
      <description>&lt;P&gt;You can programmatically fetch additional data related to the data within your report.&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Example, you can use this report to not only track and update the status of various collaborations, but you can also fetch additional data via API, such as the latest contact information for a registered partner company.&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Here is the Python code for the user data function that powers this scenario:&amp;nbsp;&lt;/P&gt;
&lt;LI-CODE lang="python"&gt;import fabric.functions as fn
import logging
import requests

udf = fn.UserDataFunctions()

@udf.connection(argName="sqlDB",alias="Translytical")
@udf.function()
def GetContactInfo(sqlDB: fn.FabricSqlConnection, company: str, status: str, date:str, comment: str) -&amp;gt; str:
    logging.info('Python UDF trigger function processed a request.')    

    # Error handling for no status selected or no company input
    if(status=="" or len(status) &amp;lt; 1):
        raise fn.UserThrownError("The status isn't valid.", {"status:": status})

    if(company=="" or len(company) &amp;lt; 1):
        raise fn.UserThrownError("The company isn't valid.", {"company:": company})             
    
    #Call External API to get contact info within registered partner company
    url = "https://dummy-json.mock.beeceptor.com/users"
    response = requests.get(url)
    
    if response.status_code == 200:
        Jsondata = response.json()
        for i in Jsondata:
            #Check if company contact is registered in the external system
            if i['company'] == company:

                # Combine timestamp with comment
                comment_value = date + " - " + comment
                
                # Get customer contact and put in format based on if updating an record or adding new record
                Existing_Partner_data = (i['name'], i['username'], i['email'], i['address'], i['zip'], i['state'], i['country'], i['phone'], status, comment_value, company)
                New_Partner_data = (i['name'], company, i['username'], i['email'], i['address'], i['zip'], i['state'], i['country'], i['phone'], status, comment_value)

                # Establish a connection to the SQL database
                connection = sqlDB.connect()
                cursor = connection.cursor()

                #Check if there is a status record for the company 
                SQL_read_Command = "SELECT * FROM [dbo].[CompanyStatus] WHERE Company = ?"
                cursor.execute(SQL_read_Command, company)

                if cursor.fetchone():
                    #if there is a status record for the company, update the status and contact info
                    SQL_update_command = "UPDATE [dbo].[CompanyStatus] SET [Name] = ?, [Username] = ?, [Email] = ?, [Address] = ?, [Zip] = ?, [State] = ?, [Country] = ?, [Phone] = ?, [Status] = ?, [Comment] =  ? WHERE [Company] = ?;"
                    cursor.execute(SQL_update_command, Existing_Partner_data)
                    
                else:
                    #if there is not a status record for the company, add new record
                    SQL_insert_command = "INSERT INTO [dbo].[CompanyStatus](Name, Company, Username, Email, Address, Zip, State, Country, Phone, Status, Comment) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"
                    cursor.execute(SQL_insert_command, New_Partner_data)
            
                # Commit the transaction
                connection.commit()

                # Close the connection
                cursor.close()
                connection.close()

                return "Collab with " + company + " is now " + status.lower() + "."

        #if reached here in the code, then the company contact is NOT registered in the external system, throw error   
        raise fn.UserThrownError("The company is not a registered partner.", {"company:": company})  &lt;/LI-CODE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Feel free to use this code as inspiration for your own data ops + write back scenario!&lt;/P&gt;</description>
      <pubDate>Fri, 23 May 2025 15:25:43 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Augment-data-on-the-fly/m-p/4702500#M5</guid>
      <dc:creator>SujataNarayana</dc:creator>
      <dc:date>2025-05-23T15:25:43Z</dc:date>
    </item>
    <item>
      <title>Data annotations</title>
      <link>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Data-annotations/m-p/4702494#M4</link>
      <description>&lt;P&gt;With Translytical task flows you can enable datapoint annotation directly within your report.&lt;BR /&gt;&lt;BR /&gt;&lt;/P&gt;
&lt;P&gt;For example, in the report below you can add, edit or delete annotations about each month’s sales data. Here we can see that to add a new data annotation, you select the datapoint, input your comment, and then submit, and it appears immediately on the report.&lt;BR /&gt;&lt;BR /&gt;&lt;img /&gt;&lt;BR /&gt;&lt;BR /&gt;Data annotation scenarios may consist of up to three user data functions to:&amp;nbsp;&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;Add Annotation: Add a new datapoint annotation&lt;/LI&gt;
&lt;LI&gt;Edit Annotation: Update an exisiting annotation&lt;/LI&gt;
&lt;LI&gt;Delete Annotation: Delete a specific annotation&lt;/LI&gt;
&lt;/UL&gt;
&lt;P&gt;Here is the user data function for the&amp;nbsp;&lt;STRONG&gt;Add Annotation&lt;/STRONG&gt; scenario:&amp;nbsp;&lt;/P&gt;
&lt;LI-CODE lang="python"&gt;import fabric.functions as fn
import logging
import calendar

udf = fn.UserDataFunctions()

@udf.connection(argName="sqlDB",alias="Translytical")
@udf.function()
def AddAnnotation(sqlDB: fn.FabricSqlConnection, date: str, commentdate: str, comment: str, user: str) -&amp;gt; str:
    
    logging.info('Python UDF trigger function processed a request.') 

    # month abbr to YYYY-MM-DD
    month_num = list(calendar.month_abbr).index(date)
 
    formatted_date = f"{2023}-{month_num:02d}-10"
    data = (commentdate, formatted_date, user, comment)
 
    # Establish a connection to the SQL database
    connection = sqlDB.connect()
    cursor = connection.cursor()    
 
    logging.info("Adding comment ... ")
    # Insert data into the table
    insert_query = "INSERT INTO [dbo].[DataReasoning] ([Date_Created],[Date_Month],[User],[Comment]) VALUES (?, ?, ?, ?);"
    cursor.execute(insert_query, data)
    logging.info("Comment was added")
 
    # Commit the transaction
    connection.commit()
 
    # Close the connection
    cursor.close()
    connection.close()               
    return "Comment was successfully added"&lt;/LI-CODE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Here is the user data function for the&amp;nbsp;&lt;STRONG&gt;Edit Annotation&lt;/STRONG&gt; scenario:&amp;nbsp;&lt;/P&gt;
&lt;LI-CODE lang="python"&gt;import fabric.functions as fn
import logging
import calendar

udf = fn.UserDataFunctions()

@udf.connection(argName="sqlDB",alias="Translytical")
@udf.function()
def EditAnnotation(sqlDB: fn.FabricSqlConnection, comment: str, commentdate: str, user: str, newcomment :str ) -&amp;gt; str:

    logging.info('Python UDF trigger function processed a request.') 

    data = (newcomment, commentdate, user, comment)

    # Establish a connection to the SQL database
    connection = sqlDB.connect()
    cursor = connection.cursor()

   # Insert data into the table
    logging.info("Updating comment")
    update_query = " UPDATE [dbo].[DataReasoning] SET [Comment] = ?, [Date_Created] = ?, [User] = ? WHERE [Comment] = ?;"
    cursor.execute(update_query, data)
    logging.info("Comment was updated")

    # Commit the transaction
    connection.commit()

    # Close the connection
    cursor.close()
    connection.close()               
    return "Comment was successfully updated"&lt;/LI-CODE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Here is the user data function for the&lt;STRONG&gt; Delete Annotation&lt;/STRONG&gt; scenario:&amp;nbsp;&lt;/P&gt;
&lt;LI-CODE lang="python"&gt;import fabric.functions as fn
import logging

udf = fn.UserDataFunctions()

@udf.connection(argName="sqlDB",alias="Translytical")
@udf.function()
def DeleteAnnotation(sqlDB: fn.FabricSqlConnection, comment: str ) -&amp;gt; str:
        
    logging.info('Python UDF trigger function processed a request.') 
    
    # Establish a connection to the SQL database
    connection = sqlDB.connect()
    cursor = connection.cursor()
    
    # Delete comment 
    logging.info("Deleting comment ... ")
    delete_query = "DELETE FROM [dbo].[DataReasoning] WHERE [Comment] = ?"
    cursor.execute(delete_query,comment)
    logging.info("Comment was deleted")

    # Commit the transaction
    connection.commit()

    # Close the connection
    cursor.close()
    connection.close()               
    return "Comment was successfully deleted"&lt;/LI-CODE&gt;
&lt;P&gt;&lt;SPAN&gt;&lt;BR /&gt;Feel free to use this code as inspiration for your data annotations scenarios!&lt;/SPAN&gt;&lt;/P&gt;</description>
      <pubDate>Fri, 23 May 2025 15:26:47 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Data-annotations/m-p/4702494#M4</guid>
      <dc:creator>SujataNarayana</dc:creator>
      <dc:date>2025-05-23T15:26:47Z</dc:date>
    </item>
    <item>
      <title>Modify data record(s) in a SQL table</title>
      <link>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Modify-data-record-s-in-a-SQL-table/m-p/4702442#M3</link>
      <description>&lt;P&gt;&lt;SPAN&gt;This translytical task flow can be used as a template / guide for how to &lt;STRONG&gt;modify data records within a SQL table&lt;/STRONG&gt;.&lt;/SPAN&gt;&lt;/P&gt;
&lt;P&gt;&lt;SPAN&gt;&amp;nbsp;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P&gt;&lt;SPAN&gt;For example,&lt;/SPAN&gt;&amp;nbsp;you can use translytical task flows to modify the discount value seen in the table without ever leaving the report. You simply enter in the new value in the text slicer and click the ‘Submit discount’ button, which runs a Fabric User data function that instantly updates the data source records that match the applied filters.&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;img /&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Here is the Python code for the user data function that powers this scenario:&amp;nbsp;&lt;/P&gt;
&lt;LI-CODE lang="python"&gt;import fabric.functions as fn
import logging

udf = fn.UserDataFunctions()

@udf.connection(argName="sqlDB", alias="Translytical")
@udf.function()
def UpdateDiscount(sqlDB: fn.FabricSqlConnection, quantity: int, risklevel: str, dealexpiration: int,  discount: float)-&amp;gt;str :
    
    logging.info('Python UDF trigger function processed a request.')

    sqlConnection = sqlDB.connect()
    cursor = sqlConnection.cursor()

    if (discount &amp;lt; 0):
        raise fn.UserThrownError("Discount cannot be negative")
    if (discount &amp;gt; 1):
        discount = discount / 100
    if (discount &amp;gt; 0.50):
        raise fn.UserThrownError("Discount cannot exceed 50%")

    risk = get_risk(risklevel)

    if risk == 0: 
        return f"This opportunity cannot be changed since it is either in Won or Lost state."

    days_to_close_sql = get_days_to_close_sql_string(dealexpiration)
    query = f"UPDATE [dbo].[Opportunity] SET [Discount] = ? WHERE Rating = ? {days_to_close_sql} AND Quantity = ?"
    params = (discount, risk, quantity)
    
    # Convert the query to a properly formatted T-SQL statement
    tsql_query = query.replace("?", "{}").format(*[f"'{p}'" if isinstance(p, str) else p for p in params])

    # Print the actual T-SQL statement
    logging.info(f"Executing SQL Query: {tsql_query}\n")

    cursor.execute(query, params)
    
    sqlConnection.commit()
    sqlConnection.close()
    return f"Opportunities with {risklevel} are updated."


def get_risk(risklevel:str)-&amp;gt;int:
    match risklevel:
        case "High risk":
            return 1
        case "Medium risk":
            return 2
        case "Low risk":
            return 3
        case _:
            return 0

def get_days_to_close_sql_string(dealexpiration: int)-&amp;gt;str:
    match dealexpiration:
        case 60:
            return "AND Days_To_Close &amp;lt;= 69"
        case 300:
            return "AND Days_To_Close &amp;gt;= 300"
        case _:
            return f"AND Days_To_Close &amp;gt;= {dealexpiration} AND Days_To_Close &amp;lt;= {dealexpiration + 9}"&lt;/LI-CODE&gt;
&lt;P&gt;&lt;BR /&gt;Feel free to use this code as inspiration for your writeback scenarios!&lt;/P&gt;</description>
      <pubDate>Fri, 23 May 2025 15:28:15 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Translytical-Task-Flow-Gallery/Modify-data-record-s-in-a-SQL-table/m-p/4702442#M3</guid>
      <dc:creator>SujataNarayana</dc:creator>
      <dc:date>2025-05-23T15:28:15Z</dc:date>
    </item>
  </channel>
</rss>

