<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Harish Sirikoti on Medium]]></title>
        <description><![CDATA[Stories by Harish Sirikoti on Medium]]></description>
        <link>https://medium.com/@harish.siri?source=rss-5185abd665b7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2-NGDpkUfqnuxuQB9CXzSA.png</url>
            <title>Stories by Harish Sirikoti on Medium</title>
            <link>https://medium.com/@harish.siri?source=rss-5185abd665b7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:13:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harish.siri/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Copilot Studio Agent
 inside a SharePoint SPFx Web Part]]></title>
            <link>https://medium.com/@harish.siri/copilot-studio-agent-inside-a-sharepoint-spfx-web-part-30ec2dd79408?source=rss-5185abd665b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/30ec2dd79408</guid>
            <category><![CDATA[sharepoint-spfx]]></category>
            <category><![CDATA[sharepoint-online]]></category>
            <category><![CDATA[microsoft-copilot]]></category>
            <category><![CDATA[copilot-studio]]></category>
            <dc:creator><![CDATA[Harish Sirikoti]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 07:23:48 GMT</pubDate>
            <atom:updated>2026-10-07T07:23:48.015Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. What are we building?</h3><p>We want a user to open a normal SharePoint page and chat with an existing Copilot Studio agent without leaving SharePoint. The SPFx web part is only the “chat window.” The intelligence, topics, tools, prompts, and knowledge stay inside Copilot Studio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*cVbqfPYnaQ8JM0mB4TUEWg.png" /></figure><h3>2. Before You Start: The Five Names That Are Easy to Confuse</h3><p>When configuring authentication and client integration for Microsoft Copilot Studio, it is easy to mix up these five similarly named components. Keep this quick reference handy before touching the configuration settings:</p><p><strong>EnterpriseAssist</strong></p><ul><li><strong>What it is:</strong> The Copilot Studio agent.</li><li><strong>Used for:</strong> The actual chatbot/agent that end users interact with.</li></ul><p><strong>EnterpriseAssistAuth</strong></p><ul><li><strong>What it is:</strong> Entra ID authentication app registration.</li><li><strong>Used for:</strong> Represents the protected authentication and API surface consumed by the agent.</li></ul><p><strong>EnterpriseAssistSPFxClient</strong></p><ul><li><strong>What it is:</strong> A dedicated client app registration.</li><li><strong>Used for:</strong> Custom canvas and Single Sign-On (SSO) readiness (kept strictly separate from the backend auth app).</li></ul><p><strong>copilot.studio.scope</strong></p><ul><li><strong>What it is:</strong> A custom delegated permission scope.</li><li><strong>Used for:</strong> The specific API permission exposed by EnterpriseAssistAuth.</li></ul><p><strong>Copilot Token Endpoint</strong></p><ul><li><strong>What it is:</strong> An agent-specific URL endpoint.</li><li><strong>Used for:</strong> Returning short-lived conversation tokens required by the custom web chat client.</li></ul><blockquote><strong><em>Key Takeaway:</em></strong><em> Client ID, Scope URI, Token Endpoint, Redirect URL, and Direct Line Token are all entirely different entities — never use them interchangeably.</em></blockquote><h3>3. Prerequisites</h3><p>· A Copilot Studio agent that already works in the Copilot Studio test pane.</p><p>· Permission to edit the agent security/authentication settings.</p><p>· Permission to create Microsoft Entra app registrations (or help from an Entra administrator).</p><p>· Permission to deploy an SPFx package through the SharePoint App Catalog.</p><p>· A SharePoint page where the final web part will be placed.</p><p>· The SPFx project itself. The coding steps are documented separately in README.md.</p><p><strong>Important:</strong><br> Publish the agent after authentication changes. Microsoft states that authentication changes take effect only after the agent is published.</p><h3>4. Change the Copilot Studio agent authentication</h3><p>The agent originally used “Authenticate with Microsoft.” That option is convenient for Microsoft-hosted experiences, but our custom Web Chat/SPFx scenario needed manual Entra configuration so that the agent could expose the token-exchange and custom-canvas settings we needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*-qhB2twAMo03eWfh8F3abg.png" /></figure><h3>4.1 Click path</h3><p>1. Open the Enterprise Assist agent in Copilot Studio.</p><p>2. Open Settings.</p><p>3. Open Security → Authentication.</p><p>4. Choose Authenticate manually.</p><p>5. Keep Require users to sign in enabled.</p><p>6. Choose Microsoft Entra ID V2 with federated credentials.</p><p>7. Do not guess any missing provider URL. Use the fields shown by your current Copilot Studio UI.</p><p>8. After all values are configured, Save and Publish the agent.</p><p><strong>Why federated credentials?</strong><br> They allow a secret-less trust setup. We did not place a long-lived client secret in the SPFx browser application.</p><h3>5. Entra app registration #1 — EnterpriseAssistAuth</h3><p>This is the authentication app for the Copilot Studio agent. In our setup it is the app that exposes the custom API scope. Do not reuse it as the custom client/canvas registration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*_tHLWf84uPyu-0-AWWu2Rw.png" /></figure><h3>5.1 Create the registration</h3><p>1. Open the Microsoft Entra admin center.</p><p>2. Go to App registrations → New registration.</p><p>3. Name: EnterpriseAssistAuth.</p><p>4. Choose the account type required by your organization. In our project this authentication app was Single tenant.</p><p>5. Leave Redirect URI empty for the initial registration.</p><p>6. Create the app.</p><p>7. From Overview, keep the Application (client) ID and Directory (tenant) ID available. Do not publish real IDs in a public blog.</p><h3>5.2 Add the Bot Framework OAuth redirect URL</h3><p>Open EnterpriseAssistAuth → Authentication → Add a platform → Web, then add the Bot Framework callback URL used by this authentication pattern:</p><p><a href="https://token.botframework.com/.auth/web/redirect">https://token.botframework.com/.auth/web/redirect</a></p><p>Enable Access tokens and ID tokens only where the current Microsoft guidance/current portal experience calls for them. Save the platform configuration.</p><p><strong>Do not mix this up:</strong><br> <a href="https://token.botframework.com/.auth/web/redirect">https://token.botframework.com/.auth/web/redirect</a> is an OAuth callback. It is NOT the Copilot Studio Token Endpoint used by the SPFx chat client.</p><h3>5.3 Expose the custom API scope</h3><p>1. Open EnterpriseAssistAuth → Expose an API.</p><p>2. Set or accept an Application ID URI in the form api://&lt;AUTH_APP_CLIENT_ID&gt;.</p><p>3. Select Add a scope.</p><p>4. Use the scope name copilot.studio.scope.</p><p>5. Allow Admins and users to consent, subject to your tenant policy.</p><p>6. Use a clear consent display name/description and enable the scope.</p><p>Full scope URI:<br> api://&lt;AUTH_APP_CLIENT_ID&gt;/copilot.studio.scope</p><p>This full scope URI is the value we later used as the Copilot Studio Token exchange URL.</p><h3>5.4 OpenID permissions</h3><p>Microsoft’s current authentication guidance also calls for the OpenID delegated permissions needed for sign-in, such as openid and profile. Verify them under API permissions / Microsoft Graph in your tenant. Do not add unrelated Graph permissions unless your agent actually needs them.</p><h3>6. Entra app registration #2 — EnterpriseAssistSPFxClient</h3><p>We created a second registration because Microsoft’s custom-canvas/SSO guidance separates the authentication app from the client/canvas app. Keeping the two roles separate also makes the architecture easier to understand.</p><p><strong>Current project status:</strong><br> This second app was prepared for the custom-canvas/SSO path. The final deployed version described in this guide still uses Copilot Studio manual OAuth plus conversation continuity; it does not currently acquire the runtime token through this client registration.</p><h3>6.1 Create the client registration</h3><p>1. Create another App registration.</p><p>2. Name it EnterpriseAssistSPFxClient.</p><p>3. Choose the account type that matches your tenant policy. In our setup, the broader Entra + personal-account option was selected.</p><p>4. Leave Redirect URI empty during initial creation.</p><p>5. Create the registration and copy only the Application (client) ID GUID.</p><h3>6.2 Confirm access-token version</h3><p>In the newer app-registration manifest UI, access-token version is represented by requestedAccessTokenVersion. Our registration already showed version 2, so no change was needed.</p><p>“api”: {<br> “requestedAccessTokenVersion”: 2<br> }</p><h3>6.3 Authorize the client against the auth scope</h3><p>1. Copy the EnterpriseAssistSPFxClient Application (client) ID.</p><p>2. Open EnterpriseAssistAuth → Expose an API.</p><p>3. Under Authorized client applications, choose Add a client application.</p><p>4. Paste the EnterpriseAssistSPFxClient client ID.</p><p>5. Select copilot.studio.scope.</p><p>6. Save.</p><p><strong>Memory rule:</strong><br> Client ID = the GUID of an app registration. Scope URI = api://…/copilot.studio.scope. They are not interchangeable.</p><h3>6.4 Add the SharePoint page redirect URI</h3><p>Open EnterpriseAssistSPFxClient → Authentication → Add a platform. For the custom-canvas setup, use the platform type required by the current Microsoft SSO guidance (currently shown as SPA for the web app example) and add the exact SharePoint page URL that will host the chatbot.</p><p>https://&lt;tenant&gt;.sharepoint.com/sites/&lt;site&gt;/SitePages/&lt;chat-page&gt;.aspx</p><p>If your current Microsoft documentation or portal uses slightly different labels, follow the current UI; do not invent a platform option.</p><h3>7. Put the Entra Values into Copilot Studio</h3><p>Return to <strong>EnterpriseAssist</strong> → <strong>Settings</strong> → <strong>Security</strong> → <strong>Authentication</strong>, then map your configuration using the values below:</p><p><strong>Authentication option</strong></p><ul><li><strong>Value:</strong> Authenticate manually</li></ul><p><strong>Service provider</strong></p><ul><li><strong>Value:</strong> Microsoft Entra ID V2 with federated credentials</li></ul><p><strong>Client ID</strong></p><ul><li><strong>Value:</strong> Application (client) ID from EnterpriseAssistAuth</li></ul><p><strong>Token exchange URL</strong></p><ul><li><strong>Value:</strong> api://&lt;ENTERPRISE_ASSIST_AUTH_CLIENT_ID&gt;/copilot.studio.scope</li></ul><p><strong>Scopes</strong></p><ul><li><strong>Value:</strong> profile openid</li></ul><p><strong>Require users to sign in</strong></p><ul><li><strong>Value:</strong> Enabled</li></ul><blockquote><strong><em>Important:</em></strong><em> After updating the authentication configuration, make sure to </em><strong><em>Save</em></strong><em> and </em><strong><em>Publish</em></strong><em> the agent. Saving alone will not push these changes to your end users.</em></blockquote><h3>8. Create the federated credential</h3><p>After the manual authentication settings are saved, Copilot Studio provides the federation values needed by the Entra authentication app. These are trust-configuration values, not a client secret.</p><p>1. Copy the Federated credential issuer shown by Copilot Studio.</p><p>2. Copy the Federated credential value/subject shown by Copilot Studio.</p><p>3. Open EnterpriseAssistAuth in the Entra admin center.</p><p>4. Open Certificates &amp; secrets → Federated credentials.</p><p>5. Add a credential using the “Other issuer” scenario (or the equivalent current UI).</p><p>6. Paste the issuer exactly.</p><p>7. Paste the subject/value exactly.</p><p>8. Give it a clear name, for example EnterpriseAssistCopilotFederation.</p><p>9. Save.</p><p><strong>Do not “simplify” these values:</strong><br> Issuer and subject must match exactly. A typo can make authentication fail even when all client IDs look correct.</p><h3>9. Find the Copilot Studio Token Endpoint</h3><p>The SPFx chat client needs an agent-specific Token Endpoint. This endpoint is used to obtain a short-lived conversation token for Bot Framework Web Chat / Direct Line.</p><h3>9.1 Where we found it</h3><p>1. Open the Enterprise Assist agent.</p><p>2. Open Channels.</p><p>3. Open Email.</p><p>4. Find Token Endpoint.</p><p>5. Copy the full URL and keep it as environment configuration for the SPFx project.</p><p><strong>Current Microsoft UI note:</strong><br> Microsoft’s custom-canvas documentation currently documents Email as a place to retrieve the Token Endpoint. Some SSO documentation may show Mobile app. Use the actual Token Endpoint exposed by your current tenant UI; in our tenant it was Email.</p><p>Never substitute the Bot Framework OAuth callback URL for the agent Token Endpoint.</p><h3>10. What values does the SPFx web part need?</h3><p>The browser-side web part needs configuration values, but it must not contain long-lived secrets. In our project the configuration template contains:</p><p>COPILOT_TOKEN_ENDPOINT=<br> ENTRA_TENANT_ID=<br> SPFX_CLIENT_ID=<br> COPILOT_SCOPE=<br> SHAREPOINT_CHAT_PAGE_URL=</p><p>These values are configuration, not passwords. They are kept out of hardcoded TypeScript so that the repository can be reused in other environments.</p><h3>10.1 What is safe to treat as configuration</h3><p>· Tenant ID</p><p>· Application/client ID</p><p>· Custom scope URI</p><p>· Copilot Studio Token Endpoint</p><p>· SharePoint page URL</p><h3>10.2 What must NEVER be shipped in the browser bundle</h3><p>· Client secret</p><p>· Direct Line secret</p><p>· Password</p><p>· Private key</p><p>· Long-lived access token</p><p>· Any credential copied from a secure backend</p><p><strong>Most important security rule:</strong><br> Putting a secret in .env does NOT make it safe in an SPFx browser application. Build-time values can end up inside the JavaScript bundle. Use short-lived runtime tokens instead.</p><h3>11. SharePoint API permission request we configured</h3><p>During the project we also configured an SPFx API permission request for EnterpriseAssistAuth / copilot.studio.scope. This was part of the authentication/SSO groundwork. The permission was surfaced in the SharePoint Admin Center and approved by an administrator.</p><p>“webApiPermissionRequests”: [{<br> “resource”: “EnterpriseAssistAuth”,<br> “scope”: “copilot.studio.scope”<br> }]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*FFpnJxMxmmSPvNCVdnVW8Q.png" /></figure><p>For the final manual-auth runtime, this approval is not a substitute for the user Login card. It is useful groundwork for protected API/SSO scenarios and should not be described as “SSO completed.”</p><h3>12. What happens when a user chats?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*FctRT8QDFGTn98HwNs3kWw.png" /></figure><p>The web part uses the Copilot Studio Token Endpoint to obtain a short-lived Direct Line conversation token. The client then connects to the regional Direct Line endpoint and renders Bot Framework Web Chat.</p><p>When the agent needs protected user data, Copilot Studio can show the Login card. The user signs in and enters the one-time validation code into the chat. After authentication, the agent can continue with authenticated actions such as reading or creating tickets.</p><p><strong>Our final implementation also added conversation continuity in sessionStorage. When the same browser session and Direct Line token are still valid, the web part can reconnect to the same conversation and reduce repeated login prompts. This is NOT SharePoint SSO, and expired/invalid sessions can still require Login again.</strong></p><h3>13. End-to-end test checklist</h3><p>· ☐ Publish the Copilot Studio agent after authentication changes.</p><p>· ☐ Confirm EnterpriseAssistAuth exists and exposes copilot.studio.scope.</p><p>· ☐ Confirm the federated credential exists in EnterpriseAssistAuth.</p><p>· ☐ Confirm EnterpriseAssistSPFxClient exists and is authorized for the custom scope (custom-canvas/SSO readiness).</p><p>· ☐ Confirm the SharePoint page redirect URI is registered where required.</p><p>· ☐ Copy the real agent Token Endpoint from Copilot Studio.</p><p>· ☐ Build/deploy the SPFx package.</p><p>· ☐ Open the real SharePoint page (not only the workbench).</p><p>· ☐ Send a normal message and confirm the agent responds.</p><p>· ☐ Trigger an action that needs authentication.</p><p>· ☐ Complete Login/validation-code flow if prompted.</p><p>· ☐ Confirm the authenticated action succeeds.</p><p>· ☐ Refresh the page and confirm conversation continuity behaves as expected for the same valid browser session.</p><h3>SPFx Web Part Implementation</h3><p>At this point, the Copilot Studio and Entra configuration is complete.<br>The remaining work is the SPFx React implementation that connects Bot Framework Web Chat to the Copilot Studio agent using the configured Token Endpoint and Direct Line.</p><p>The complete reusable SPFx source code, project structure, environment template, setup commands, and deployment instructions are available in the GitHub repository below.</p><p><strong>Source code:</strong> <a href="https://github.com/harishsirikoti/spfx_copilot">https://github.com/harishsirikoti/spfx_copilot</a></p><p>Please read the repository README.md before running the project. Copy .env.example to .env and provide your own environment-specific values. Do not commit secrets.</p><p>## Let’s Connect</p><p>I’m always interested in discussing SharePoint Framework, Power Platform, Copilot Studio, React, and Microsoft 365 development.</p><p>You can reach me here:</p><p>- LinkedIn: <a href="https://www.linkedin.com/in/sirikotiharish">https://www.linkedin.com/in/sirikotiharish</a><br>- Email: harish.siri@outlook.com<br>- GitHub: <a href="https://github.com/harishsirikoti">https://github.com/harishsirikoti</a></p><p>Feel free to connect if you have questions about this implementation or if you are building something similar.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30ec2dd79408" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Reusable Table System: Sorting, Search & Filters in React]]></title>
            <link>https://medium.com/@harish.siri/creating-a-reusable-table-system-sorting-search-filters-in-react-0bff6cda26e1?source=rss-5185abd665b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bff6cda26e1</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[ui-ux-design]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[reusable-component]]></category>
            <dc:creator><![CDATA[Harish Sirikoti]]></dc:creator>
            <pubDate>Fri, 04 Jul 2025 13:16:47 GMT</pubDate>
            <atom:updated>2025-07-16T15:52:22.318Z</atom:updated>
            <content:encoded><![CDATA[<p>Tired of rebuilding table components for every project? Frustrated with libraries that don’t quite fit your<br> needs? I was too. That’s why I built a comprehensive, production-ready table system in Next.js 15 that you can<br> literally copy-paste into any project.</p><p>This isn’t just another basic table component. It’s a complete system featuring column-level sorting, global<br> search, dropdown filtering, nested property support, dark/light mode compatibility, and flexible component<br> placement — all in a single TypeScript file.</p><p>The best part? The search and filter components can be placed anywhere in your app (navbar, sidebar, separate<br> page) and automatically sync with your tables. No complex state management, no external dependencies, just pure<br> React magic.</p><p>Component Code</p><pre>&#39;use client&#39;;<br><br>import { useState, createContext, useContext, useEffect, useCallback, useMemo } from &#39;react&#39;;<br>import { ChevronUp, ChevronDown, Search, ChevronDown as DropdownIcon } from &#39;lucide-react&#39;;<br><br>/**<br>* Global storage for table data across components<br>* Allows multiple components to share the same table state (search, filters, data)<br>*/<br>interface TableDataStore {<br>  originalData: any[];<br>  filteredData: any[];<br>  searchTerm: string;<br>  searchColumns: string[];<br>  dropdownFilters: Record&lt;string, string&gt;;<br>  subscribers: Set&lt;() =&gt; void&gt;;<br>}<br><br>const globalTableDataStore = new Map&lt;string, TableDataStore&gt;();<br><br>/** Sort direction for table columns */<br>export type SortDirection = &#39;asc&#39; | &#39;desc&#39; | null;<br><br>/** Configuration for sorting */<br>export interface SortConfig {<br>  column: string;<br>  direction: SortDirection;<br>}<br><br>/** Table context value for sharing state between components */<br>export interface TableContextValue {<br>  sortConfig: SortConfig;<br>  onSort: (column: string) =&gt; void;<br>  sortedData: any[];<br>}<br><br>/** Props for table header component */<br>export interface ThProps {<br>  column_name?: string; // If provided, enables sorting<br>  children: React.ReactNode;<br>  className?: string;<br>}<br><br>/** Props for main table component */<br>export interface TableProps {<br>  children: React.ReactNode;<br>  className?: string;<br>  data?: any[]; // Array of data objects<br>  defaultSort?: SortConfig;<br>  dataId?: string; // Required for search/filter functionality<br>}<br><br>/** Props for search input component */<br>export interface TableSearchProps {<br>  dataId: string; // Must match Table&#39;s dataId<br>  columns: string[]; // Columns to search in (supports dot notation for nested)<br>  placeholder?: string;<br>  className?: string;<br>}<br><br>/** Props for dropdown filter component */<br>export interface TableDropdownProps {<br>  dataId: string; // Must match Table&#39;s dataId<br>  column_name: string; // Column to filter on (supports dot notation)<br>  filter_values: string[]; // Available filter options<br>  placeholder?: string;<br>  className?: string;<br>}<br><br>const getNestedValue = (obj: any, path: string): any =&gt; {<br>  return path.split(&#39;.&#39;).reduce((current, key) =&gt; current?.[key], obj);<br>};<br><br>const applyAllFilters = (store: TableDataStore): void =&gt; {<br>  let filtered = [...store.originalData];<br><br>  // Apply search filter<br>  if (store.searchTerm.trim()) {<br>    filtered = filtered.filter((item) =&gt; {<br>      return store.searchColumns.some((column: string) =&gt; {<br>        const value = getNestedValue(item, column);<br>        return String(value).toLowerCase().includes(store.searchTerm.toLowerCase());<br>      });<br>    });<br>  }<br><br>  // Apply dropdown filters<br>  Object.entries(store.dropdownFilters).forEach(([column, filterValue]) =&gt; {<br>    if (filterValue &amp;&amp; filterValue !== &#39;&#39;) {<br>      filtered = filtered.filter((item) =&gt; {<br>        const value = getNestedValue(item, column);<br>        return String(value) === String(filterValue);<br>      });<br>    }<br>  });<br><br>  store.filteredData = filtered;<br>  // Notify all subscribers of data change<br>  store.subscribers.forEach((callback) =&gt; callback());<br>};<br><br>export function useTableData(dataId: string, initialData: any[] = []): any[] {<br>  const [, forceUpdate] = useState({});<br>  // Memoize the update function to prevent unnecessary re-renders<br>  const updateFn = useCallback(() =&gt; forceUpdate({}), []);<br><br>  // Initialize or update store BEFORE returning data<br>  if (!globalTableDataStore.has(dataId)) {<br>    // Initialize new table data store<br>    globalTableDataStore.set(dataId, {<br>      originalData: initialData,<br>      filteredData: initialData,<br>      searchTerm: &#39;&#39;,<br>      searchColumns: [],<br>      dropdownFilters: {},<br>      subscribers: new Set()<br>    });<br>  } else {<br>    // Update existing store with new data<br>    const store = globalTableDataStore.get(dataId)!;<br>    <br>    // Check if data has actually changed<br>    const hasDataChanged = JSON.stringify(store.originalData) !== JSON.stringify(initialData);<br>    <br>    if (hasDataChanged) {<br>      store.originalData = initialData;<br><br>      // Only reset filtered data if no active filters<br>      if (!store.searchTerm &amp;&amp; Object.keys(store.dropdownFilters).length === 0) {<br>        store.filteredData = initialData;<br>      } else {<br>        // Re-apply existing filters to new data<br>        applyAllFilters(store);<br>      }<br>    }<br>  }<br><br>  useEffect(() =&gt; {<br>    const store = globalTableDataStore.get(dataId)!;<br>    store.subscribers.add(updateFn);<br><br>    // Cleanup subscription on unmount<br>    return () =&gt; {<br>      store.subscribers.delete(updateFn);<br>    };<br>  }, [dataId, updateFn]);<br><br>  const store = globalTableDataStore.get(dataId);<br>  return store ? store.filteredData : initialData;<br>}<br><br>export function updateTableFilter(dataId: string, searchTerm: string, columns: string[]): void {<br>  const store = globalTableDataStore.get(dataId);<br>  if (!store) return;<br><br>  store.searchTerm = searchTerm;<br>  store.searchColumns = columns;<br>  applyAllFilters(store);<br>}<br><br>export function updateTableDropdownFilter(dataId: string, column: string, value: string): void {<br>  const store = globalTableDataStore.get(dataId);<br>  if (!store) return;<br><br>  if (value === &#39;&#39; || value === null || value === undefined) {<br>    delete store.dropdownFilters[column];<br>  } else {<br>    store.dropdownFilters[column] = value;<br>  }<br><br>  applyAllFilters(store);<br>}<br><br>const TableContext = createContext&lt;TableContextValue | null&gt;(null);<br><br>const useTableContext = (): TableContextValue =&gt; {<br>  const context = useContext(TableContext);<br>  if (!context) {<br>    throw new Error(&#39;Table components must be used within a Table component&#39;);<br>  }<br>  return context;<br>};<br><br>export default function Table({<br>  children,<br>  className = &#39;&#39;,<br>  data = [],<br>  defaultSort,<br>  dataId<br>}: TableProps) {<br>  // Sorting state<br>  const [sortConfig, setSortConfig] = useState&lt;SortConfig&gt;(<br>    defaultSort || { column: &#39;&#39;, direction: null }<br>  );<br><br>  // Get filtered data from global store or use provided data<br>  const filteredData = dataId ? useTableData(dataId, data) : data;<br>  const [sortedData, setSortedData] = useState(filteredData);<br><br><br>  const handleSort = useCallback((column: string) =&gt; {<br>    const newDirection: SortDirection =<br>      sortConfig.column === column &amp;&amp; sortConfig.direction === &#39;asc&#39;<br>        ? &#39;desc&#39;<br>        : sortConfig.column === column &amp;&amp; sortConfig.direction === &#39;desc&#39;<br>          ? null<br>          : &#39;asc&#39;;<br><br>    const newSortConfig: SortConfig = { column, direction: newDirection };<br>    setSortConfig(newSortConfig);<br><br>    if (newDirection === null) {<br>      // No sorting - return original order<br>      setSortedData([...filteredData]);<br>    } else {<br>      // Sort data based on column values<br>      const sorted = [...filteredData].sort((a, b) =&gt; {<br>        const aValue = getNestedValue(a, column);<br>        const bValue = getNestedValue(b, column);<br><br>        // Handle null/undefined values<br>        if (aValue == null &amp;&amp; bValue == null) return 0;<br>        if (aValue == null) return 1;<br>        if (bValue == null) return -1;<br><br>        // Convert to strings for comparison<br>        const aStr = String(aValue).toLowerCase();<br>        const bStr = String(bValue).toLowerCase();<br><br>        // Check if both values are purely numeric<br>        const aIsNumeric = !isNaN(Number(aValue)) &amp;&amp; !isNaN(parseFloat(aValue)) &amp;&amp; isFinite(Number(aValue));<br>        const bIsNumeric = !isNaN(Number(bValue)) &amp;&amp; !isNaN(parseFloat(bValue)) &amp;&amp; isFinite(Number(bValue));<br><br>        if (aIsNumeric &amp;&amp; bIsNumeric) {<br>          // Numeric comparison<br>          const aNum = Number(aValue);<br>          const bNum = Number(bValue);<br>          return newDirection === &#39;asc&#39; ? aNum - bNum : bNum - aNum;<br>        } else {<br>          // Natural string comparison (handles embedded numbers)<br>          const comparison = aStr.localeCompare(bStr, undefined, {<br>            numeric: true,<br>            sensitivity: &#39;base&#39;<br>          });<br>          return newDirection === &#39;asc&#39; ? comparison : -comparison;<br>        }<br>      });<br>      setSortedData(sorted);<br>    }<br>  }, [sortConfig, filteredData]);<br><br>  // Memoize context value to prevent unnecessary re-renders<br>  const contextValue = useMemo(() =&gt; ({<br>    sortConfig,<br>    onSort: handleSort,<br>    sortedData<br>  }), [sortConfig, handleSort, sortedData, data]);<br><br>  // Update sorted data when filtered data changes<br>  useEffect(() =&gt; {<br>    setSortedData(filteredData);<br><br>  }, [filteredData, data]);<br>  // console.log(dataId,&quot;contextValueyyyyyyyy&quot;, contextValue);<br>  return (<br>    &lt;TableContext.Provider value={contextValue}&gt;<br>      &lt;div className=&quot;overflow-x-auto&quot;&gt;<br>        &lt;table className={`min-w-full border-collapse bg-white dark:bg-gray-800 shadow-sm rounded-lg border border-gray-200 dark:border-gray-700 ${className}`}&gt;<br>          {children}<br>        &lt;/table&gt;<br>      &lt;/div&gt;<br>    &lt;/TableContext.Provider&gt;<br>  );<br>}<br><br>export function Th({ column_name, children, className = &#39;&#39; }: ThProps) {<br>  const { sortConfig, onSort } = useTableContext();<br><br>  const handleClick = useCallback(() =&gt; {<br>    if (column_name) {<br>      onSort(column_name);<br>    }<br>  }, [column_name, onSort]);<br><br>  /**<br>   * Get sort icon based on current sort state<br>   */<br>  const sortIcon = useMemo(() =&gt; {<br>    if (!column_name) return null;<br><br>    const isActiveColumn = sortConfig.column === column_name;<br><br>    if (isActiveColumn) {<br>      if (sortConfig.direction === &#39;asc&#39;) {<br>        return &lt;ChevronUp className=&quot;w-4 h-4 text-blue-600 dark:text-blue-400&quot; /&gt;;<br>      } else if (sortConfig.direction === &#39;desc&#39;) {<br>        return &lt;ChevronDown className=&quot;w-4 h-4 text-blue-600 dark:text-blue-400&quot; /&gt;;<br>      }<br>    }<br><br>    return &lt;ChevronDown className=&quot;w-4 h-4 opacity-30 dark:opacity-40&quot; /&gt;;<br>  }, [column_name, sortConfig]);<br><br>  const isActiveSorting = useMemo(() =&gt;<br>    sortConfig.column === column_name &amp;&amp; sortConfig.direction !== null,<br>    [sortConfig.column, sortConfig.direction, column_name]<br>  );<br><br>  return (<br>    &lt;th<br>      className={`px-6 py-3 text-left text-xs uppercase tracking-wider border-b transition-all duration-200 ${isActiveSorting<br>        ? &#39;bg-blue-50 dark:bg-blue-900/20 text-blue-800 dark:text-blue-200 font-bold border-blue-200 dark:border-blue-700&#39;<br>        : &#39;bg-gray-50 dark:bg-gray-700 text-gray-500 dark:text-gray-400 font-medium border-gray-200 dark:border-gray-600&#39;<br>        } ${column_name ? &#39;cursor-pointer hover:bg-blue-50 dark:hover:bg-blue-900/20 hover:text-blue-600 dark:hover:text-blue-300 select-none&#39; : &#39;&#39;<br>        } ${className}`}<br>      onClick={handleClick}<br>    &gt;<br>      &lt;div className=&quot;flex items-center justify-between&quot;&gt;<br>        &lt;span className={isActiveSorting ? &#39;font-bold&#39; : &#39;&#39;}&gt;{children}&lt;/span&gt;<br>        {sortIcon}<br>      &lt;/div&gt;<br>    &lt;/th&gt;<br>  );<br>}<br><br>export function Td({ children, className = &#39;&#39; }: { children: React.ReactNode; className?: string }) {<br>  return (<br>    &lt;td className={`px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100 border-b border-gray-200 dark:border-gray-600 ${className}`}&gt;<br>      {children}<br>    &lt;/td&gt;<br>  );<br>}<br><br>export function Tbody({ children, renderRow }: {<br>  children?: React.ReactNode;<br>  renderRow?: (item: any, index: number) =&gt; React.ReactNode<br>}) {<br>  const { sortedData } = useTableContext();<br>  // console.log(&quot;sortedDatayyyyyyyyy&quot;,sortedData);<br><br>  if (renderRow) {<br>    return (<br>      &lt;tbody&gt;<br>        {sortedData.map((item, index) =&gt; renderRow(item, index))}<br>      &lt;/tbody&gt;<br>    );<br>  }<br><br>  return &lt;tbody&gt;{children}&lt;/tbody&gt;;<br>}<br><br>export function Tr({ children, className = &#39;&#39; }: { children: React.ReactNode; className?: string }) {<br>  return (<br>    &lt;tr className={`hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors ${className}`}&gt;<br>      {children}<br>    &lt;/tr&gt;<br>  );<br>}<br><br>export function TableSearch({ dataId, columns, placeholder = &#39;Search...&#39;, className = &#39;&#39; }: TableSearchProps) {<br>  const [searchValue, setSearchValue] = useState(&#39;&#39;);<br><br>  const handleSearchChange = useCallback((e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    const value = e.target.value;<br>    setSearchValue(value);<br>    updateTableFilter(dataId, value, columns);<br>  }, [dataId, columns]);<br><br>  return (<br>    &lt;div className={`relative ${className}`}&gt;<br>      &lt;div className=&quot;absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none&quot;&gt;<br>        &lt;Search className=&quot;h-5 w-5 text-gray-400 dark:text-gray-500&quot; /&gt;<br>      &lt;/div&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        value={searchValue}<br>        onChange={handleSearchChange}<br>        placeholder={placeholder}<br>        className=&quot;block w-full pl-10 pr-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md leading-5 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400 focus:outline-none focus:placeholder-gray-400 dark:focus:placeholder-gray-500 focus:ring-1 focus:ring-blue-500 dark:focus:ring-blue-400 focus:border-blue-500 dark:focus:border-blue-400 sm:text-sm transition-colors&quot;<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export function TableDropdown({ dataId, column_name, filter_values, placeholder = &#39;Filter...&#39;, className = &#39;&#39; }: TableDropdownProps) {<br>  const [selectedValue, setSelectedValue] = useState(&#39;&#39;);<br>  const [isOpen, setIsOpen] = useState(false);<br><br>  // Close dropdown when clicking outside<br>  useEffect(() =&gt; {<br>    const handleClickOutside = (event: MouseEvent) =&gt; {<br>      const target = event.target as Element;<br>      if (!target.closest(`[data-dropdown=&quot;${dataId}-${column_name}&quot;]`)) {<br>        setIsOpen(false);<br>      }<br>    };<br><br>    if (isOpen) {<br>      document.addEventListener(&#39;mousedown&#39;, handleClickOutside);<br>      return () =&gt; document.removeEventListener(&#39;mousedown&#39;, handleClickOutside);<br>    }<br>  }, [isOpen, dataId, column_name]);<br><br>  const handleSelectChange = useCallback((value: string) =&gt; {<br>    setSelectedValue(value);<br>    setIsOpen(false);<br>    updateTableDropdownFilter(dataId, column_name, value);<br>  }, [dataId, column_name]);<br><br>  const handleClear = useCallback(() =&gt; {<br>    setSelectedValue(&#39;&#39;);<br>    updateTableDropdownFilter(dataId, column_name, &#39;&#39;);<br>  }, [dataId, column_name]);<br><br>  const toggleDropdown = useCallback(() =&gt; {<br>    setIsOpen(prev =&gt; !prev);<br>  }, []);<br><br>  return (<br>    &lt;div className={`relative ${className}`} data-dropdown={`${dataId}-${column_name}`}&gt;<br>      &lt;button<br>        type=&quot;button&quot;<br>        onClick={toggleDropdown}<br>        className=&quot;relative w-full cursor-default rounded-md bg-white dark:bg-gray-800 py-2 pl-3 pr-10 text-left shadow-sm border border-gray-300 dark:border-gray-600 focus:border-blue-500 dark:focus:border-blue-400 focus:outline-none focus:ring-1 focus:ring-blue-500 dark:focus:ring-blue-400 sm:text-sm transition-colors&quot;<br>        aria-haspopup=&quot;listbox&quot;<br>        aria-expanded={isOpen}<br>        aria-label={`Filter by ${column_name}`}<br>      &gt;<br>        &lt;span className={`block truncate ${selectedValue ? &#39;text-gray-900 dark:text-gray-100&#39; : &#39;text-gray-500 dark:text-gray-400&#39;}`}&gt;<br>          {selectedValue || placeholder}<br>        &lt;/span&gt;<br>        &lt;span className=&quot;pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2&quot;&gt;<br>          &lt;DropdownIcon className=&quot;h-5 w-5 text-gray-400 dark:text-gray-500&quot; aria-hidden=&quot;true&quot; /&gt;<br>        &lt;/span&gt;<br>      &lt;/button&gt;<br><br>      {isOpen &amp;&amp; (<br>        &lt;div className=&quot;absolute z-10 mt-1 max-h-56 w-full overflow-auto rounded-md bg-white dark:bg-gray-800 py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm border border-gray-200 dark:border-gray-600&quot;&gt;<br>          {selectedValue &amp;&amp; (<br>            &lt;div<br>              onClick={handleClear}<br>              className=&quot;relative cursor-pointer select-none py-2 pl-3 pr-9 text-gray-700 dark:text-gray-300 hover:bg-blue-50 dark:hover:bg-blue-900/20 border-b border-gray-200 dark:border-gray-600&quot;<br>            &gt;<br>              &lt;span className=&quot;block truncate italic&quot;&gt;Clear filter&lt;/span&gt;<br>            &lt;/div&gt;<br>          )}<br>          {filter_values.map((value, index) =&gt; (<br>            &lt;div<br>              key={index}<br>              onClick={() =&gt; handleSelectChange(value)}<br>              className={`relative cursor-pointer select-none py-2 pl-3 pr-9 ${selectedValue === value<br>                ? &#39;bg-blue-100 dark:bg-blue-900/30 text-blue-900 dark:text-blue-100&#39;<br>                : &#39;text-gray-900 dark:text-gray-100 hover:bg-gray-100 dark:hover:bg-gray-700&#39;<br>                }`}<br>            &gt;<br>              &lt;span className=&quot;block truncate&quot;&gt;{value}&lt;/span&gt;<br>              {selectedValue === value &amp;&amp; (<br>                &lt;span className=&quot;absolute inset-y-0 right-0 flex items-center pr-4 text-blue-600 dark:text-blue-400&quot;&gt;<br>                  ✓<br>                &lt;/span&gt;<br>              )}<br>            &lt;/div&gt;<br>          ))}<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Use age example</p><pre>&#39;use client&#39;<br>import React from &#39;react&#39;<br>import Table, { Th, Td, Tr, Tbody, TableSearch, TableDropdown } from &#39;@/components/Table&#39;<br><br>type CustomerData = {<br>    id: number;<br>    email: string;<br>    account_no: string;<br>    first_name: string;<br>    last_name: string;<br>    status: string;<br>    address: {<br>        postal: string;<br>        city: string;<br>        street: string;<br>    };<br>};<br><br>const Displaydate = ({ customers }: { customers: CustomerData[] }) =&gt; {<br>    return (<br>        &lt;div className=&quot;container mx-auto p-8&quot;&gt;<br>            &lt;h1 className=&quot;text-3xl font-bold mb-8&quot;&gt;Customer Data&lt;/h1&gt;<br><br>            {/* Search and Filter Controls */}<br>            &lt;div className=&quot;mb-6 flex flex-wrap gap-4&quot;&gt;<br>                &lt;TableSearch<br>                    dataId=&quot;customers&quot;<br>                    columns={[&#39;account_no&#39;, &#39;first_name&#39;, &#39;last_name&#39;, &#39;email&#39;, &#39;address.city&#39;, &#39;status&#39;, &#39;address.postal&#39;]}<br>                    placeholder=&quot;Search customers...&quot;<br>                    className=&quot;max-w-md&quot;<br>                /&gt;<br>                &lt;TableDropdown<br>                    dataId=&quot;customers&quot;<br>                    column_name=&quot;status&quot;<br>                    filter_values={[&#39;customer&#39;, &#39;active&#39;, &#39;inactive&#39;]}<br>                    placeholder=&quot;Filter by Status&quot;<br>                    className=&quot;w-48&quot;<br>                /&gt;<br>                &lt;TableDropdown<br>                    dataId=&quot;customers&quot;<br>                    column_name=&quot;address.city&quot;<br>                    filter_values={[&#39;Toronto&#39;, &#39;Ottawa&#39;, &#39;Vancouver&#39;]}<br>                    placeholder=&quot;Filter by City&quot;<br>                    className=&quot;w-48&quot;<br>                /&gt;<br>            &lt;/div&gt;<br><br>            &lt;Table data={customers} dataId=&quot;customers&quot; className=&quot;border border-gray-300&quot;&gt;<br>                &lt;thead&gt;<br>                    &lt;Tr&gt;<br>                        &lt;Th column_name=&quot;account_no&quot;&gt;Account No&lt;/Th&gt;<br>                        &lt;Th column_name=&quot;first_name&quot;&gt;Name&lt;/Th&gt;<br>                        &lt;Th column_name=&quot;email&quot;&gt;Email&lt;/Th&gt;<br>                        &lt;Th column_name=&quot;status&quot;&gt;Status&lt;/Th&gt;<br>                        &lt;Th column_name=&quot;address.postal&quot;&gt;Address&lt;/Th&gt;<br>                    &lt;/Tr&gt;<br>                &lt;/thead&gt;<br>                &lt;Tbody renderRow={(customer, index) =&gt; (<br>                    &lt;Tr key={customer.id}&gt;<br>                        &lt;Td&gt;{customer.account_no}&lt;/Td&gt;<br>                        &lt;Td&gt;{customer.first_name} {customer.last_name}&lt;/Td&gt;<br>                        &lt;Td&gt;{customer.email}&lt;/Td&gt;<br>                        &lt;Td&gt;<br>                            &lt;span className={`px-2 py-1 text-xs rounded-full ${customer.status === &#39;customer&#39;<br>                                    ? &#39;bg-green-100 text-green-800&#39;<br>                                    : &#39;bg-gray-100 text-gray-800&#39;<br>                                }`}&gt;<br>                                {customer.status}<br>                            &lt;/span&gt;<br>                        &lt;/Td&gt;<br>                        &lt;Td&gt;<br>                            &lt;div className=&quot;text-sm&quot;&gt;<br>                                &lt;div&gt;#{customer.address.postal}&lt;/div&gt;<br>                                &lt;div className=&quot;text-gray-500&quot;&gt;${customer.address.city}&lt;/div&gt;<br>                            &lt;/div&gt;<br>                        &lt;/Td&gt;<br>                    &lt;/Tr&gt;<br>                )} /&gt;<br>            &lt;/Table&gt;<br>        &lt;/div&gt;<br>    )<br>}<br><br>export default Displaydate</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1obeQREuwXCX7s6QO-RfA.png" /></figure><p>If you found this helpful and would like more solutions or guidance on building reusable components in React or improving your frontend architecture, feel free to reach out to me at <strong>harish.siri@outlook.com</strong>. I’m always happy to help or collaborate on exciting projects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bff6cda26e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pdf Generator in NextJS]]></title>
            <link>https://medium.com/@harish.siri/pdf-generator-in-nextjs-fcaea81404a4?source=rss-5185abd665b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcaea81404a4</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[pdf-download]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Harish Sirikoti]]></dc:creator>
            <pubDate>Fri, 25 Apr 2025 11:24:36 GMT</pubDate>
            <atom:updated>2025-04-25T11:24:36.014Z</atom:updated>
            <content:encoded><![CDATA[<p>This Method will work for tailwind css also</p><p>Requirements:<br>1. playwright <br>{npm install -g playwright<br>npx playwright install}<br>Note : Use — legacy-peer-deps if getting blocker in install</p><p><strong>Route | route.ts file</strong></p><pre>import { NextRequest, NextResponse } from &quot;next/server&quot;;<br><br>import { chromium } from &quot;playwright&quot;;<br><br>import fs from &quot;fs&quot;;<br><br>import path from &quot;path&quot;;<br><br>import axios from &quot;axios&quot;;<br><br>async function imageToBase64(url: string) {<br>  try {<br>    const response = await axios.get(url, { responseType: &quot;arraybuffer&quot; });<br><br>    const buffer = Buffer.from(response.data, &quot;binary&quot;);<br><br>    return `data:image/jpeg;base64,${buffer.toString(&quot;base64&quot;)}`;<br>  } catch (error) {<br>    console.error(&quot;Error loading image:&quot;, error);<br><br>    return &quot;&quot;;<br>  }<br>}<br><br>async function replaceImagesWithBase64(html: string) {<br>  const imageRegex = /&lt;img[^&gt;]+src=&quot;([^&quot;]+)&quot;/g;<br><br>  let match;<br><br>  let htmlWithBase64 = html;<br><br>  while ((match = imageRegex.exec(html)) !== null) {<br>    const imageUrl = match[1];<br><br>    if (!imageUrl.startsWith(&quot;data:image&quot;)) {<br>      const base64 = await imageToBase64(imageUrl);<br><br>      htmlWithBase64 = htmlWithBase64.replace(imageUrl, base64);<br>    }<br>  }<br><br>  return htmlWithBase64;<br>}<br><br>export async function POST(req: NextRequest) {<br>  const { token, formHTML } = await req.json();<br>  const mode = process.env.NODE_ENV || &quot;production&quot;;<br><br>  if (!formHTML) {<br>    return NextResponse.json(<br>      { error: &quot;Missing form data, or token&quot; },<br>      { status: 400 }<br>    );<br>  }<br><br>  try {<br>    const browser = await chromium.launch({<br>      headless: true,<br><br>      args: [&quot;--no-sandbox&quot;, &quot;--disable-setuid-sandbox&quot;],<br>    });<br><br>    const globalsCssPath = path.resolve(process.cwd(), &quot;src/app/globals.css&quot;);<br><br>    const globalsCss = fs.readFileSync(globalsCssPath, &quot;utf-8&quot;);<br>    let tailwindCss = &quot;&quot;;<br>    const tailwindCssPath = path.resolve(<br>      process.cwd(),<br>      &quot;.next/static/css/app/layout.css&quot;<br>    );<br><br>    if (mode == &quot;development&quot;) {<br>      tailwindCss = fs.existsSync(tailwindCssPath)<br>        ? fs.readFileSync(tailwindCssPath, &quot;utf-8&quot;)<br>        : &quot;&quot;;<br>    } else {<br>      const cssDir = path.resolve(process.cwd(), &quot;.next/static/css&quot;);<br>      const cssFiles = fs.readdirSync(cssDir);<br><br>      // Function to check if a CSS file contains Tailwind-specific classes<br>      const isTailwindCss = (cssContent: string) =&gt; {<br>        return /(?:\.\w+)?\b(container|flex|grid|text-xl|p-4|m-2)\b/.test(<br>          cssContent<br>        );<br>      };<br><br>      for (const file of cssFiles) {<br>        if (file.endsWith(&quot;.css&quot;)) {<br>          const filePath = path.join(cssDir, file);<br>          const cssContent = fs.readFileSync(filePath, &quot;utf-8&quot;);<br><br>          if (isTailwindCss(cssContent)) {<br>            tailwindCss = cssContent;<br>            break; // Stop once we find the Tailwind file<br>          }<br>        }<br>      }<br>    }<br><br>    const invoiceHTMLWithBase64 = await replaceImagesWithBase64(formHTML);<br><br>    const htmlWithStyles = `<br>&lt;html&gt;<br>&lt;head&gt;<br>&lt;style&gt;${globalsCss} ${tailwindCss}&lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;${invoiceHTMLWithBase64}&lt;/body&gt;<br>&lt;/html&gt;<br><br>    `;<br><br>    const context = await browser.newContext();<br><br>    const pdfPage = await context.newPage();<br><br>    await pdfPage.setContent(htmlWithStyles, { waitUntil: &quot;load&quot; });<br><br>    const pdfBuffer = await pdfPage.pdf({<br>      format: &quot;legal&quot;,<br>      margin: {<br>        top: 10,<br>        bottom: 10,<br>        left: 10,<br>        right: 10,<br>      },<br>      printBackground: true,<br>      landscape: true,<br>    });<br><br>    await browser.close();<br><br>    return new NextResponse(pdfBuffer, {<br>      headers: {<br>        &quot;Content-Type&quot;: &quot;application/pdf&quot;,<br><br>        &quot;Content-Disposition&quot;: &#39;attachment; filename=&quot;document.pdf&quot;&#39;,<br>      },<br>    });<br>  } catch (error: any) {<br>    console.error(&quot;Error generating PDF:&quot;, error);<br><br>    return NextResponse.json(<br>      { error: `Failed to generate PDF: ${error.message}` },<br><br>      { status: 500 }<br>    );<br>  }<br>}</pre><p><strong>Component | Button to tigger the pdf generation</strong></p><pre>&quot;use client&quot;;<br>import React from &quot;react&quot;;<br><br>const DownloadPdf = () =&gt; {<br>  const get_pdf = async () =&gt; {<br>    const data = document.getElementById(`pdf_div`);<br>    console.log(&quot;got the div content&quot;);<br><br>    if (data) {<br>      const formHTML = data;<br>      // Step 3: Generate PDF<br>      const pdfResponse = await fetch(&quot;/api/generate_pdf&quot;, {<br>        method: &quot;POST&quot;,<br>        headers: {<br>          &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        },<br>        body: JSON.stringify({<br>          token: &quot;formData.token&quot;,<br>          formHTML: formHTML.innerHTML,<br>        }),<br>      });<br><br>      if (!pdfResponse.ok) {<br>        const errorData = await pdfResponse.json();<br>        console.log(<br>          `Failed to generate PDF: ${errorData.error || &quot;Unknown error&quot;}`<br>        );<br>        return;<br>      }<br><br>      // Get PDF blob and create a URL for it<br>      const pdfBlob = await pdfResponse.blob();<br>      //   const pdfURL = URL.createObjectURL(pdfBlob);<br><br>      const url = window.URL.createObjectURL(pdfBlob);<br>      const a = document.createElement(&quot;a&quot;);<br>      a.href = url;<br>      a.download = &quot;document.pdf&quot;;<br>      a.click();<br>      window.URL.revokeObjectURL(url);<br>      //   Update your state or do something with the URL<br>    } else {<br>      console.log(&quot;Form reference not found!&quot;);<br>    }<br>  };<br>  return (<br>    &lt;button<br>      onClick={get_pdf}<br>    &gt;<br>      &lt;CloudDownload /&gt; Download<br>    &lt;/button&gt;<br>  );<br>};<br><br>export default DownloadPdf;</pre><p>Import the above component wherever you want to enable PDF download of the screen.<br> <strong>Important:</strong> Make sure to assign the id value &quot;pdf_div&quot; to the parent &lt;div&gt; of the section you want to export as a PDF.</p><pre>import React from &quot;react&quot;;<br>import DownloadPdf from &quot;@/component/DownloadPdf&quot;<br><br>const ComponentA = () =&gt; {<br>  <br>  return (<br>    &lt;&gt;<br>      &lt;DownloadPdf /&gt;<br>&lt;div id=&quot;pdf_div&quot;&gt;<br><br>{Child components here}<br><br>&lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default ComponentA;</pre><p>Contact for more Next and ReactJS solutions.</p><p>Mail: harish.siri@outlook.com<br>LinkedIn: <a href="https://www.linkedin.com/in/sirikotiharish/">https://www.linkedin.com/in/sirikotiharish/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcaea81404a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Radial Graph By value]]></title>
            <link>https://medium.com/@harish.siri/radial-graph-by-value-8845ecda0577?source=rss-5185abd665b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8845ecda0577</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[ui-ux-design]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Harish Sirikoti]]></dc:creator>
            <pubDate>Fri, 25 Apr 2025 10:16:14 GMT</pubDate>
            <atom:updated>2025-04-25T10:16:14.849Z</atom:updated>
            <content:encoded><![CDATA[<p>At some point in their journey, most UI developers need a radial graph with a gradient effect. Here’s a simple example to help you get started.</p><h3>Code</h3><pre>&quot;use client&quot;;<br>export function RadialGaugeChart({maxValue=5, value=3.5}: {maxValue: number, value: number}) {<br>  const percentage = value / maxValue;<br>  const degrees = percentage * 360;<br><br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;relative w-64 h-64 mx-auto&quot;&gt;<br>        {/* Full circle with gradient and mask based on value */}<br>        &lt;div<br>          className=&quot;absolute inset-0 rounded-full&quot;<br>          style={{<br>            background: `conic-gradient(<br>                red,orange,yellow,green,green<br>              )`,<br>            maskImage: `conic-gradient(white 0deg, white ${degrees}deg, transparent ${degrees}deg, transparent 360deg)`,<br>            WebkitMaskImage: `conic-gradient(white 0deg, white ${degrees}deg, transparent ${<br>              degrees + 20<br>            }deg, transparent 360deg)`,<br>          }}<br>        /&gt;<br><br>        {/* Inner black circle to create the ring effect */}<br>        &lt;div className=&quot;absolute inset-6 rounded-full bg-background&quot; /&gt;<br><br>        {/* Centered text */}<br>        &lt;div className=&quot;absolute inset-0 flex flex-col items-center justify-center&quot;&gt;<br>          &lt;div className=&quot;text-5xl font-bold&quot;&gt;{value.toFixed(1)}&lt;/div&gt;<br>          &lt;div className=&quot;text-muted-foreground&quot;&gt;out of {maxValue}&lt;/div&gt;<br>        &lt;/div&gt;<br>        <br>      &lt;/div&gt;<br>      {value&gt;maxValue?&lt;div className=&quot;mx-auto text-red-500&quot;&gt;Value Exceeded than Overall  &lt;/div&gt;:null}<br>    &lt;/&gt;<br>  );<br>}</pre><p>Useage</p><pre>import { RadialGaugeChart } from &#39;@/components/charts/radialchart&#39;;<br>import React from &#39;react&#39;<br><br>const RatingRadialGraph = () =&gt; {<br>  return (<br>    &lt;&gt;<br>     &lt;RadialGaugeChart value={3.5} maxValue={5} /&gt;<br>    &lt;/&gt;<br>  )<br>}<br><br>export default RatingRadialGraph</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*iAOX6uZeIdp-HAFdViz9Cg.png" /><figcaption>Radial Graph</figcaption></figure><p>Contact for more UI solutions</p><p>Mail: harish.siri@outlook.com<br>LinkedIn: <a href="https://www.linkedin.com/in/sirikotiharish/">https://www.linkedin.com/in/sirikotiharish/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8845ecda0577" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PDF Generation in Power Platform]]></title>
            <link>https://medium.com/@harish.siri/pdf-generation-in-power-platform-85450465aab7?source=rss-5185abd665b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/85450465aab7</guid>
            <category><![CDATA[sharepoint-online]]></category>
            <category><![CDATA[powerapps]]></category>
            <dc:creator><![CDATA[Harish Sirikoti]]></dc:creator>
            <pubDate>Tue, 08 Apr 2025 15:24:29 GMT</pubDate>
            <atom:updated>2025-04-08T15:24:29.973Z</atom:updated>
            <content:encoded><![CDATA[<p>Generating dynamic PDFs in platforms like PowerApps and SharePoint has traditionally been complex and often required third-party tools, which can be costly. However, I’ve streamlined this process within PowerApps, eliminating the need for external solutions.</p><h3>Pre requisites:</h3><ol><li>Powerapps appilcation with a button to trigger the PowerAutomate Flow.<br><em>[Note: This method requires a button to trigger the Flow, so you can use this in SharePoint also, by chainging the trigger option in the flow buy Http request method.]</em></li><li>A dummy folder in onedrive, <em>I have a floder with name ‘generated pdfs’ .you can create a new one if you want.</em></li><li>Basic Knowlege on PowerAutomate.</li></ol><h3>Step 1:</h3><p>PowerApps Application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uEmG6icIez77N17raz--pQ.png" /><figcaption>Sample Power apps</figcaption></figure><p>This is a Powerapps application, this is demo to manage Job Posts with in the organization.<br>Here to view the complete details of a single job we need to download a pdf. The pdf should be generated based on the Job selected by the user.<br>Here we go.</p><h3>Step 2:</h3><p>Create a Powerautomate flow with trigger ‘Power Apps (V2)’ and add an input with type number/text name it ‘id’.<br><em>[Note : Here iam passing the item id i.e. Job ID to the flow from poweapps if you need you can send other parameters as per your requirements.]</em></p><p>Using this ID i will fetch the complete data of the item Using ‘Get Item’ action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*R2OF_haDF70laJisIyt1IA.png" /><figcaption>Getting item details based on the ID Passed</figcaption></figure><p>Now you are fetching the dinamic content, using this content we should generate the Pdf.</p><h3>Step 3:</h3><p>Prepare a simple HTML code as you need to view the content in the PDF file you can use AI tools to generate this HTML.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Job Post&lt;/title&gt;<br>    &lt;style&gt;<br>        body {<br>            font-family: Arial, sans-serif;<br>            background-color: #f4f4f9;<br>            margin: 0;<br>            padding: 20px;<br>        }<br>        .job-post {<br>            max-width: 600px;<br>            background-color: #ffffff;<br>            margin: 50px auto;<br>            padding: 20px;<br>            border-radius: 8px;<br>            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);<br>        }<br>        h1 {<br>            text-align: center;<br>            color: #ffffff;<br>            background-color: #4CAF50;<br>            padding: 10px;<br>            border-radius: 8px 8px 0 0;<br>            margin: -20px -20px 20px -20px;<br>        }<br>        .field {<br>            margin-bottom: 15px;<br>            padding: 10px;<br>            border-left: 5px solid #4CAF50;<br>            background-color: #f9f9f9;<br>            border-radius: 4px;<br>        }<br>        .field label {<br>            font-weight: bold;<br>            color: #333333;<br>            display: block;<br>            margin-bottom: 5px;<br>        }<br>        .field p {<br>            margin: 0;<br>            color: #555555;<br>        }<br>    &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;job-post&quot;&gt;<br>        &lt;h1&gt;Job Post&lt;/h1&gt;<br>        &lt;div class=&quot;field&quot;&gt;<br>            &lt;label&gt;Job Title:&lt;/label&gt;<br>            &lt;p&gt;@{outputs(&#39;Get_item&#39;)?[&#39;body/Job_x0020_Title/Value&#39;]}&lt;/p&gt;<br>        &lt;/div&gt;<br>&lt;div class=&quot;field&quot;&gt;<br>            &lt;label&gt;Job ID:&lt;/label&gt;<br>            &lt;p&gt;@{outputs(&#39;Get_item&#39;)?[&#39;body/ID&#39;]}&lt;/p&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;field&quot;&gt;<br>            &lt;label&gt;Job Description:&lt;/label&gt;<br>            &lt;p&gt;@{outputs(&#39;Get_item&#39;)?[&#39;body/Job_x0020_Description&#39;]}&lt;/p&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;field&quot;&gt;<br>            &lt;label&gt;Experience:&lt;/label&gt;<br>            &lt;p&gt;@{outputs(&#39;Get_item&#39;)?[&#39;body/Experience_x0020_in_x0020_years&#39;]} years&lt;/p&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;field&quot;&gt;<br>            &lt;label&gt;Department:&lt;/label&gt;<br>            &lt;p&gt;@{outputs(&#39;Get_item&#39;)?[&#39;body/Department/Value&#39;]}&lt;/p&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Here is a sample HTML code to view the Job Posts.<br><em>[Note : here iam using Flow variables to replace to dinamic content in the HTML code like <br>&lt;div class=”field”&gt;<br> &lt;label&gt;Experience:&lt;/label&gt;<br> </em><strong><em>&lt;p&gt;@{outputs(‘Get_item’)?[‘body/Experience_x0020_in_x0020_years’]} years&lt;/p&gt;</em></strong><em><br> &lt;/div&gt;]</em></p><h3>Step 4:</h3><p>Paste this HTML code in ‘create file’ action in flow of onedrive.<br>Here you will create a HTML file in ‘/Poweapps PDfs generation’ onedrive folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*FcTGWjxh5bwl4YYn5C-1BQ.png" /></figure><p>Here iam using ‘/Poweapps PDfs generation’ folder in my personal onedriv.<br>Imp: use ‘.html’ at the end of the file name.</p><h3>Step 5:</h3><p>Now we have to convert the HTML file into PDF using ‘convert file’ action in the flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*Pp3Xmy9T7lWduxWrIbHieA.png" /></figure><p>The file id you will get it from ‘Create file’ action.</p><h3>Step 6:</h3><p>Now go to you onedrive open ‘/Poweapps PDfs generation’ folder you have created.<br>Upload a dummy pdf file . (any random pdf file, if you dont have any pdf download a sample file from internet)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p5nJxvRU5bpKfhDcZq0ytw.png" /></figure><p>I have uploaded here and named it as ‘return_pdf.pdf’. (Name it as you need)</p><h3>Step 7:</h3><p>Now create a another file in the same folder and name it as the pdf file you have uploaded in the onedrive folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*K4nG8PqSRYVjcBLCCLiGlg.png" /></figure><p><strong>Imp: </strong>The file name should end with ‘.pdf’ the name should match with the file uploaded in the onedrive. <br>The ‘Body’ you will get it from the ‘Convert file’ action.</p><h3>Step 8:</h3><p>Open the pdf file in the onedrive using ‘open in browser’ option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-SadiAdM4_MmF2sjl2jdfA.png" /></figure><p>Copy the file url upto the file name ‘return_pdf.pdf’.<br>The url looks like this,<br>‘<a href="https://zelarsoft1-my.sharepoint.com/personal/harish_siri_zelarsoft_com/Documents/Powerapps%20PDfs%20generation/return_pdf.pdf?CT=1744124697262&amp;OR=ItemsView">https://XXXXX-my.sharepoint.com/personal/xxxxxxxxxxxx/Documents/Powerapps%20PDfs%20generation/return_pdf.pdf</a>’</p><p>Use ‘Respond to a Power App or flow’ action and and out put variable with name ‘url’ of type text.<br>Now past the file url here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*_-m4XYT5iurv-cc6Nqf85w.png" /><figcaption>This URL will be returned to the PowerApp or the Sharepoint webpart from where this flow is called.</figcaption></figure><h3>Step 9:</h3><p>Go to the PowerApps now.<br>Add this Flow to the PowerApps.(my flow name is ‘Pdf Generate’)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*tPgq8PXZl1fMBESbOBj5uw.png" /></figure><p>Now go to onselect property of button on icon in the PowerApp,<br>write this formule there.</p><pre>Download(PdfGenerate.Run(ThisItem.ID).url)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lDfmQbznjIsAF5HEmzX-zQ.png" /></figure><p>Here iam passing the item ID using (ThisItem.ID) to the flow so the flow will generate the dinamic pdf file with respect to the Item selected.</p><p>Now the app is ready to generate the PDF files.</p><p><em>If you need more solutions on PowerApps or PowerAutomate,<br>Contact : harish.siri@outlook.com,<br>Watsapp: +91 9652725760</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85450465aab7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Audit Trail for Supabase Database]]></title>
            <link>https://medium.com/@harish.siri/simpe-audit-trail-for-supabase-database-efefcce622ff?source=rss-5185abd665b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/efefcce622ff</guid>
            <dc:creator><![CDATA[Harish Sirikoti]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 14:12:57 GMT</pubDate>
            <atom:updated>2025-04-26T09:40:20.978Z</atom:updated>
            <content:encoded><![CDATA[<p>Most applications that use Supabase Auth require a simple audit trail report for regulatory purposes. Here are some straightforward steps to implement one.</p><p><strong>Important Note:<br></strong> 1. This method will work for the applications which uses supabase authentication.<br>2. Run all the following commands in the same project in which the application is using for authentication and for data base.<br>3. All tables should have “id” column as primary key, if you are using another column as primary key then upate the SQL query according to that.</p><h3>Step 1:</h3><p>Go to SQL Editor select new editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*_JclK6dlSFsGQhjhTwES6w.png" /></figure><p><strong>Create a audit table: <br></strong>Run this below SQL query in editor</p><pre>CREATE TABLE audit_log (<br>  audit_id SERIAL PRIMARY KEY,            -- Unique ID for each audit record<br>  user_email TEXT NOT NULL,               -- Email of the user who made the change<br>  table_name TEXT NOT NULL,               -- Name of the table being modified<br>  item_id TEXT NOT NULL,                  -- ID of the item being modified (as text)<br>  action TEXT NOT NULL,                   -- Action type: INSERT, UPDATE, DELETE<br>  changes JSONB NOT NULL,                 -- A JSONB object containing the changes<br>  created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP  -- Timestamp of the change<br>);</pre><h3>Step 2:</h3><p><strong>Create a function to upadate all the changes in audit table.</strong><br>Run this below SQL query in editor in new editor.</p><pre>DROP FUNCTION IF EXISTS log_changes() CASCADE;<br><br>CREATE OR REPLACE FUNCTION log_changes()<br>RETURNS TRIGGER AS $$<br>DECLARE<br>  item_id TEXT;<br>BEGIN<br>  -- Determine the item_id based on the table being modified<br>  IF TG_TABLE_NAME = &#39;table_one&#39; THEN<br>    item_id := COALESCE(CAST(OLD.table_one_id AS TEXT), CAST(NEW.table_one_id AS TEXT));<br>  ELSIF TG_TABLE_NAME = &#39;table_two&#39; THEN<br>    item_id := COALESCE(CAST(OLD.table_two_id AS TEXT), CAST(NEW.table_two_id AS TEXT));<br>  ELSE<br>    item_id := COALESCE(CAST(OLD.id AS TEXT), CAST(NEW.id AS TEXT));  -- Fallback for other tables<br>  END IF;<br><br>  -- Insert change details into the audit_log table<br>  INSERT INTO audit_log (user_email, table_name, item_id, action, changes)<br>  VALUES (<br>    COALESCE(<br>      (auth.jwt() -&gt;&gt; &#39;email&#39;), -- Attempt to get the user&#39;s email from the JWT context<br>      &#39;db_edit&#39;            -- If no user, use a default value<br>    ),<br>    TG_TABLE_NAME,              -- The name of the table being modified<br>    item_id,                    -- Use the determined item_id<br>    TG_OP,                      -- The action performed (INSERT, UPDATE, DELETE)<br>    jsonb_build_object(         -- The changes (old and new)<br>      &#39;old&#39;, CASE <br>               WHEN TG_OP = &#39;DELETE&#39; THEN row_to_json(OLD)::jsonb<br>               WHEN TG_OP = &#39;UPDATE&#39; THEN row_to_json(OLD)::jsonb<br>               ELSE NULL::jsonb<br>             END,<br>      &#39;new&#39;, CASE <br>               WHEN TG_OP = &#39;INSERT&#39; THEN row_to_json(NEW)::jsonb<br>               WHEN TG_OP = &#39;UPDATE&#39; THEN row_to_json(NEW)::jsonb<br>               ELSE NULL::jsonb<br>             END<br>    )<br>  );<br>  RETURN NEW;<br>END;<br>$$ LANGUAGE plpgsql;</pre><p><strong>Note: </strong><br>Here I have given some example if the primary column in your table is not “id” then you can manage it by using {if ifelse}.</p><h3>Step 3:</h3><p>Create trigger for each table in this project using below SQL query in new Editor, you can avoid this step for some tables if you dont want to maintain this audit log for that spefic table. <br>(Avoid creating this trigger for audit table)</p><pre>DROP TRIGGER IF EXISTS trigger_table_one_changes ON table_one;<br>CREATE TRIGGER trigger_table_one_changes<br>AFTER INSERT OR UPDATE OR DELETE ON table_one<br>FOR EACH ROW EXECUTE FUNCTION log_changes();<br><br>DROP TRIGGER IF EXISTS trigger_table_name_changes ON table_name;<br>CREATE TRIGGER trigger_table_name_changes<br>AFTER INSERT OR UPDATE OR DELETE ON table_name<br>FOR EACH ROW EXECUTE FUNCTION log_changes();</pre><p>In the above code i have given examples for 2 tables [‘table_name’,’table_one’] you should repeat this for all tables expect the audit table, and run this all this triggers SQL queries in single go.</p><p>Now your audit report is ready.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efefcce622ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Read Gmails in Next.JS]]></title>
            <link>https://medium.com/@harish.siri/read-gmails-in-next-js-a18ab77ddb5b?source=rss-5185abd665b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a18ab77ddb5b</guid>
            <dc:creator><![CDATA[Harish Sirikoti]]></dc:creator>
            <pubDate>Mon, 30 Sep 2024 12:42:31 GMT</pubDate>
            <atom:updated>2024-09-30T12:42:31.357Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Note: </strong>This method will work for React also.</p><p>Follow this steps to add Google login button and read gmails from the inbox.<br><strong>Note</strong>: This method wont work at organization level.</p><p><strong>Step 1:</strong><br>Create a google cloude app at <a href="https://console.cloud.google.com/apis">https://console.cloud.google.com/apis</a></p><ul><li>Select ‘Library’ on the left hand menu.</li><li>Enter ‘gmail api’ in the search box.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*Uyavx9yKjN_il9h5WFoRBw.png" /></figure><ul><li>Click on Gmail Api</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*MpJpwWlNJR0REqJZY9YAEw.png" /></figure><ul><li>Click on Enable button.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*h1WQSWZjo2TKyJ67al6guA.png" /></figure><ul><li>After enable follow next steps.</li><li>Select ‘OAuth consent screen’ on the left hand side menu.</li><li>Select ‘External’ at ‘User Type’ and click on ‘Create’ or ‘Next’ button.</li><li>Fill ‘App information’ and ‘Developer contact information’ fileds. Remaining fields like App logo,App domain and Authorized domains are should be filled after when the application is in live.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*hoEtQjMdpC_6t_Jz2pO-nQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*00CLoa7T8zN2rjpDdxF3rQ.png" /></figure><ul><li>Then click on ‘Save and Continue’ button.</li><li>Click on ‘Add or Remove Scopes’ button.</li><li>Select the scopes need for developement.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*6N3WAsyT1bsOvcuZ2VkfAg.png" /></figure><ul><li>Make sure that all this scopes are selected which are shown in the below images.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*dOslHNf2qK_Y6-q1xS-SfQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*xuFbR65wC23GO0P9OP4aVA.png" /></figure><ul><li>Now click on ‘Save and Continue’.</li><li>Now add Test users</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*ikzV15r3DPiC8158MQ70gQ.png" /></figure><ul><li><strong>Note: </strong>only the users mensioned here are eble to login and use this application in testing phase after publishing this will be avialable to everyone.</li><li>Now click on ‘Save and Continue’.</li><li>Go to the summary now and click on ‘Back to Daskboard’.</li><li>Now select ‘Credentials’ on the left side menu.</li><li>Click on ‘Create Credentials’ on the top</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*PehJ4UDJX1DdS0ZKQMnvsQ.png" /></figure><ul><li>Select ‘OAuth client ID’.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*qwjq-1zT445c2Q-LYv3oxA.png" /></figure><ul><li>Select ‘Application Type’ with Web application.</li><li>Now fill the Authorized URIs with ‘<a href="http://localhost:3000/">http://localhost:3000</a>’ or your application url, if the application is in live.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*YzGaH8aRd1FEv9kwCihfBw.png" /></figure><ul><li>Now the OAuth 2.0 Client IDs is created.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LXXgr7N8wE53cvWpHZ64uA.png" /></figure><ul><li>Click on Download button and this JSON file this file will contain ‘Client ID’ and ‘Client secret’.</li></ul><p><strong>Step 2:</strong></p><p>Create Next JS application.</p><ul><li>Create .env file add add your client id and client secret from above json file like below.</li></ul><p>GOOGLE_CLIENT_ID=’your client id’</p><p>GOOGLE_CLIENT_SECRET=’your client secret’</p><ul><li>Run {npm i @react-oauth/google} in terminal.</li><li>Create actions.tsx file in app folder and add this below code —ex: .app/actions.tsx</li></ul><pre>&#39;use server&#39;<br>export const googleClientID=async()=&gt;{<br>    const url=process.env.GOOGLE_CLIENT_ID;<br>    return url<br>}</pre><ul><li>Create ‘mails’ folder in app folder and add page.tsx in mails folder — ex: .app/mails/page.tsx</li><li>Now paste the below code in mails/page.tsx file.</li></ul><pre>&#39;use client&#39;<br>import { googleLogout, useGoogleLogin } from &#39;@react-oauth/google&#39;;<br>import { useState } from &#39;react&#39;;<br><br>interface User {<br>    email: string;<br>    family_name: string;<br>    given_name: string;<br>    id: string;<br>    name: string;<br>    picture: string;<br>  }<br><br>export default function Mails() {<br>    const [user, setUser] = useState&lt;User | any&gt;(null);<br>    const [toggle, setToggle] = useState(false);<br>    const [emails, setEmails] = useState&lt;any&gt;([]);<br><br>const fetchGmailSubjects = async (user:any) =&gt; {<br>    try {<br>        if (!user) {<br>            return;<br>        }<br><br>        const response = await fetch(<br>            `https://www.googleapis.com/gmail/v1/users/me/messages`,<br>            {<br>                method: &#39;GET&#39;,<br>                headers: {<br>                    Authorization: `Bearer ${user.access_token}`,<br>                    Accept: &#39;application/json&#39;,<br>                },<br>            }<br>        );<br><br>        const data = await response.json();<br><br>        const messages = data.messages.slice(0, 100);<br>        for (const message of messages) {<br>            const messageResponse = await fetch(<br>                `https://www.googleapis.com/gmail/v1/users/me/messages/${message.id}`,<br>                {<br>                    method: &#39;GET&#39;,<br>                    headers: {<br>                        Authorization: `Bearer ${user.access_token}`,<br>                        Accept: &#39;application/json&#39;,<br>                    },<br>                }<br>            );<br><br>            const messageData = await messageResponse.json();<br><br>            const subjectHeader = messageData.payload.headers.find(<br>                (header:any) =&gt; header.name === &#39;Subject&#39;<br>            );<br><br>            const fromHeader = messageData.payload.headers.find(<br>                (header:any) =&gt; header.name === &#39;From&#39;<br>            );<br><br>            const dateHeader = messageData.payload.headers.find(<br>                (header:any) =&gt; header.name === &#39;Date&#39;<br>            );<br><br>            const body = messageData.snippet; // Using snippet as an example. Adjust according to your needs.<br>            console.log(&quot;mails&quot;,subjectHeader.value);  <br>            setEmails((prevEmails:any) =&gt; [<br>                ...prevEmails,{ subject: subjectHeader.value, date: dateHeader.value, from: fromHeader.value, id: message.id, body },<br>            ]);<br><br>        }<br><br>    } catch (error) {<br><br>    }<br>};<br><br>const fetchUserProfile = (accessToken:any) =&gt; {<br>    fetch(`https://www.googleapis.com/oauth2/v1/userinfo?access_token=${accessToken}`, {<br>        method: &#39;GET&#39;,<br>        headers: {<br>            Authorization: `Bearer ${accessToken}`,<br>            Accept: &#39;application/json&#39;,<br>        },<br>    })<br>        .then((res) =&gt; res.json())<br>        .then((data) =&gt; {<br>            console.log(data)<br>            setUser(data);<br>            setToggle(true)<br>            // fetchLatestMailForUser(data.email);<br>        })<br>        .catch((err) =&gt; console.log(err));<br>};<br>const login = useGoogleLogin({<br>    onSuccess: (codeResponse:any) =&gt; {<br>        const tempUser= { ...codeResponse, tokenCreatedAt: new Date() }<br>        console.log(&#39;tempUser&#39;,tempUser);<br>        <br>        fetchUserProfile({ ...codeResponse, tokenCreatedAt: new Date() }.access_token);<br>        fetchGmailSubjects(tempUser)<br>    },<br>    onError: (error:any) =&gt; console.log(&#39;Login Failed:&#39;, error),<br>    scope: &#39;https://www.googleapis.com/auth/gmail.readonly&#39;,<br>});<br>  if (!toggle) {<br>    return (<br>      &lt;div className=&quot;flex justify-center items-center h-screen&quot;&gt;<br>        &lt;button onClick={() =&gt;{ login()}} className=&quot;bg-blue-500 text-white px-4 py-2 rounded&quot;&gt;<br>          Sign in with Google<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br><br>  return (<br>    &lt;div className=&quot;container mx-auto p-4&quot;&gt;<br>         &lt;div className=&quot;flex justify-center items-center&quot;&gt;<br>      {user ? (<br>        &lt;div className=&quot;bg-white p-6 rounded-lg shadow-xl transform transition duration-500 hover:scale-105 hover:shadow-2xl&quot;&gt;<br>          &lt;div className=&quot;flex flex-col items-center&quot;&gt;<br>            {/* Profile picture */}<br>            &lt;img<br>              src={user.picture}<br>              alt=&quot;Profile&quot;<br>              className=&quot;w-24 h-24 rounded-full border-4 border-blue-500 animate-bounce&quot;<br>            /&gt;<br>            {/* User name */}<br>            &lt;h2 className=&quot;text-2xl font-bold mt-4 text-gray-900&quot;&gt;{user.name}&lt;/h2&gt;<br>            {/* Email */}<br>            &lt;p className=&quot;text-gray-600&quot;&gt;{user.email}&lt;/p&gt;<br>          &lt;/div&gt;<br>          {/* Additional Info */}<br>          &lt;div className=&quot;mt-4&quot;&gt;<br>            &lt;p className=&quot;text-sm text-gray-600&quot;&gt;<br>              &lt;strong&gt;Family Name:&lt;/strong&gt; {user.family_name}<br>            &lt;/p&gt;<br>            &lt;p className=&quot;text-sm text-gray-600&quot;&gt;<br>              &lt;strong&gt;Given Name:&lt;/strong&gt; {user.given_name}<br>            &lt;/p&gt;<br>            &lt;p className=&quot;text-sm text-gray-600&quot;&gt;<br>              &lt;strong&gt;ID:&lt;/strong&gt; {user.id}<br>            &lt;/p&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      ) : (<br>        // Show a loading message or a placeholder when the user is null<br>        &lt;p className=&quot;text-gray-600 text-xl&quot;&gt;Loading user profile...&lt;/p&gt;<br>      )}<br>    &lt;/div&gt;<br>      &lt;h1 className=&quot;text-2xl font-bold mb-4&quot;&gt;Gmail Inbox&lt;/h1&gt;<br>      &lt;button onClick={() =&gt;  googleLogout()} className=&quot;bg-red-500 text-white px-4 py-2 rounded mb-4&quot;&gt;<br>        Sign out<br>      &lt;/button&gt;<br>      &lt;table className=&quot;w-full border-collapse border border-gray-300 text-gray-600&quot;&gt;<br>        &lt;thead&gt;<br>          &lt;tr className=&quot;bg-gray-100&quot;&gt;<br>            &lt;th className=&quot;border border-gray-300 p-2 &quot;&gt;Subject&lt;/th&gt;<br>            &lt;th className=&quot;border border-gray-300 p-2 &quot;&gt;Sno&lt;/th&gt;<br>            &lt;th className=&quot;border border-gray-300 p-2&quot;&gt;From&lt;/th&gt;<br>            &lt;th className=&quot;border border-gray-300 p-2&quot;&gt;Date&lt;/th&gt;<br>            &lt;th className=&quot;border border-gray-300 p-2&quot;&gt;Body&lt;/th&gt;<br>          &lt;/tr&gt;<br>        &lt;/thead&gt;<br>        &lt;tbody&gt;<br>          {emails.map((email:any,index:number) =&gt; (<br>            &lt;tr key={email.id}&gt;<br>              &lt;td className=&quot;border border-gray-300 p-2&quot;&gt;{index+1 }&lt;/td&gt;<br>              &lt;td className=&quot;border border-gray-300 p-2&quot;&gt;{email.subject}&lt;/td&gt;<br>              &lt;td className=&quot;border border-gray-300 p-2&quot;&gt;{email.from}&lt;/td&gt;<br>              &lt;td className=&quot;border border-gray-300 p-2&quot;&gt;{email.date}&lt;/td&gt;<br>              &lt;td className=&quot;border border-gray-300 p-2&quot;&gt;{email.body}&lt;/td&gt;<br>            &lt;/tr&gt;<br>          ))}<br>        &lt;/tbody&gt;<br>      &lt;/table&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><ul><li>In .app/page.tsx file add the below code.</li></ul><pre>&quot;use client&quot;;<br>import { GoogleOAuthProvider } from &quot;@react-oauth/google&quot;;<br>import { googleClientID } from &quot;./actions&quot;;<br>import Mails from &quot;./mails/page&quot;;<br>import { useEffect, useState } from &quot;react&quot;;<br><br>export default function Home() {<br>  const [client_ID, setClientID] = useState(&quot;google client id&quot;);<br>  const getID = async () =&gt; {<br>    const url: any = await googleClientID();<br>    setClientID(url);<br>  };<br>  useEffect(() =&gt; {<br>    getID();<br>  }, []);<br><br>  return (<br>    &lt;GoogleOAuthProvider clientId={client_ID}&gt;<br>      &lt;Mails /&gt;<br>    &lt;/GoogleOAuthProvider&gt;<br>  );<br>}</pre><p>Now run the application using cmd {npm run dev}</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a18ab77ddb5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Send emails via Supabase Edge Function]]></title>
            <link>https://medium.com/@harish.siri/send-emails-via-supabase-edge-function-95daf2b4a14c?source=rss-5185abd665b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/95daf2b4a14c</guid>
            <dc:creator><![CDATA[Harish Sirikoti]]></dc:creator>
            <pubDate>Thu, 30 May 2024 05:30:18 GMT</pubDate>
            <atom:updated>2024-05-30T05:30:18.171Z</atom:updated>
            <content:encoded><![CDATA[<p>We cannot send emails directly from front-end JavaScript, so we need to use Node.js or other server-side code and deploy it. Fortunately, Supabase Edge Functions offer a simple solution for this.</p><h3>Prerequisites</h3><p>· Docker desktop.<br>· Visual studio.<br>· SMPT provider. (Iam using<a href="https://sendgrid.com/en-us"> SendGrid</a> provider)</p><h3>To create a Supabase Edge Function, follow these steps:</h3><ol><li><strong>Set Up Supabase CLI</strong>:<br>Install the Supabase CLI if you haven’t already. You can do this using npm:</li></ol><pre>npm install -g supabase</pre><p>2. <strong>Initialize Supabase Project</strong>:<br>Navigate to your project directory and initialize a new Supabase project:</p><pre>npx supabase init</pre><p>3. <strong>Create a New Edge Function</strong>:<br> -Inside your project directory, create a new function.<br> -Replace &lt;function-name&gt; with your desired function name. This command will create a new directory with the necessary files for your function.</p><pre>npx supabase functions new &lt;function-name&gt;</pre><p>4. <strong>Write Your Function Code</strong>:<br>- In the created directory, you’ll find an index.ts file (or index.js if you&#39;re using JavaScript). Write your function logic in this file. like send emails code is given below:</p><pre><br>import nodemailer from &#39;npm:nodemailer@6.9.10&#39;;<br>import { serve } from &quot;https://deno.land/std@0.131.0/http/server.ts&quot;;  // Deno&#39;s HTTP server module<br><br>// SMTP credentials for SendGrid (hardcoded, not recommended for production)<br>const transport = nodemailer.createTransport({<br>  host: &quot;smtp.sendgrid.net&quot;,<br>  port: 465,<br>  secure: true,<br>  auth: {<br>    user: &#39;username&#39;,  // SendGrid SMTP username<br>    pass: &#39;password&#39;  // SendGrid SMTP password<br>  }<br>});<br><br>console.log(`Function &quot;send-email-smtp&quot; up and running!`);<br><br>function corsHeaders() {<br>  return {<br>    &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;,  // Allow all origins; use specific origins in production<br>    &quot;Access-Control-Allow-Methods&quot;: &quot;GET, POST, OPTIONS&quot;,  // Allowed HTTP methods<br>    &quot;Access-Control-Allow-Headers&quot;: &quot;Content-Type, Authorization&quot;,  // Allowed headers<br>  };<br>}<br><br>serve(async (req) =&gt; {<br>  if (req.method === &quot;OPTIONS&quot;) {<br>    // Handle preflight request<br>    return new Response(null, {<br>      headers: corsHeaders(),<br>    });<br>  }<br><br>  try {<br>    const { to, subject, text } = await req.json();<br>    <br>    await new Promise&lt;void&gt;((resolve, reject) =&gt; {<br>      transport.sendMail({<br>        from: &quot;example@gmail.com&quot;,<br>        to,<br>        subject,<br>        text,<br>      }, (error) =&gt; {<br>        if (error) {<br>          return reject(error);<br>        }<br>        resolve();<br>      });<br>    });<br><br>    return new Response(JSON.stringify({ message: &quot;Email sent successfully&quot; }), {<br>      status: 200,<br>      headers: corsHeaders(),<br>    });<br><br>  } catch (error) {<br>    return new Response(<br>      JSON.stringify({ message: &quot;Failed to send email&quot;, error: error.message }),<br>      {<br>        status: 500,<br>        headers: corsHeaders(),<br>      }<br>    );<br>  }<br>});</pre><p><strong>5. Deploy Your Function</strong>: <br>- To deploy your function, use the following command:</p><pre>npx supabase functions deploy &lt;function-name&gt;</pre><p>{ NOTE: if you get this error.<br><strong>Access token not provided.</strong> Supply an access token by running supabase login or setting the<strong> SUPABASE_ACCESS_TOKEN</strong> environment variable.<br>Try rerunning the command with — debug to troubleshoot the error.</p><p>Then run: <strong>[ npx supbase login ]<br></strong>this will redirect to the browser to login, login with your Supabase account details.<br>Now run<strong> npx supabase functions deploy &lt;function-name&gt;</strong></p><p>}</p><p><strong>6. Call Your Function</strong>:<br>- Once deployed, you can call your function using the provided URL. You can find this URL in the Supabase dashboard under the “Functions” section.</p><p>7. <strong>Example of Calling the Function</strong>:<br>- You can call the deployed function from your front-end or any other client. Here’s an example using fetch in JavaScript:</p><pre>const sendEmail = async (email,sub,message) =&gt; {<br>    try {<br>      const response = await fetch(&#39;https://&lt;your-supabase-project&gt;.supabase.co/functions/v1/&lt;function-name&gt;&#39;, {<br>        method: &#39;POST&#39;,<br>        headers: {<br>          &#39;Content-Type&#39;: &#39;application/json&#39;,<br>          &#39;Authorization&#39;: `Bearer eyJhbGciOiJIUzI1NiIsIoxNzE1NjY4ODU4LCJpYXQiOjE3MTU2NjUyNTgsImlzcyI6Imh0dHBzOi8vc3NzeGJ2eXlwcmJ1dWF3YnBtZXAuc3VwYWJhc2UuY28vYXV0aC92MSIsInN1YiI6IjllMmEyZTMyLWNlZTUtNDAxYy1iMzQyLTRjMjU0NjA5YTBjMCIsImVtYWlsIjoiYW1laDEwMzFAZ21haWwuY29tIiwicGhvbmUiOiIiLCJhcHBfbWV0YWRhdGEiOnsicHJvdmlkZXIiOiJlbWFpbCIsInByb3ZpZGVycyI6WyJlbWFpbCJdfSwidXNlcl9tZXRhZGF0YSI6eyJlbWFpbCI6ImFtZWgxMDMxQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwicGhvbmVfdmVyaWZpZWQiOmZhbHNlLCJzdWIiOiI5ZTJhMmUzMi1jZWU1LTQwMWMtYjM0Mi00YzI1NDYwOWEwYzAifSwicm9sZSI6ImF1dGhlbnRpY2F0ZWQiLCJhYWwiFBKeiSI3260LRLVaY`, // Use the stored token<br>// update the &#39;Authorization&#39;         <br>},<br>        body: JSON.stringify({<br>          to: email,<br>          subject:sub,<br>          text: message,<br>        }),<br>      });<br><br>      if (response.ok) {<br>        console.log(&#39;Email sent successfully!&#39;);<br>      } else {<br>        console.error(&#39;Failed to send email:&#39;, response.statusText);<br>        // setStatus(&#39;Failed to send email1.&#39;);<br>      }<br>    } catch (error) {<br>      console.error(&#39;Error sending email:&#39;, error);<br>    //   setStatus(&#39;Failed to send email.&#39;);<br>    }<br>  };</pre><p>Replace &lt;your-supabase-project&gt; and &lt;function-name&gt; with your actual project details.</p><p>By following these steps, you can create and deploy a Supabase Edge Function to handle tasks like sending emails from server-side code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95daf2b4a14c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating SharePoint list and integrated PowerApps form]]></title>
            <link>https://medium.com/@harish.siri/migrating-sharepoint-list-and-integrated-powerapps-form-2bf674d312b0?source=rss-5185abd665b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bf674d312b0</guid>
            <category><![CDATA[powerapps]]></category>
            <category><![CDATA[sharepoint-online]]></category>
            <dc:creator><![CDATA[Harish Sirikoti]]></dc:creator>
            <pubDate>Fri, 10 Nov 2023 06:27:34 GMT</pubDate>
            <atom:updated>2023-11-10T06:27:34.149Z</atom:updated>
            <content:encoded><![CDATA[<p>While migrating SharePoint lists from one tenant to another is a known process, the challenge arises when the SharePoint list form is altered using PowerApps. Post-migration, the same PowerApps form doesn’t exist in the second tenant as it did in the first.</p><h3><strong>Now the Solution is here.</strong></h3><p>If you’re unfamiliar with the process of migrating a list from one tenant to another, please refer to the provided link for guidance.<a href="https://www.manageengine.com/sharepoint-management-reporting/kb/how-to-migrate-list-from-one-site-collection-to-another.html"> How to migrate SharePoint List from one tenant to another?</a></p><h3><strong><em>Prerequisites</em></strong></h3><p>· The ShaPoint list in the second tenant should be exact list name, all columns name and columns type should be same.</p><p>· You should have SharePoint and PowerApps admin access.</p><h3><strong>Now we will learn this taking example.</strong></h3><p>We should migrate PowerApps form of Time Sheets SharePoint List of tenant id (XXXXX) to tenant id (YYYYY).</p><p>Here are the images of list and PowerApps form in tenant XXXXX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35C_rZEVeDlrQSXGCvPvNg.png" /><figcaption>List in tenant XXXXX</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BG9K5ha7NBbPYd9bGS1L-Q.png" /><figcaption>Intigrated PowerApps form for Time Sheets list in tenant XXXXX</figcaption></figure><p><strong>Step 1: In tenant XXXXX</strong></p><p>· Go to List settings.</p><p>· Go to Form settings.</p><p>· Click on “See versions and usage”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*cv3D7XM0-JHwpID0o8aFiA.png" /></figure><p>· Click on “Export Package” (Now you will be navigated to PowerApps page)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*R821zaKgyvt-naWx4DiDJw.png" /></figure><p>· Fill name field with List name and update the ‘import setup’ option to ‘Create as new’.</p><p>· Click on “Export” button. (Now, a zip folder containing the specified list name will be downloaded).</p><p><strong>Step 2: Modify the downloaded Zip folder.</strong></p><p>· Don’t Unzip the folder, open the folder.</p><p>· Open the “Microsoft.PowerApps” folder and then open “apps” folder.</p><p>· Next, locate and open the folder labeled with a 20-digit random number.</p><p>· Transfer the JSON file, which shares the same random number as its name, from within the zipped folder to an external location for editing.</p><p>· Open the JSON file in VS code editor.</p><p>· Find “dataSets” in that JSON, there you can see site URL and “tableName” of tenant XXXXX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*5ZwNclhUSSlcS4Y-gGCKIQ.png" /></figure><p>· Now replace the site URL and tableName with tenant YYYYY site URL and tableName.</p><p>{</p><p>Note: If you don’t know the tableName or List-ID in tenant YYYYY follow the steps.</p><p>I. Go to the List settings of ‘Time Sheets’ in tenant YYYYY and find the URL of that page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*-oFc6YV8ls81e38qCVl3qg.png" /></figure><p>II. The text between “List=%7B” and “%7D” is the required List-ID and tableName.</p><p>}</p><p>· Find “embeddedApp” in that JSON, there you can see “siteID”, “listID” and “listUrl” of tenant XXXXX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*3CjnU1drHFZQOHO90IJnEA.png" /></figure><p>· Now replace “siteID”, “listID” and “listUrl” of tenant XXXXX with “siteID”, “listID” and “listUrl” of tenant YYYYY, save the file and close it.</p><p>· Put back the JSON file in its original position i.e. in Zip folder .</p><p>· Now the Zip folder is ready to import.</p><p><strong>Step 3: Import the Modified Zip folder.</strong></p><p>· Go to the PowerApps page in tenant YYYYY.</p><p>· Click on “Import canvas app”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*t0u8nv5bJOYUJpZCQXDNPw.png" /></figure><p>· Upload the Zip folder and wait till uploads.</p><p>· Change the “IMPORT SETUP” to ’Create as new’ and confirm the ‘Resource name’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*ibh0a8ZCKR4wq--ULrm4zg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*-NQzqfXDxUS8-_4NAF3Unw.png" /></figure><p>· Click On “Import”.</p><p>· Now check in SharePoint List it will be Updated with PowerApps form open the PowerApps by clicking on link the shown in image, refresh the data source and publish it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*ehSQgylNk1g9B5BzrXX8JA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bf674d312b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>