<?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 Kajal Ghosh on Medium]]></title>
        <description><![CDATA[Stories by Kajal Ghosh on Medium]]></description>
        <link>https://medium.com/@kkgcom?source=rss-a65def60db88------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RZ75aVkHSS8obQSx</url>
            <title>Stories by Kajal Ghosh on Medium</title>
            <link>https://medium.com/@kkgcom?source=rss-a65def60db88------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:05:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kkgcom/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[Store and display batch job status history records for more than the default 7 days storage from…]]></title>
            <link>https://kkgcom.medium.com/store-and-display-batch-job-status-history-records-for-more-than-the-default-7-days-storage-from-4a19828e75a7?source=rss-a65def60db88------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a19828e75a7</guid>
            <category><![CDATA[lwc]]></category>
            <category><![CDATA[pagination-with-2k-limit]]></category>
            <category><![CDATA[scheduled-jobs]]></category>
            <category><![CDATA[sheetjs]]></category>
            <category><![CDATA[asyncapexjob]]></category>
            <dc:creator><![CDATA[Kajal Ghosh]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 12:22:41 GMT</pubDate>
            <atom:updated>2026-04-28T12:22:41.202Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Store and display batch job status history records for more than the default 7 days storage from salesforce generic object:</strong> <strong>AsyncApexJob using LWC</strong></h3><p>Salesforce has limitation of storing the history of all the background jobs status for 7 days only, so if you need to display a report for project or security reasons, you can’t view the older data. Hence this solution was implemented to store all the daily batch job records from AsyncApexJob (which is a generic object of salesforce to store all the information of all the apex asynchronous batch jobs for 7 days only) and store it in a custom object created to store them. Then we have created a LWC to view those old records based on date filters and exporting them to excel file with pagination option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*jKSRYz3qMnuQK3sq3rcNDA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*AIZDAAQV7OwSyF8M8ucvAQ.jpeg" /></figure><p>First step is to create a <strong>custom object: Async_Job_Record__c to store daily the records from AsyncApexJob </strong>standard object of salesforce to store all the information of all the jobs.</p><p>Next add sheetjs library to our org:</p><p>Exporting Salesforce data into Excel has never been easier! Whether you’re working with large volumes of lead data or just need a quick export feature, combining <a href="https://hicglobalsolutions.com/blog/lightning-web-components-a-quick-tutorial/">Lightning Web Components</a> (LWC) with SheetJS gives you a powerful and seamless solution.</p><p>step-by-step guide:</p><ul><li>Create an Apex Class to fetch data</li><li>Add the SheetJS Library in Salesforce</li><li>Create a LWC Component to Export Data</li><li>Test the Excel sheet generation</li></ul><p>Sheet JS Library Method Usage</p><ul><li>json_to_sheet — This will convert the lead data to a worksheet</li><li>book_new — It will create a new workbook</li><li>book_append_sheet — It will append the sheet to the workbook</li><li>writeFile — It will generate an Excel file with the workbook.</li></ul><p>· Step: Add the SheetJS Library in Salesforce.</p><p>· The SheetJs library can be downloaded from the GitHub repository. However, we need a pro version to style records in an Excel sheet. The pro version will also support implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*VBs1-BvLhi4STlcIcaS7og.jpeg" /></figure><p><strong>LWC: BatchJobStatus</strong></p><p><strong>HTML part: BatchJobStatus.html</strong></p><pre>&lt;template&gt;<br>    &lt;lightning-card title=&quot;Batch Job Status Records&quot;&gt;<br>        &lt;div class=&quot;slds-m-around_medium&quot;&gt;<br>            &lt;div class=&quot;slds-grid slds-wrap slds-gutters&quot;&gt;<br>                <br>                &lt;div class=&quot;slds-col slds-size_1-of-4&quot;&gt;<br>                    &lt;lightning-input <br>                        type=&quot;date&quot; <br>                        label=&quot;Start Date&quot; <br>                        onchange={handleStartDateChange}&gt;<br>                    &lt;/lightning-input&gt;<br>                &lt;/div&gt;<br><br>                &lt;div class=&quot;slds-col slds-size_1-of-4&quot;&gt;<br>                    &lt;lightning-input <br>                        type=&quot;date&quot; <br>                        label=&quot;End Date&quot; <br>                        onchange={handleEndDateChange}&gt;<br>                    &lt;/lightning-input&gt;<br>                &lt;/div&gt;<br><br>                &lt;div class=&quot;slds-col slds-size_1-of-4&quot;&gt;<br>                    &lt;lightning-combobox<br>                        name=&quot;fieldSelect&quot;<br>                        label=&quot;Select Apex Class&quot;<br>                        value={selectedValue}<br>                        placeholder=&quot;Select an Apex Class&quot;<br>                        options={dropdownOptions}<br>                        onchange={handleChange}&gt;<br>                    &lt;/lightning-combobox&gt;<br>                &lt;/div&gt;<br><br>                &lt;div class=&quot;slds-col slds-size_1-of-4 slds-align-bottom&quot;&gt;<br>                    &lt;lightning-button <br>                        label=&quot;Apply Filter&quot; <br>                        onclick={applyFilter}&gt;<br>                    &lt;/lightning-button&gt;<br>                &lt;/div&gt;<br><br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;slds-m-around_medium&quot;&gt;           <br>            &lt;div class=&quot;slds-m-top_medium&quot;&gt;<br>                &lt;template if:true={batchjobStatusData}&gt;<br>                    &lt;lightning-datatable<br>                        key-field=&quot;Id&quot;<br>                        data={batchjobStatusData}<br>                        columns={columns}<br>                        hide-checkbox-column=&quot;true&quot;<br>                    &gt;&lt;/lightning-datatable&gt;<br>                    &lt;div class=&quot;slds-m-top_medium slds-align_absolute-center&quot;&gt;<br>                        &lt;span class=&quot;slds-m-horizontal_small&quot;&gt;Page {currentPage} of {totalPages}&lt;/span&gt;<br>                        &lt;lightning-button label=&quot;Next&quot;<br>                                        icon-name=&quot;utility:chevronright&quot;<br>                                        icon-position=&quot;right&quot;<br>                                        onclick={handleNext}<br>                                        disabled={isLastPage}&gt;<br>                        &lt;/lightning-button&gt;<br>                    &lt;/div&gt;<br>                    &lt;div&gt;<br>                        &lt;lightning-button variant=&quot;brand&quot; label=&quot;Export XLSX data&quot; title=&quot;Export XLSX Data&quot; onclick={handleExport}&gt;&lt;/lightning-button&gt;<br>                    &lt;/div&gt;<br>                &lt;/template&gt;<br>                &lt;template if:true={error}&gt;<br>                    &lt;p class=&quot;slds-text-color_error&quot;&gt;{error}&lt;/p&gt;<br>                &lt;/template&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/lightning-card&gt;<br>&lt;/template&gt;</pre><p><strong>.js file:</strong></p><pre>import { LightningElement, wire, api, track } from &#39;lwc&#39;;<br>import getDistinctFieldValues from &#39;@salesforce/apex/BatchJobStatus.getDistinctFieldValues&#39;;<br>import getAsyncJobs from &#39;@salesforce/apex/BatchJobStatus.getAsyncJobs&#39;;<br>import getTotalAsyncJobsCount from &#39;@salesforce/apex/BatchJobStatus.getTotalAsyncJobsCount&#39;;<br>import SHEETJS from &#39;@salesforce/resourceUrl/SheetJs&#39;;<br>import { loadScript } from &#39;lightning/platformResourceLoader&#39;;<br><br>export default class BatchJobStatus extends LightningElement {<br><br>    @track startDate;<br>        @track endDate;<br>        @track records;<br>        @track error;<br>        @api deploymentId; <br>        @track batchjobStatusData = [];<br><br>        @track currentPage = 1;<br>        @track pageSize = 100; // Fetch 100 records per page<br>        @track totalRecords = 0;<br>        @track totalPages = 0;<br><br>        lastRecordId = null;<br>        // Boolean flag to check if there are more records available to load<br>        hasMoreRecords = true;<br><br>        @track allRecords = []; // Accumulated records from all pages<br><br>        sheetJsInitialized = false;<br><br>        // Define columns for lightning-datatable (adjust based on your object&#39;s fields)<br>        columns = [    <br>            { label: &#39;Id&#39;, fieldName: &#39;Id&#39;, type: &#39;Id&#39; },        <br>            { label: &#39;Submitted Date&#39;, fieldName: &#39;CreatedDate&#39;, type: &#39;date&#39; },<br>            { label: &#39;Job Type&#39;, fieldName: &#39;JobType&#39;, type: &#39;text&#39; },<br>            { label: &#39;Status&#39;, fieldName: &#39;Status&#39;, type: &#39;text&#39; },<br>            { label: &#39;Total Batches&#39;, fieldName: &#39;TotalJobItems&#39;, type: &#39;text&#39; },<br>            { label: &#39;Batches Processed&#39;, fieldName: &#39;JobItemsProcessed&#39;, type: &#39;text&#39; },<br>            { label: &#39;Failures&#39;, fieldName: &#39;NumberOfErrors&#39;, type: &#39;text&#39; },<br>            { label: &#39;Completed Date&#39;, fieldName: &#39;CompletedDate&#39;, type: &#39;date&#39; },<br>            { label: &#39;Submitted By&#39;, fieldName: &#39;CreatedBy&#39;, type: &#39;text&#39; },            <br>            { label: &#39;FileName&#39;, fieldName: &#39;FileName&#39;, type: &#39;text&#39; },<br>            { label: &#39;Apex Job Id&#39;, fieldName: &#39;ApexJobId&#39;, type: &#39;text&#39; }<br>        ];<br>    columnHeader = [&#39;Submitted Date&#39;, &#39;Job Type&#39;, &#39;Status&#39;, &#39;Total Batches&#39;,&#39;Batches Processed&#39;, &#39;Failures&#39;, &#39;Completed Date&#39;, &#39;Submitted By&#39;, &#39;FileName&#39;,&#39;Apex Job Id&#39;]<br><br>    dropdownOptions = [];<br>    selectedValue = &#39;&#39;;<br><br>    @wire(getDistinctFieldValues)<br>    wiredOptions({ error, data }) {<br>        if (data) {<br>            this.dropdownOptions = data;<br>        } else if (error) {<br>            console.error(&#39;Error retrieving distinct values:&#39;, error);<br>        }<br>    }<br><br>    handleChange(event) {<br>        this.selectedValue = event.detail.value;<br>        console.log(&#39;Selected Value:&#39;, this.selectedValue);<br>    }<br>        handleStartDateChange(event) {<br>            this.startDate = event.target.value;<br>        }<br>    <br>        handleEndDateChange(event) {<br>            this.endDate = event.target.value;<br>        }<br>    <br>        applyFilter() {       <br>            this.lastRecordId = null; <br>            this.allRecords = [];  <br>            this.fetchTotalRecords();<br>            <br>        }<br>    <br>        connectedCallback() {<br>            if (!this.sheetJsInitialized) {<br>                loadScript(this, SHEETJS)<br>                    .then(() =&gt; {<br>                        this.sheetJsInitialized = true;<br>                        console.log(&#39;SheetJS loaded&#39;);<br>                    })<br>                    .catch((error) =&gt; {<br>                        console.error(&#39;Error loading SheetJS&#39;, error);<br>                    });<br>            }<br>            this.fetchTotalRecords();<br>           <br>        }<br>    <br>    fetchTotalRecords() {<br>        this.currentPage = 1;<br>        getTotalAsyncJobsCount({ <br>                startDate: this.startDate,<br>                endDate: this.endDate,<br>                selectedValue: this.selectedValue})<br>            .then(result =&gt; {<br>                this.totalRecords = result;<br>                this.totalPages = Math.ceil(this.totalRecords / this.pageSize);<br>                this.fetchRecords();<br>            })<br>            .catch(error =&gt; {<br>                console.error(&#39;Error fetching total records:&#39;, error);<br>            });<br>    }<br><br>    fetchRecords() {<br>        <br>        console.log(&#39;Selected record id:&#39;, this.lastRecordId);<br>        getAsyncJobs({ <br>                startDate: this.startDate,<br>                endDate: this.endDate,<br>                selectedValue: this.selectedValue,<br>                pageSize: this.pageSize, <br>                lastRecordId: this.lastRecordId })<br>            .then(result =&gt; {<br>                if (result &amp;&amp; result.length &gt; 0) {<br>                <br>                this.batchjobStatusData = result.map(item =&gt; ({<br>                    ...item,<br>                    StartDate: item.StartDate<br>                }));<br>                this.error = undefined;<br>                 // Accumulate data: This adds the current page&#39;s data to the allRecords array.<br>                // You might want to clear and rebuild allRecords if navigating back and forth<br>                // or if the data can change on the server.<br>                <br>                if(this.allRecords.length === 0){<br>                    this.allRecords = [...result]; <br>                }<br>                else{<br>                    <br>                    this.allRecords = [...this.allRecords, ...result]; <br>                }<br><br>                // Track last record Id for next page<br>                this.lastRecordId = result[result.length - 1].Id;<br>                if (result.length === this.totalRecords) {<br>                    this.hasMoreRecords = false;<br>                } else {<br>                    this.hasMoreRecords = true;<br>                }<br>               <br>            }<br>            else{<br>                this.batchjobStatusData = [];<br>                this.lastRecordId = null;<br>            }            <br>            })<br>            .catch(error =&gt; {<br>                <br>                this.error = error.body.message;<br>                this.records = undefined;<br>            });<br>    }<br><br>    handlePrevious() {<br>        if (this.currentPage &gt; 1) {<br>            this.currentPage--;<br>            this.fetchRecords();<br>        }<br>    }<br><br>    handleNext() {<br>        console.log(&#39;current pages&#39;+ this.currentPage);<br>        console.log(&#39;total pages&#39;+ this.totalPages);<br>        if (this.currentPage &lt; this.totalPages) {<br>            this.currentPage++;<br>            this.fetchRecords();<br>        }<br>    }<br><br>    get isFirstPage() {<br>        return this.currentPage === 1;<br>    }<br><br>    get isLastPage() {<br>        return this.currentPage === this.totalPages;<br>    }<br><br>    exportContactData(){<br>        // Prepare a html table<br>        let doc = &#39;&lt;table&gt;&#39;;<br>        // Add styles for the table<br>        doc += &#39;&lt;style&gt;&#39;;<br>        doc += &#39;table, th, td {&#39;;<br>        doc += &#39;    border: 1px solid black;&#39;;<br>        doc += &#39;    border-collapse: collapse;&#39;;<br>        doc += &#39;}&#39;;          <br>        doc += &#39;&lt;/style&gt;&#39;;<br>        // Add all the Table Headers<br>        doc += &#39;&lt;tr&gt;&#39;;<br>        this.columnHeader.forEach(element =&gt; {            <br>            doc += &#39;&lt;th&gt;&#39;+ element +&#39;&lt;/th&gt;&#39;           <br>        });<br>        doc += &#39;&lt;/tr&gt;&#39;;<br>        // Add the data rows<br>        this.batchjobStatusData.forEach(record =&gt; {<br>            doc += &#39;&lt;tr&gt;&#39;;<br>            doc += &#39;&lt;th&gt;&#39;+record.Id+&#39;&lt;/th&gt;&#39;; <br>            doc += &#39;&lt;th&gt;&#39;+record.CreatedDate+&#39;&lt;/th&gt;&#39;; <br>            doc += &#39;&lt;th&gt;&#39;+record.JobType+&#39;&lt;/th&gt;&#39;; <br>            doc += &#39;&lt;th&gt;&#39;+record.Status+&#39;&lt;/th&gt;&#39;;<br>            doc += &#39;&lt;th&gt;&#39;+record.TotalJobItems+&#39;&lt;/th&gt;&#39;; <br>            doc += &#39;&lt;th&gt;&#39;+record.JobItemsProcessed+&#39;&lt;/th&gt;&#39;; <br>            doc += &#39;&lt;th&gt;&#39;+record.NumberOfErrors+&#39;&lt;/th&gt;&#39;; <br>            doc += &#39;&lt;th&gt;&#39;+record.CompletedDate+&#39;&lt;/th&gt;&#39;;<br>            doc += &#39;&lt;th&gt;&#39;+record.CreatedBy+&#39;&lt;/th&gt;&#39;;<br>            doc += &#39;&lt;th&gt;&#39;+record.FileName+&#39;&lt;/th&gt;&#39;;<br>            doc += &#39;&lt;th&gt;&#39;+record.ApexJobId+&#39;&lt;/th&gt;&#39;; <br>            doc += &#39;&lt;/tr&gt;&#39;;<br>        });<br>        doc += &#39;&lt;/table&gt;&#39;;<br>        var element = &#39;data:application/vnd.ms-excel,&#39; + encodeURIComponent(doc);<br>        let downloadElement = document.createElement(&#39;a&#39;);<br>        downloadElement.href = element;<br>        downloadElement.target = &#39;_self&#39;;<br>        // use .csv as extension on below line if you want to export data as csv<br>        downloadElement.download = &#39;Apex Job Data.xls&#39;;<br>        document.body.appendChild(downloadElement);<br>        downloadElement.click();<br>    }<br><br>    handleExport() {<br>        const worksheetData = [];<br>        console.log(&#39;Method called&#39;);<br>        <br>        if (!this.sheetJsInitialized) {<br>            console.warn(&#39;SheetJS library not loaded yet&#39;);<br>            return;<br>        }<br><br>        if (!this.allRecords || this.allRecords.length === 0) {<br>            console.warn(&#39;No data available to export&#39;);<br>            return;<br>        }<br><br>        for (const record of this.allRecords) {<br>            worksheetData.push({<br>                &quot;Id&quot;: record.Id,<br>                &quot;Submitted Date&quot;: record.CreatedDate,<br>                &quot;Job Type&quot;: record.JobType,<br>                &quot;Status&quot;:record.Status,<br>                &quot;Total Batches&quot;: record.TotalJobItems,<br>                &quot;Batches Processed&quot;: record.JobItemsProcessed,<br>                &quot;Failures&quot;:record.NumberOfErrors,<br>                &quot;Completed Date&quot;: record.CompletedDate,<br>                &quot;Submitted By&quot;: record.CreatedBy,<br>                &quot;File Name&quot;:record.FileName,<br>                &quot;Apex Job Id&quot;:record.ApexJobId            <br>            });<br>        }<br><br>        const data = JSON.parse(JSON.stringify(worksheetData));<br>        console.log(&#39;Data to export:&#39;, data);<br>        <br>        const ws = XLSX.utils.json_to_sheet(data);<br>        console.log(&#39;Worksheet created:&#39;, ws);<br>       <br>        const wb = XLSX.utils.book_new();<br>        XLSX.utils.book_append_sheet(wb, ws, &#39;Apex Batch Jobs&#39;);<br>        <br>        XLSX.writeFile(wb, &#39;BatchJobExport.xlsx&#39;);<br>    }<br><br>        /**<br>     * allLoaded getter checks if all records have been loaded.<br>     * @return {boolean} – True if all records are loaded, false otherwise.<br>     */<br>    get allLoaded() {<br>        // Returns true if there are no more records to load and at least one record is present<br>        return !this.hasMoreRecords &amp;&amp; this.allRecords.length &gt; 0;<br>    }<br>}</pre><p><strong>Apex class:</strong></p><p><strong>processAsyncJobBatch</strong>: Schedule class to store the daily asynchronous apex job status to a stagging <strong>custom object: Async_Job_Record__c, created</strong> for this implementation.</p><pre>public class processAsyncJobBatch implements Schedulable{<br><br>   public void execute(SchedulableContext SC) {<br>        // Query AsyncApexJob records based on job type<br>        List&lt;AsyncApexJob&gt; asyncJobs = [<br>            SELECT Id, CreatedDate,CreatedById, CreatedBy.Name, JobType, Status, JobItemsProcessed, <br>                   TotalJobItems, NumberOfErrors, CompletedDate,  ApexClassId, ApexClass.Name<br>            FROM AsyncApexJob <br>WHERE JobType IN (&#39;BatchApex&#39;) // Filter relevant job types<br>            AND ApexClass.Name &lt;&gt; &#39;StProjectQueueFactoryJob&#39;<br>            AND CreatedDate = TODAY<br>            ORDER BY CreatedDate DESC<br>        ];<br>        //bulkify the code: Write Apex to handle collections of records (lists/maps) rather than processing records one by one in a loop.<br>        List&lt;Async_Job_Record__c&gt; newRecords = new List&lt;Async_Job_Record__c&gt;();<br>        for (AsyncApexJob aajs : asyncJobs) {<br>            newRecords.add(new Async_Job_Record__c(<br>                       Name=&#39;ajrs&#39; + aajs.Id,<br>                                                          Apex_Job_ID__c=aajs.Id,<br>                                                          ApexClassName__c=aajs.ApexClass.Name,<br>                                                          CompletedDateTime__c=aajs.CompletedDate,<br>                                                          CreatedUserId__c=aajs.CreatedById,<br>                                                          CreatedUserName__c=aajs.CreatedBy.Name,<br>                                                          CreatedDateTime__c=aajs.CreatedDate,<br>                                                          JobType__c=aajs.JobType,<br>                                                          Status__c=aajs.Status,<br>                                                          TotalJobItems__c=aajs.TotalJobItems,<br>                                                          JobItemsProcessed__c=aajs.JobItemsProcessed,<br>                                                          NumberOfErrors__c=aajs.NumberOfErrors));     <br>        }<br>        if (!newRecords.isEmpty()) {<br>            insert newRecords;<br>        }<br>   }<br>  <br>}<br><br>processAsyncJobBatchTest: Test class for the above scheduled apex class.<br><br>@isTest<br>public class processAsyncJobBatchTest {<br> <br>    @isTest<br>    public static void testSchedule(){                <br>        Test.startTest();<br>        User currentUser= [select id from User where id=:UserInfo.getUserId() limit 1];<br>        Contract__c contract = new Contract__c();<br>        contract.Name = ‘Text Contract’;<br>        insert contract;<br>    <br>        stdraw__Approval_Process_Template__c apt = new stdraw__Approval_Process_Template__c();<br>        apt.stdraw__Allow_Recalls__c = true;<br>        apt.stdraw__Active__c = true;<br>        apt.stdraw__Approval_Process_Template_Name__c = &#39;test template&#39;;<br>        apt.stdraw__Description__c = &#39;Test Description&#39;;<br>        apt.stdraw__Entry_Criteria__c = null;<br>        apt.stdraw__Object_API__c = &#39;sitetracker__Finance__c&#39;;<br>        apt.stdraw__Object_Name__c = &#39;Finance&#39;;<br>        insert apt;<br>    <br>    <br>        stdraw__Steps_Template__c step1 = new stdraw__Steps_Template__c();<br>        step1.stdraw__Approval_Process_Template__c = apt.Id;<br>        step1.stdraw__Approval_Type__c = &#39;First&#39;;<br>        step1.stdraw__Days_to_Review__c = 5;<br>        step1.stdraw__Days_to_Review_Type__c = &#39;Business Days&#39;;<br>        step1.stdraw__Next_Step_Template__c = null;<br>        step1.stdraw__Previous_Step_Template__c = null;<br>        step1.stdraw__Step_Template_Name__c = &#39;Step 1&#39;;<br>        step1.stdraw__Do_Not_Send_Emails__c = true;<br>        insert step1;<br>        <br>        stdraw__Approver_Template__c at1 = new stdraw__Approver_Template__c();<br>        at1.stdraw__Step_Template__c = step1.Id;<br>        at1.stdraw__User__c = UserInfo.getUserId();<br>        at1.stdraw__Object_API__c = &#39;Sitetracker__Finance__c&#39;;<br>        insert at1;<br>    <br>        <br>        sitetracker__Site__c site= new sitetracker__Site__c();<br>        site.sitetracker__Site_Type__c=&#39;SW&#39;;<br>        site.sitetracker__City__c=&#39;testCity&#39;;<br>        site.Name=&#39;testName&#39;;<br>        site.Site_Operator__c=&#39;Test&#39;;<br>        insert site;<br>        <br>        <br>        sitetracker__Project_Template__c pTemplate= new sitetracker__Project_Template__c();<br>        pTemplate.Name=&#39;testPT&#39;;<br>        pTemplate.sitetracker__Active__c=true;<br>        insert pTemplate;<br>        <br>        sitetracker__Project_Price_Book__c stprbk = new sitetracker__Project_Price_Book__c ();<br>        stprbk.Name=&#39;testPB&#39;;<br>        stprbk.sitetracker__Project_Template__c=pTemplate.ID;<br>        insert stprbk;      <br>        <br>        sitetracker__Pricebook_Item__c stprc = new sitetracker__Pricebook_Item__c ();<br>        stprc.Name=&#39;testDV&#39;;<br>        stprc.sitetracker__Project_Price_Book__c=stprbk.ID;<br>        stprc.ASP_PO_Required__c=true;<br>        stprc.SWC_PO_Required__c=true;<br>        stprc.Customer_PO_Required__c=true;<br>        stprc.deliverable_type__c = &#39;SWC&#39;;<br>        stprc.Approval_Process_Template__c = apt.Id;<br>        stprc.Contract__c = contract.Id;<br>        stprc.Multi_Contract__c = Test Contract&#39;;<br>        insert stprc;<br>  <br>       Account acc = new Account();<br>        acc.Name=&#39;ACC&#39;;<br>        insert acc;<br>  <br>  Account acc1 = new Account();<br>        acc1.Name=&#39;3rd Party&#39;;<br>        insert acc1;<br><br>        Pricing__c prc= new Pricing__c();<br>        prc.Price_Book_Item__c=stprc.Id;<br>        prc.Account__c = acc.id;<br>  prc.Contract__c = &#39;Test Contract&#39;;<br>        prc.Is_Active__c = true;<br>        insert prc;   <br>  <br>  Contract__c Con = new Contract__c();<br>  Con.name=&#39;Test Contract&#39;;<br>        <br>        MP_Code__c MPCode = new MP_Code__c();<br>        MPCode.name = &#39;MPCode 1&#39;;<br>        MPCode.Programme__c = &#39;Test Programme’;<br>        Insert MPCode;<br>        <br>        sitetracker__Project__c stProject= new sitetracker__Project__c();<br>        stProject.sitetracker__Site__c=site.Id;<br>        stProject.sitetracker__ProjectTemplate__c=pTemplate.id;<br>        stProject.account__c = acc.id;<br>  stproject.SWC_Account__c = acc1.id;<br>        stProject.Instruction_Received_A__c=Date.newInstance(2020, 09, 13);<br>        stProject.Contract__c=Con.ID;<br>        stProject.sitetracker__Project_Price_Book__c=stprbk.ID;<br>        stProject.Customer_Deliverable_Primary__c = stprc.Id;<br>        stProject.MP_Project__c =  MPCode.Id;  <br>        insert stProject;<br>     <br>        Work_Instruction__c WI = new Work_Instruction__c();<br>        WI.Cell_ID__c = site.Id;<br>        WI.Work_Instruction_Status__c=&#39;WIP&#39;;<br>        WI.Project__c=stProject.Id;<br>        insert WI;<br>    <br>        sitetracker__Purchase_Order__c PO1 = New sitetracker__Purchase_Order__c();<br>        PO1.Name = &#39;PO-01&#39;;<br>        PO1.MP_Code__c = MPCode.Id;<br>        PO1.Price_Book_Item__c = stprc.Id;<br>        PO1.PO_Status__c = &#39;Active&#39;;<br>        PO1.Contract__c = Con.Id;<br>        PO1.Quantity__c = 10;<br>        Insert PO1;<br>    <br>        sitetracker__Finance__c fin= new sitetracker__Finance__c();<br>        fin.sitetracker__Project_Link__c=stProject.Id;<br>        fin.sitetracker__Pricebook_Item__c=stprc.Id;<br>        fin.Site__c = site.Id;<br>        fin.Customer_Purchase_Order__c = PO1.Id; <br>        insert fin;<br>    <br>        sitetracker__Finance__c finItem = [select id,Approval_Process__c from sitetracker__Finance__c where id =:fin.Id];<br>        system.debug(&#39;Approval Process: &#39;+finItem.Approval_Process__c);<br>        <br>        list&lt;Id&gt; approvalProcessIds = new list&lt;id&gt;();<br>    <br>        stdraw__Steps__c step = new stdraw__Steps__c();<br>        step.stdraw__Approval_Process__c=finItem.Approval_Process__c;<br>        step.stdraw__Approval_Type__c = &#39;First&#39;;<br>        step.stdraw__Step_Template__c = step1.Id;<br>        step.stdraw__Step_Name__c = &#39;Step-001&#39;;<br>        insert Step;<br>        <br>        stdraw__Approver__c approver = new stdraw__Approver__c();<br>        approver.stdraw__Approver_Template__c = at1.Id;<br>        approver.stdraw__User__c = currentUser.Id;<br>        approver.stdraw__Status__c = &#39;Pending&#39; ;<br>        approver.stdraw__Step__c  = step.Id;  <br>        approver.stdraw__Object_API__c = &#39;sitetracker__Finance__c&#39;;<br>        insert approver;<br><br>        Set&lt;Id&gt; currentFailedApprovalRecordIds = new Set&lt;Id&gt;();<br>        Failed_Approval_Batch__c currentFailedApprovalBatch = new Failed_Approval_Batch__c();<br>            currentFailedApprovalBatch.Name = UserInfo.getName() + &#39; - &#39; + Datetime.now().format(&#39;yyyy-MM-dd HH:mm:ss&#39;);<br>            currentFailedApprovalBatch.Original_User_Email__c = UserInfo.getUserEmail();<br>            currentFailedApprovalBatch.Approval_Comment__c = &#39;&#39;;<br>   Map&lt;Id, String&gt;m_approverIdErrorMessage = new Map&lt;Id, String&gt;();<br>         m_approverIdErrorMessage.put(approver.Id, &#39;Test failure&#39;);<br>            for(Id approverId : m_approverIdErrorMessage.keySet()) {<br>                currentFailedApprovalRecordIds.add(approverId);<br>            }<br>            currentFailedApprovalBatch.Record_IDs__c = String.join(new List&lt;Id&gt;(currentFailedApprovalRecordIds), &#39;,&#39;);<br>  insert currentFailedApprovalBatch;<br>         <br>        Set&lt;Id&gt; approvalsToRetry = new Set&lt;Id&gt;();<br><br>            for(String failedApproval : currentFailedApprovalBatch.Record_IDs__c.split(&#39;,&#39;)){<br>                approvalsToRetry.add((Id)failedApproval);<br>            }<br>       <br>        MassApproversBatchV2 myBatchObject = new MassApproversBatchV2(approvalsToRetry, currentFailedApprovalBatch); <br>        Id batchId = Database.executeBatch(myBatchObject);<br>        <br>        processAsyncJobBatch sh1 = new processAsyncJobBatch();<br>        String sch = &#39;0 0 2 * * ?&#39;; <br>        String jobId = system.schedule(&#39;Test Asyncjob Check&#39;, sch, sh1); <br>         // 3. Verify the job is scheduled<br>        CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE Id = :jobId];<br>        System.assertEquals(sch, ct.CronExpression);<br>        <br>        Test.stopTest();<br>              <br>         // Query your custom object to verify the inserted records<br>        List&lt;Async_Job_Record__c&gt; customRecords = [SELECT Id, Name, Apex_Job_ID__c, Status__c FROM Async_Job_Record__c];<br>    <br>        // Assertions to verify the custom object records<br>        System.assertNotEquals(0, customRecords.size(), &#39;No custom records were created by the scheduled job.&#39;);<br>        <br>    }<br>   <br>}</pre><p>Schedule the above schedulable apex class daily as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*xrLzISSrjsbVC4OSrqZ2tg.jpeg" /></figure><p><strong>BatchJobStatus</strong>: Apex class with aura methods which will be called from LWC component to display the data based on filters. export data using xlsx and pagination with Salesforce SOQL limit and offset clauses.</p><p>Have you ever tried implementing server-side pagination using Apex with Salesforce SOQL limit and offset clauses? If yes, then you might already know that Salesforce SOQL doesn’t support offset values more than 2000. That means you can’t load more than 2000 records even if they are spread across multiple pages.</p><p>When building modern Salesforce Lightning Web Components (LWCs), one essential UX feature is <strong>lazy loading</strong> (or infinite scrolling). It helps load data incrementally as users scroll — improving performance, reducing query load, and creating a smooth user experience.</p><p>A common first attempt at building pagination in Salesforce looks something like this:</p><p>SELECT Id, Name, Email FROM Contact LIMIT 50 OFFSET 100</p><p>At first glance, it seems perfect — you simply skip the first 100 records and fetch the next 50 for your next page or scroll.</p><p>However, <strong>this approach quickly runs into serious performance and scalability issues</strong> when used in Lightning Web Components (LWC) or any large dataset scenario.</p><p><strong>Offset Limitations</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*fsPfQ9YKSB697DiIilB58g.jpeg" /></figure><p>In short — <strong>OFFSET pagination breaks for large datasets</strong> and hurts performance even before that.</p><p>Instead of relying on “skip and fetch,” we can use <strong>keyset pagination</strong>, also known as <strong>cursor-based pagination</strong>.<br> <br> “Fetch the next N records where Id (or another key) is greater than the last record we already loaded.”<br> <br> This approach uses <strong>indexed, unique fields</strong> which is <strong>Id</strong> field. This ensures consistent, fast, scalable queries. There is <strong>no OFFSET limit</strong>.</p><p>The key part of the solution is to pass the Id of the last or the first record from the current page based on whether we are trying to load the next or the previous page of records. Once we have the Id of the record for an already loaded page, page size and direction, we can use SOQL with filters on the Id field, limit and order by clauses to load the next set of records.</p><p>For the first load, lastRecordId is null → fetches the first batch.<br> On scroll, we pass the last record’s Id → fetches the next batch.</p><p>First of all, we find the total number of records for the specified object in the system. We can do that using the following method:</p><p><strong>Calculate the total pages based on the total records and the page size</strong></p><p>Next, we calculate the total number of pages based on the total number of records and the specified page size. We can use the following formula to calculate that:</p><p>Integer totalPages = (Integer) Math.ceil((Decimal) totalRecords / pageSize);</p><pre>public with sharing class BatchJobStatus {<br>    @AuraEnabled(cacheable=true)<br>    public static List&lt;Map&lt;String, String&gt;&gt; getDistinctFieldValues() {<br>        List&lt;Map&lt;String, String&gt;&gt; options = new List&lt;Map&lt;String, String&gt;&gt;();<br>        Set&lt;String&gt; distinctValues = new Set&lt;String&gt;(); // Use a Set to ensure uniqueness<br>List&lt;Async_Job_Record__c&gt; asyncBatchJobs = Database.query(&#39;SELECT ApexClassName__c FROM Async_Job_Record__c&#39;);<br><br>        for (Async_Job_Record__c aajs : asyncBatchJobs) {<br>            if (aajs.ApexClassName__c != null) { // Add null check for robustness<br>                distinctValues.add(aajs.ApexClassName__c);<br>            }<br>        }<br><br>        // Convert the Set to a List of Maps for LWC consumption<br>        options.add(new Map&lt;String, String&gt;{&#39;label&#39; =&gt; &#39;None&#39;, &#39;value&#39; =&gt; null});<br>        for (String value : distinctValues) {<br>            options.add(new Map&lt;String, String&gt;{&#39;label&#39; =&gt; value, &#39;value&#39; =&gt; value});<br>        }<br>        return options;<br>    }<br>       <br>    // Inner class to represent batchJobStatus structure for easier handling<br>    public class batchJobStatus {<br>        @AuraEnabled public Id Id;<br>        @AuraEnabled public String Status;<br>        @AuraEnabled public DateTime CreatedDate;<br>        @AuraEnabled public DateTime CompletedDate;<br>        @AuraEnabled public String CreatedBy;<br>        @AuraEnabled public String JobType;<br>        @AuraEnabled public String FileName;<br>        @AuraEnabled public Decimal JobItemsProcessed; <br>        @AuraEnabled public Decimal TotalJobItems;<br>        @AuraEnabled public Decimal NumberOfErrors;<br>        @AuraEnabled public String ApexJobId;<br>    }<br>    <br>    @AuraEnabled(cacheable=true)<br>    public static List&lt;batchJobStatus&gt; getAsyncJobs(DateTime startDate, DateTime endDate, String selectedValue, Integer pageSize, Id lastRecordId) {<br>                <br>        // 1. Prepare the fixed string values<br>        List&lt;String&gt; statusValues = new List&lt;String&gt;{&#39;ScheduledApex&#39;, &#39;BatchApex&#39;, &#39;Future&#39;, &#39;Queueable&#39;};<br>        <br>        // 2. Format the string values for the IN clause<br>        List&lt;String&gt; quotedStatusValues = new List&lt;String&gt;();<br>        for (String s : statusValues) {<br>            quotedStatusValues.add(&#39;\&#39;&#39; + String.escapeSingleQuotes(s) + &#39;\&#39;&#39;);<br>        }<br>        String inClauseValues = String.join(quotedStatusValues, &#39;,&#39;);<br>  <br>        String query = &#39;SELECT Id, CreatedDateTime__c, CreatedUserId__c, CreatedUserName__c, JobType__c, Status__c, JobItemsProcessed__c, &#39;+<br>                   &#39;TotalJobItems__c, NumberOfErrors__c, CompletedDateTime__c,  Apex_Job_ID__c, ApexClassName__c &#39;+<br>              &#39;FROM Async_Job_Record__c &#39;+<br>           &#39;WHERE JobType__c IN (&#39; + inClauseValues + &#39;)&#39;;<br>        List&lt;String&gt; conditions = new List&lt;String&gt;();<br><br>        if (startDate != null) {<br>            query += &#39; AND CreatedDateTime__c &gt;= &#39; + startDate.formatGMT(&#39;yyyy-MM-dd\&#39;T\&#39;HH:mm:ss\&#39;Z\&#39;&#39;);<br>        }<br>        if (endDate != null) {<br>   Date datePart = endDate.date();<br><br>            // 2. Create a new Time instance for 11:59:59 PM<br>            // Note: Milliseconds are typically 0 when setting to the end of the second.<br>            Time endOfDayTime = Time.newInstance(23, 59, 59, 0); <br>    <br>            // 3. Combine Date and Time to create the new DateTime<br>            DateTime endOfDayDateTime = DateTime.newInstance(datePart, endOfDayTime);<br><br>            query += &#39; AND CreatedDateTime__c &lt;= &#39; + endOfDayDateTime.formatGMT(&#39;yyyy-MM-dd\&#39;T\&#39;HH:mm:ss\&#39;Z\&#39;&#39;);<br>        }<br>        <br>        if (String.isNotBlank(selectedValue)) {<br>            query += &#39; AND ApexClassName__c = \&#39;&#39; + selectedValue + &#39;\&#39;&#39;;<br>        }<br>        if (lastRecordId != null) {<br>            query += &#39; AND Id &lt; :lastRecordId&#39;;<br>        }<br>        query += &#39; ORDER BY Id DESC LIMIT &#39; + pageSize; // Add a limit for performance<br>        List&lt;batchJobStatus&gt; batchJobStats = new List&lt;batchJobStatus&gt;();<br>         // Query AsyncApexJob records based on job type<br>        List&lt;Async_Job_Record__c&gt; asyncBatchJobs = Database.query(query);<br>        for (Async_Job_Record__c aajs : asyncBatchJobs) {<br>            batchJobStatus bjs = new batchJobStatus();<br>            bjs.Id= aajs.Id;<br>            bjs.JobType= aajs.JobType__c;<br>            bjs.Status= aajs.status__c;            <br>            bjs.CreatedDate= aajs.CreatedDateTime__c;<br>            bjs.CreatedBy= aajs.CreatedUserName__c;<br>            bjs.CompletedDate= aajs.CompletedDateTime__c;<br>            bjs.JobItemsProcessed= aajs.JobItemsProcessed__c;<br>            bjs.TotalJobItems= aajs.TotalJobItems__c;<br>            bjs.NumberOfErrors= aajs.NumberOfErrors__c;<br>            bjs.FileName= aajs.ApexClassName__c; <br>            bjs.ApexJobId= aajs.Apex_Job_ID__c;<br>            batchJobStats.add(bjs);<br>        }<br>        return batchJobStats;<br>    }<br><br>    @AuraEnabled(cacheable=true)<br>    public static Integer getTotalAsyncJobsCount(DateTime startDate, DateTime endDate, String selectedValue) {<br>        // Add error handling and security checks as needed<br>        List&lt;String&gt; statusValues = new List&lt;String&gt;{&#39;ScheduledApex&#39;, &#39;BatchApex&#39;, &#39;Future&#39;, &#39;Queueable&#39;};<br><br>        // 2. Format the string values for the IN clause<br>        List&lt;String&gt; quotedStatusValues = new List&lt;String&gt;();<br>        for (String s : statusValues) {<br>            quotedStatusValues.add(&#39;\&#39;&#39; + String.escapeSingleQuotes(s) + &#39;\&#39;&#39;);<br>        }<br>        String inClauseValues = String.join(quotedStatusValues, &#39;,&#39;);<br>        String query = &#39;SELECT COUNT() &#39;+<br>              &#39;FROM Async_Job_Record__c &#39;+<br>           &#39;WHERE JobType__c IN (&#39; + inClauseValues + &#39;)&#39;;<br>        List&lt;String&gt; conditions = new List&lt;String&gt;();<br>        if (startDate != null) {<br>            query += &#39; AND CreatedDateTime__c &gt;= &#39; + startDate.formatGMT(&#39;yyyy-MM-dd\&#39;T\&#39;HH:mm:ss\&#39;Z\&#39;&#39;);<br>        }<br>        if (endDate != null) {<br>   Date datePart = endDate.date();<br><br>            // 2. Create a new Time instance for 11:59:59 PM<br>            // Note: Milliseconds are typically 0 when setting to the end of the second.<br>            Time endOfDayTime = Time.newInstance(23, 59, 59, 0); <br>    <br>            // 3. Combine Date and Time to create new DateTime<br>            DateTime endOfDayDateTime = DateTime.newInstance(datePart, endOfDayTime);<br><br>            query += &#39; AND CreatedDateTime__c &lt;= &#39; + endOfDayDateTime.formatGMT(&#39;yyyy-MM-dd\&#39;T\&#39;HH:mm:ss\&#39;Z\&#39;&#39;);<br>        }<br>        <br>        if (String.isNotBlank(selectedValue)) {<br>            query += &#39; AND ApexClassName__c = \&#39;&#39; + selectedValue + &#39;\&#39;&#39;;<br>        }<br>        <br>        Integer totalRecordCount = Database.countQuery(query);<br>        return totalRecordCount; <br>    }<br>}<br><br>Test class:<br>@isTest<br>public class BatchJobStatusTest {<br>   @isTest(SeeAllData=true)<br>        static void testGetAsyncApexJobs() {<br>            // No need to create AsyncApexJob records directly in tests<br>            // as they are system-generated.<br>            // However, you can create a scheduled job to ensure there&#39;s data.<br>            System.schedule(&#39;Test Scheduled Job&#39;, &#39;0 0 0 1 1 ? 2050&#39;, new TestSchedulableClass());<br>   Date stDate = Date.newInstance(2025, 1, 1);           <br>            Date endDate = Date.newInstance(2025, 12, 11);<br>            String selectedValue = &#39;&#39;;<br>            Set&lt;String&gt; distinctValues = new Set&lt;String&gt;(); // Use a Set to ensure uniqueness<br>            List&lt;Async_Job_Record__c&gt; asyncBatchJobClasses = Database.query(&#39;SELECT ApexClassName__c FROM Async_Job_Record__c&#39;);<br>            <br>            for (Async_Job_Record__c aajs : asyncBatchJobClasses) {<br>                if (aajs.ApexClassName__c != null) { // Add null check for robustness<br>                    distinctValues.add(aajs.ApexClassName__c);<br>                }<br>            }<br>            // Convert the Set to a List<br>   List&lt;String&gt; myStringList = new List&lt;String&gt;(distinctValues);<br>            selectedValue = myStringList[0];<br>            Integer pageSize = BatchJobStatus.getTotalAsyncJobsCount(stDate,endDate,selectedValue);<br>            Integer offset = 0 ;<br>            Test.startTest();<br>            Id lastRecord;<br>            <br>            List&lt;BatchJobStatus.batchJobStatus&gt; jobs = BatchJobStatus.getAsyncJobs(stDate,endDate,selectedValue,pageSize, lastRecord);            <br>            Test.stopTest();<br><br>            System.assertNotEquals(null,jobs, &#39;The list of AsyncApexJob should not be null.&#39;);<br>            // 1. Prepare the fixed string values<br>            List&lt;String&gt; statusValues = new List&lt;String&gt;{&#39;ScheduledApex&#39;, &#39;BatchApex&#39;, &#39;Future&#39;, &#39;Queueable&#39;};<br>    <br>            // 2. Format the string values for the IN clause<br>            List&lt;String&gt; quotedStatusValues = new List&lt;String&gt;();<br>            for (String s : statusValues) {<br>                quotedStatusValues.add(&#39;\&#39;&#39; + String.escapeSingleQuotes(s) + &#39;\&#39;&#39;);<br>            }<br>            String inClauseValues = String.join(quotedStatusValues, &#39;,&#39;);<br><br>            String whereValue = &#39;MassApproversBatchV2&#39;;    <br>            String query = &#39;SELECT Id, CreatedDateTime__c, CreatedUserId__c, CreatedUserName__c, JobType__c, Status__c, JobItemsProcessed__c, &#39;+<br>                       &#39;TotalJobItems__c, NumberOfErrors__c, CompletedDateTime__c,  Apex_Job_ID__c, ApexClassName__c &#39;+<br>                        &#39;FROM Async_Job_Record__c &#39;+<br>                        //&#39;WHERE ApexClassName__c =: whereValue&#39;;<br>                        //&#39;WHERE ApexClassName__c =\&#39;MassApproversBatchV2\&#39;&#39;;<br>                        &#39;WHERE JobType__c IN (&#39; + inClauseValues + &#39;)&#39;;<br>            List&lt;String&gt; conditions = new List&lt;String&gt;();<br>            if (stDate != null) {<br>                conditions.add(&#39;CreatedDate &gt;= :stDate&#39;);<br>            }<br>            if (endDate != null) {<br>                conditions.add(&#39;CreatedDate &lt;= :endDate&#39;);<br>            }<br>            if (String.isNotBlank(selectedValue)) {<br>                 conditions.add(&#39;ApexClassName__c = \&#39;&#39; + selectedValue + &#39;\&#39;&#39;);<br>            }<br>            if (!conditions.isEmpty()) {<br>                query += &#39; AND &#39; + String.join(conditions, &#39; AND &#39;);<br>            }<br>            <br>            Map&lt;String, Object&gt; bindVars = new Map&lt;String, Object&gt;();<br>            bindVars.put(&#39;stDate&#39;, stDate);<br>            bindVars.put(&#39;endDate&#39;, endDate);<br>            bindVars.put(&#39;selectedValue&#39;, &#39;&#39;);<br>            List&lt;SObject&gt; records = Database.queryWithBinds(query, bindVars, AccessLevel.USER_MODE);<br>            <br>            query += &#39; ORDER BY CreatedDate DESC LIMIT 100&#39;;<br>                List&lt;Async_Job_Record__c&gt; asyncBatchJobs = Database.query(query);<br>                List&lt;BatchJobStatus.batchJobStatus&gt; batchJobStats = new List&lt;BatchJobStatus.batchJobStatus&gt;();<br>                 for (Integer i = 0; i &lt; asyncBatchJobs.size(); i++) {<br>                            Async_Job_Record__c aajob = asyncBatchJobs[i];<br>                            if(aajob!=null){<br>                                BatchJobStatus.batchJobStatus job = jobs[i];<br>                                BatchJobStatus.batchJobStatus bjs = new BatchJobStatus.batchJobStatus();<br>                                bjs.Id= aajob.Apex_Job_ID__c;<br>                                bjs.JobType= aajob.JobType__c;<br>                                bjs.Status= aajob.status__c;            <br>                                bjs.CreatedDate= aajob.CreatedDateTime__c;<br>                                bjs.CreatedBy= aajob.CreatedUserName__c;<br>                                bjs.CompletedDate= aajob.CompletedDateTime__c;<br>                                bjs.JobItemsProcessed= aajob.JobItemsProcessed__c;<br>                                bjs.TotalJobItems= aajob.TotalJobItems__c;<br>                                bjs.NumberOfErrors= aajob.NumberOfErrors__c;<br>                                bjs.FileName= aajob.ApexClassName__c; <br>                                batchJobStats.add(bjs);<br>                     } <br>              }<br>        <br>        }<br><br>        // A simple schedulable class for testing purposes<br>        public class TestSchedulableClass implements Schedulable {<br>            public void execute(SchedulableContext sc) {<br>                // Do nothing or perform a simple operation for the test<br>            }<br>        }        <br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a19828e75a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using LWC, display any deployment details along with changeset name (if deployed with Changeset)]]></title>
            <link>https://kkgcom.medium.com/using-lwc-display-any-deployment-details-along-with-changeset-name-if-deployed-with-changeset-d4aa72606916?source=rss-a65def60db88------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4aa72606916</guid>
            <category><![CDATA[tooling-api]]></category>
            <category><![CDATA[filter-deployment-records]]></category>
            <category><![CDATA[deployrequest]]></category>
            <category><![CDATA[session-api]]></category>
            <category><![CDATA[salesforce-lwc]]></category>
            <dc:creator><![CDATA[Kajal Ghosh]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 09:53:04 GMT</pubDate>
            <atom:updated>2026-04-08T09:53:04.985Z</atom:updated>
            <content:encoded><![CDATA[<p>The requirement was to create a LWC component to display deployment details for a date range with status, deployment date, deployment done by, files or components deployed along with the changeset name, if deployed through changeset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*1TvHQ9JZbj5-UQ11RLKEww.jpeg" /></figure><p>Salesforce is storing all the deployment details in an object: DeployRequest, however we can’t directly fetch the records using soql query in an apex class.</p><p>In Salesforce, the <strong>DeployRequest</strong> is a specialized object used primarily via the <strong>Tooling API</strong> and <strong>Metadata API</strong> to manage, read and track the deployment of metadata components (such as Apex classes, objects, or triggers) into an organization.</p><p><strong>Tooling API</strong></p><p>Tooling API exposes metadata information of Org, we can access Metadata information using REST or SOAP. Tooling API retrieve the small piece of metadata, we can use this to develop an interactive application or tools for developers. This can be used to fetch the metadata such as Apex classes, Apex triggers, custom objects, custom fields, Visualforce Pages, Users, Apex Component etc.<br> <br> Tooling API provides both SOAP and REST interfaces.</p><p><strong>Resources</strong></p><p>The base URI for each Tooling REST API resource is:<br> <a href="https://domain/services/data/vXX.X/tooling/">https://domain/services/data/vXX.X/tooling/</a><br> where domain is a Salesforce instance or a custom domain and vXX.X is the API version number.<br> Example:- <a href="https://abctest.salesforce.com/services/data/v28.0/tooling/">https://abctest.salesforce.com/services/data/v28.0/tooling/</a></p><p><strong>Features:</strong></p><p><strong>We can accomplish following tasks using Tooling API:</strong></p><ul><li>Fetch the metadata about Visualforce Pages, Apex Triggers, Apex classes.</li><li>Get the metadata about an object’s field.</li><li>Get the Code Coverage details of Apex Classes and Triggers.</li><li>Retrieve metadata of custom and standard object properties.</li><li>Retrieve metadata information about Validation Rules and Workflow Rules.</li><li>We can Create, Update Apex Classes and Apex Triggers.</li><li>We can get the RecentItems of our dev-org using Tooling API.</li></ul><p>In general, developers use <strong><em>UserInfo.getSessionId() </em></strong>to get current users sessionId in apex,</p><p>But when running it from apex code that’s being called by a component, you will receive</p><p>System.HttpResponse[Status=Unauthorized, StatusCode=401]</p><p>When you run the code from Execute Anonymous Window, you will receive</p><p>System.HttpResponse[Status=OK, StatusCode=200]</p><p>So, as it turns outs there is no way of getting a valid API-capable Session-Id from lightning component, here is a quote from the partner discussion forums:</p><p><strong>Three things:</strong></p><ol><li>There’s no $Api global variable in Lightning Components today. So, {! $Api.whatever } will always fail.</li><li>This is intentional at this time. There’s no official/supported way to get an API-capable session ID in Lightning Components. Again, this is by design.</li><li>With only a little creativity and cleverness you can create a bare-bones Visualforce page with {! $Api.SessionID }, and then call getContent(thatPage) from Apex to get a page that contains an API-capable session ID, which you should be able to parse out easily enough.</li></ol><p>From there, it’s not hard to pass that session ID along to Lightning Components via an @AuraEnabled method.</p><p><strong>Implementation of Tooling API in Salesforce Classic:</strong></p><p>But let’s be clear: this is a hack, the performance will be poor, and there’s good reasons to keep an API-capable session ID out of your Lightning Components code.</p><p>Create a Visual Force page</p><p><strong>GetSessionId.vfp</strong></p><p>&lt;apex:page&gt;<br> Start_Of_Session_Id{!$Api.Session_ID}End_Of_Session_Id<br> &lt;/apex:page&gt;</p><p>Create a Utils Class</p><p><strong>UtilsGetSessionId</strong></p><p>global class UtilsGetSessionId{<br> global static String getSessionIdFromVFPage(PageReference visualforcePage){<br> String content = visualforcePage.getContent().toString();<br> Integer s = content.indexOf(‘Start_Of_Session_Id’) + ‘Start_Of_Session_Id’.length(),<br> e = content.indexOf(‘End_Of_Session_Id’);<br> return content.substring(s, e);<br> }<br> }</p><p><strong>Update your controller like this</strong></p><p>req.setHeader(‘Authorization’, ‘Bearer ‘ + <strong>UtilsGetSessionId</strong>.getSessionIdFromVFPage(Page.GetSessionId));</p><p><strong>Implementation of Tooling API in Salesforce Lightning:</strong></p><p>As we know we can not make the Salesforce API Call directly from the lightning component.If we use the UserInfo.getSessionID() it will return this.</p><p><strong>INVALID_SESSION_ID:This session is not valid for use with the Rest API.</strong></p><p>So to make Callout for this API in the Lightning Component we need to create three things:</p><ol><li>A Connected App.</li><li>An Auth. Provider.</li><li>A Named Credential.</li></ol><p><strong>1. Steps to Create the Connected App:</strong></p><ul><li>Find for Apps in Quick Search Box.</li><li>Click on App Manager.</li><li>Click on New Connected App.</li><li>Enter the Name for Connected App</li><li>Enter your contact Email.</li><li>Enter the URL of your page in Callback URL.</li><li>Select all the scopes in Selected Auth Scopes.</li><li>Click on Save Button. The page will shown as below:</li></ul><p><strong>2.Steps to Create an Auth. Provider:</strong></p><ul><li>From Setup, enter Auth. Providers in the Quick Find box, and then select <strong>Auth. Providers</strong> then click on <strong>New</strong> button.</li><li>Select Salesforce for the provider type.</li><li>Enter a name of the provider.</li><li>Enter the URL suffix, which is used in the client configuration URLs.</li><li>Paste the consumer key value from the connected app definition into the Consumer Key field.</li><li>Paste the consumer secret value from the connected app definition into the Consumer Secret field.</li><li>For Authorize Endpoint URL, specify an OAuth authorization URL.<br> Ex: <a href="https://login.salesforce.com/services/oauth2/authorize.">https://login.salesforce.com/services/oauth2/authorize.</a></li><li>For Token Endpoint URL, specify an OAuth token URL.<br> Ex: <a href="https://login.salesforce.com/services/oauth2/token">https://login.salesforce.com/services/oauth2/token</a></li><li>After entering all the details click on save button, the page will be shown as below:</li></ul><p><strong>3.Steps to Create a Named Credential:</strong></p><ul><li>From Setup, enter <strong>Named Credentials</strong> in the Quick Find box, and then select <strong>Named Credentials| New Named Credential.</strong></li><li>Enter the Name.</li><li>Enter URL for Named Credential.</li><li>Select <strong>Named Principal</strong> for Identity type.</li><li>Select <strong>Oauth 2.0</strong> for Authentication Protocol.</li><li>Choose the Authorization Provider you created.</li><li>Enter <strong>refresh_token full</strong> in the Scope field.</li><li>Click on save button and page will seen as below after saving it.</li></ul><p>After completion of all the three steps, we can use the Named Credential in the (Endpoint) @AuraEnabled apex method to make the Salesforce API callout from the Lightning Component.</p><p>@AuraEnabled public static String Callout(){<br> Http h = new Http();<br> HttpRequest req = new HttpRequest();<br> <strong>req.setEndpoint(‘callout:Test1/services/data/v35.0/tooling/query/?q=Select+id,FullName,createdDate,TableEnumOrId,ValidationName,Metadata+from+ValidationRule’);</strong> req.setMethod(‘GET’);<br> req.setHeader(‘Content-Type’, ‘application/json’);<br> HttpResponse res = h.send(req);<br> return res; }</p><p>I have used the classic method of creating vf page, mentioned earlier.</p><p><strong>Visual Force Page:</strong></p><p>GetSessionId.vfp:</p><p>&lt;apex:page &gt;</p><p>Start_Of_Session_Id{!$Api.Session_ID}End_Of_Session_Id</p><p>&lt;/apex:page&gt;</p><p><strong>Main Class to be called from LWC:</strong></p><pre>public class checkDeployStatus {<br>// Method to query DeployRequest records using Tooling API<br>@AuraEnabled(cacheable=true)<br>public static List&lt;DeployRequest&gt; getDeployRequests(DateTime startDate, DateTime endDate) {<br>String query = &#39;SELECT Id, ChangeSetName, Status, StartDate, CompletedDate FROM DeployRequest&#39;;<br>List&lt;String&gt; conditions = new List&lt;String&gt;();<br>if (startDate != null) {<br>query += &#39; WHERE StartDate &gt;= &#39; + startDate.formatGMT(&#39;yyyy-MM-dd\&#39;T\&#39;HH:mm:ss\&#39;Z\&#39;&#39;);<br>}<br>if (endDate != null) {<br>Date datePart = endDate.date();<br>// 2. Create a new Time instance for 11:59:59 PM<br>// Note: Milliseconds are typically 0 when setting to the end of the second.<br>Time endOfDayTime = Time.newInstance(23, 59, 59, 0);<br>// 3. Combine Date and Time to create the new DateTime<br>DateTime endOfDayDateTime = DateTime.newInstance(datePart, endOfDayTime);<br>query += &#39; AND StartDate &lt;= &#39; + endOfDayDateTime.formatGMT(&#39;yyyy-MM-dd\&#39;T\&#39;HH:mm:ss\&#39;Z\&#39;&#39;);<br>}<br>query += &#39; ORDER BY StartDate DESC LIMIT 99&#39;; // Add a limit for performance<br>HttpResponse res = ToolingAPIUtility.queryToolingAPI(query);<br>List&lt;DeployRequest&gt; deployRequests = new List&lt;DeployRequest&gt;();<br>if (res.getStatusCode() == 200) {<br>Map&lt;String, Object&gt; responseMap = (Map&lt;String, Object&gt;) JSON.deserializeUntyped(res.getBody());<br>List&lt;Object&gt; records = (List&lt;Object&gt;) responseMap.get(&#39;records&#39;);<br>for (Object record : records) {<br>Map&lt;String, Object&gt; deployRequestMap = (Map&lt;String, Object&gt;) record;<br>DeployRequest dr = new DeployRequest();<br>String drId = (String) deployRequestMap.get(&#39;Id&#39;);<br>dr.Id = (String) drId.substring(0, drId.length() - 3);<br>dr.Status = (String) deployRequestMap.get(&#39;Status&#39;);<br>dr.Name = (String) deployRequestMap.get(&#39;ChangeSetName&#39;);<br>String dateTimeString;<br>String cleanedDateTimeString;<br>if(deployRequestMap.get(&#39;CompletedDate&#39;) != null){<br>dr.CompletedDate = (Datetime) JSON.deserialize(&#39;&quot;&#39; + (String)deployRequestMap.get(&#39;CompletedDate&#39;) + &#39;&quot;&#39;, Datetime.class);<br>}<br>if(deployRequestMap.get(&#39;StartDate&#39;) != null){<br>dr.StartDate = (Datetime) JSON.deserialize(&#39;&quot;&#39; + (String)deployRequestMap.get(&#39;StartDate&#39;) + &#39;&quot;&#39;, Datetime.class);<br>}<br>DeployResult data = checkDeployStatus.checkAndDisplayDeployStatus(dr);<br>dr.FileName = data.FileName;<br>dr.CreatedBy = data.CreatedBy;<br>if(data.isDeploy == false){<br>deployRequests.add(dr);<br>}<br>}<br>} else {<br>System.debug(&#39;Error querying DeployRequest: &#39; + res.getBody());<br>}<br>return deployRequests;<br>}<br>// Method to check deploy status and display file names<br>public static DeployResult checkAndDisplayDeployStatus(DeployRequest deployRequest) {<br>HttpRequest req = new HttpRequest();<br>String deployRequestId =deployRequest.id;<br>String instanceName = System.Url.getOrgDomainUrl().toExternalForm();<br>// Visualforce can&#39;t make the direct API calls. Might need to massage the instanceName<br>req.setEndpoint(instanceName + &#39;/services/data/v64.0/metadata/deployRequest/&#39; + deployRequestId + &#39;?includeDetails=true&#39;);<br>req.setMethod(&#39;GET&#39;);<br>req.setHeader(&#39;Authorization&#39;,&#39;Bearer &#39; + UtilsGetSessionId.getSessionIdFromVFPage(Page.GetSessionId));<br>req.setHeader(&#39;Content-Type&#39;, &#39;application/json&#39;);<br>Http http = new Http();<br>HttpResponse res = http.send(req);<br>DeployResult result = new DeployResult();<br>String fileNames=&#39;&#39;;<br>if (res.getStatusCode() == 200) {<br>Map&lt;String, Object&gt; responseMap = (Map&lt;String, Object&gt;) JSON.deserializeUntyped(res.getBody());<br>DeployResultJson jsonResult = (DeployResultJson)JSON.deserialize(res.getBody(), DeployResultJson.class);<br>if(jsonResult.deployResult != null &amp;&amp; jsonResult.deployResult.checkOnly ==false &amp;&amp; jsonResult.deployResult.details != null &amp;&amp; jsonResult.deployResult.details.componentSuccesses != null) {<br>for(Metadata.DeployMessage dm : jsonResult.deployResult.details.componentSuccesses) {<br>if(dm.fullName == &#39;package.xml&#39;) {<br>continue;<br>}<br>else{<br>if (fileNames == &#39;&#39;){<br>fileNames = dm.fullName;<br>}<br>else{<br>fileNames = fileNames + &#39;,&#39; + dm.fullName;<br>}<br>}<br>}<br>result.CreatedBy = jsonResult.deployResult.createdByName;<br>result.isDeploy = jsonResult.deployResult.checkOnly;<br>}<br>else if(jsonResult.deployResult != null &amp;&amp; jsonResult.deployResult.checkOnly ==false &amp;&amp; jsonResult.deployResult.details != null &amp;&amp; jsonResult.deployResult.details.componentFailures != null) {<br>for(Metadata.DeployMessage dm : jsonResult.deployResult.details.componentFailures) {<br>if(dm.fullName == &#39;package.xml&#39;) {<br>continue;<br>}<br>else{<br>if (fileNames == &#39;&#39;){<br>fileNames = dm.fullName;<br>}<br>else{<br>fileNames = fileNames + &#39;,&#39; + dm.fullName;<br>}<br>}<br>}<br>result.CreatedBy = jsonResult.deployResult.createdByName;<br>result.isDeploy = jsonResult.deployResult.checkOnly;<br>}<br>result.FileName = fileNames;<br>} else {<br>System.debug(&#39;Error checking deploy status for DeployRequest &#39; + deployRequest.Id + &#39;: &#39; + res.getBody());<br>}<br>return result;<br>}<br>// Inner class to represent DeployRequest structure for easier handling<br>public class DeployRequest {<br>@AuraEnabled public String Id;<br>@AuraEnabled public String Name;<br>@AuraEnabled public String Status;<br>@AuraEnabled public DateTime StartDate;<br>@AuraEnabled public DateTime CompletedDate;<br>@AuraEnabled public String CreatedBy;<br>@AuraEnabled public String ComponentType;<br>@AuraEnabled public String FileName;<br>}<br>public class DeployResult {<br>public String FileName { get; set; }<br>public String CreatedBy;<br>public Boolean isDeploy {get; set; }<br>}<br>// Support unpacking via JSON.deserialize from deployRequest metadata api call<br>public class DeployResultJson {<br>public String id;<br>public Object validatedDeployRequestId;<br>public Object deployOptions;<br>public Metadata.DeployResult deployResult;<br>public String fileName;<br>public String componentType;<br>}<br>}<br>public with sharing class ToolingAPIUtility {<br>public static final String endpoint = &#39;/services/data/v64.0/tooling/query/?q=&#39;;<br>public static HttpResponse queryToolingAPI(String query) {<br>String baseUrl = URL.getOrgDomainUrl().toExternalForm();<br>String urlString = endpoint + EncodingUtil.urlEncode(query, &#39;UTF-8&#39;);<br>HttpRequest request = new HttpRequest();<br>request.setEndpoint(baseUrl + urlString);<br>request.setMethod(&#39;GET&#39;);<br>request.setTimeout(120000);<br>// OAuth header<br>request.setHeader(&#39;Authorization&#39;,&#39;Bearer &#39; + UtilsGetSessionId.getSessionIdFromVFPage(Page.GetSessionId));<br>request.setHeader(&#39;Content-Type&#39;, &#39;application/json&#39;);<br>Http http = new Http();<br>HttpResponse response = http.send(request);<br>return response;<br>}<br>}<br>UtilsGetSessionId Class:<br>global class UtilsGetSessionId {<br>global static String getSessionIdFromVFPage(PageReference visualforcePage){<br>String content = Test.isRunningTest() ? &#39;Start_Of_Session_Idtest1234567889999999999999End_Of_Session_Id&#39; : visualforcePage.getContent().toString();<br>Integer s = content.indexOf(&#39;Start_Of_Session_Id&#39;) + &#39;Start_Of_Session_Id&#39;.length(),<br>e = content.indexOf(&#39;End_Of_Session_Id&#39;);<br>return content.substring(s, e);<br>}<br>}</pre><p><strong>Test Class:</strong></p><pre>@IsTest<br>public class checkDeployStatusTest {<br>@IsTest<br>static void testGetDeployRequestsAndCheckStatus() {<br>// Mock HTTP callout for getDeployRequests<br>Test.setMock(HttpCalloutMock.class, new MockDeployRequestCallout());<br>Date stDate = Date.newInstance(2025, 1, 1);<br>Time stTime = Time.newInstance(10, 30, 0, 0); // Hours, Minutes, Seconds, Milliseconds<br>DateTime startDt = DateTime.newInstance(stDate, stTime);<br>Date testDate = Date.newInstance(2025, 9, 16);<br>Time testTime = Time.newInstance(10, 30, 0, 0); // Hours, Minutes, Seconds, Milliseconds<br>DateTime endDt = DateTime.newInstance(testDate, testTime);<br>List&lt;checkDeployStatus.DeployRequest&gt; deployRequests = checkDeployStatus.getDeployRequests(startDt, endDt);<br>System.assertNotEquals(null, deployRequests, &#39;Deploy requests should not be null&#39;);<br>// Mock HTTP callout for checkAndDisplayDeployStatus<br>Test.setMock(HttpCalloutMock.class, new MockDeployResultCallout());<br>checkDeployStatus.DeployRequest sampleDeployRequest = new checkDeployStatus.DeployRequest();<br>sampleDeployRequest.Id = &#39;0AfPu00000NSi2UKAT&#39;; // Use a sample ID for testing<br>sampleDeployRequest.Status = &#39;Succeeded&#39;;<br>Test.startTest();<br>checkDeployStatus.checkAndDisplayDeployStatus(sampleDeployRequest);<br>Test.stopTest();<br>}<br>// Mock class for getDeployRequests callout<br>private class MockDeployRequestCallout implements HttpCalloutMock {<br>public HttpResponse respond(HttpRequest req) {<br>HttpResponse res = new HttpResponse();<br>res.setHeader(&#39;Content-Type&#39;, &#39;application/json&#39;);<br>res.setBody(&#39;{&quot;size&quot;:1,&quot;done&quot;:true,&quot;records&quot;:[{&quot;attributes&quot;:{&quot;type&quot;:&quot;DeployRequest&quot;,&quot;url&quot;:&quot;/services/data/v64.0/tooling/sobjects/DeployRequest/0AfPu00000NSi2UKAT&quot;},&quot;Id&quot;:&quot;0AfPu00000NSi2UKAT&quot;,&quot;Status&quot;:&quot;Succeeded&quot;,&quot;CreatedDate&quot;:&quot;2023–10–26T10:00:00.000+0000&quot;, &quot;checkOnly&quot;:false}]}&#39;);<br>res.setStatusCode(200);<br>return res;<br>}<br>}<br>// Mock class for checkAndDisplayDeployStatus callout<br>private class MockDeployResultCallout implements HttpCalloutMock {<br>public HttpResponse respond(HttpRequest req) {<br>HttpResponse res = new HttpResponse();<br>res.setHeader(&#39;Content-Type&#39;, &#39;application/json&#39;);<br>//res.setBody(&#39;{&quot;size&quot;:1,&quot;done&quot;:true, &quot;records&quot;:[{&quot;attributes&quot;:{&quot;type&quot;:&quot;DeployResult&quot;,&quot;url&quot;:&quot;/services/data/v64.0/tooling/sobjects/DeployResult/0AfPu00000NSi2UKAT&quot;},&quot;Id&quot;:&quot;0AfPu00000NSi2UKAT&quot;,&quot;FileName&quot;:&quot;MyApexClass.cls&quot;}]}&#39;);<br>res.setBody(&#39;{&quot;size&quot;:1,&quot;done&quot;:true, &quot;records&quot;:[{&quot;attributes&quot;:{&quot;type&quot;:&quot;DeployResult&quot;,&quot;url&quot;:&quot;/services/data/v64.0/tooling/sobjects/DeployResult/0AfPu00000NSi2UKAT&quot;},&quot;Id&quot;:&quot;0AfPu00000NSi2UKAT&quot;,&quot;checkOnly&quot;:false,&quot;status&quot;:&quot;Succeeded&quot;,&quot;success&quot;:true,&quot;startDate&quot;:&quot;2025–02–01T12:00:00.000Z&quot;,&quot;completedDate&quot;:&quot;2025–02–01T12:01:00.000Z&quot;,&quot;details&quot;:{&quot;componentFailures&quot;:[],&quot;componentSuccesses&quot;:[{&quot;componentType&quot;:&quot;ApexClass&quot;,&quot;fileName&quot;:&quot;src/classes/YourApexClass.cls&quot;,&quot;fullName&quot;:&quot;YourApexClass&quot;,&quot;id&quot;:&quot;0AfPu00000NSi2UKAT&quot;,&quot;success&quot;:true}]},&quot;startDate&quot;:&quot;2025–02–01T12:00:00.000Z&quot;,&quot;completedDate&quot;:&quot;2025–02–01T12:01:00.000Z&quot;}]}&#39;);<br>res.setStatusCode(200);<br>return res;<br>}<br>}<br>}</pre><p><strong>LWC Components:</strong></p><p>HTML File:</p><pre>&lt;template&gt;<br>&lt;lightning-card title=&quot;Last 100 Deployment Records&quot;&gt;<br>&lt;div class=&quot;slds-m-around_medium slds-grid slds-gutters slds-nowrap slds-align_absolute-center&quot;&gt;<br>&lt;div class=&quot;slds-col slds-size_1-of-3&quot;&gt;<br>&lt;lightning-input<br>type=&quot;date&quot;<br>label=&quot;Start Date&quot;<br>onchange={handleStartDateChange}&gt;<br>&lt;/lightning-input&gt;<br>&lt;/div&gt;<br>&lt;div class=&quot;slds-col slds-size_1-of-3&quot;&gt;<br>&lt;lightning-input<br>type=&quot;date&quot;<br>label=&quot;End Date&quot;<br>onchange={handleEndDateChange}&gt;<br>&lt;/lightning-input&gt;<br>&lt;/div&gt;<br>&lt;div class=&quot;slds-col slds-size_1-of-3 slds-align-bottom&quot;&gt;<br>&lt;lightning-button<br>label=&quot;Apply Filter&quot;<br>onclick={applyFilter}&gt;<br>&lt;/lightning-button&gt;<br>&lt;/div&gt;<br>&lt;/div&gt;<br>&lt;div class=&quot;slds-m-around_medium&quot;&gt;<br>&lt;template if:true={deploymentStatusData}&gt;<br>&lt;lightning-datatable<br>key-field=&quot;Id&quot;<br>data={deploymentStatusData}<br>columns={columns}<br>hide-checkbox-column=&quot;true&quot;<br>&gt;&lt;/lightning-datatable&gt;<br>&lt;/template&gt;<br>&lt;template if:true={error}&gt;<br>&lt;p class=&quot;slds-text-color_error&quot;&gt;{error}&lt;/p&gt;<br>&lt;/template&gt;<br>&lt;/div&gt;<br>&lt;/lightning-card&gt;<br>&lt;/template&gt;</pre><p><strong>Javascript file (.js):</strong></p><pre>import { LightningElement, api, wire, track } from &#39;lwc&#39;;<br>import getFilteredRecords from &#39;@salesforce/apex/checkDeployStatus.getDeployRequests&#39;;<br>import { NavigationMixin } from &#39;lightning/navigation&#39;;<br>export default class DispDeployStatus extends NavigationMixin(LightningElement) {<br>@track startDate;<br>@track endDate;<br>@track records;<br>@track error;<br>@api deploymentId;<br>@track deploymentStatusData = [];<br>// Define columns for lightning-datatable (adjust based on your object&#39;s fields)<br>columns = [<br>{ label: &#39;Record Id&#39;, fieldName: &#39;Id&#39;, type: &#39;text&#39;},<br>{ label: &#39;Name&#39;, fieldName: &#39;Name&#39;, type: &#39;text&#39; },<br>{ label: &#39;Status&#39;, fieldName: &#39;Status&#39;, type: &#39;text&#39; },<br>{ label: &#39;Start Date&#39;, fieldName: &#39;StartDate&#39;, type: &#39;date&#39; },<br>{ label: &#39;Completed Date&#39;, fieldName: &#39;CompletedDate&#39;, type: &#39;date&#39; },<br>{ label: &#39;Created By&#39;, fieldName: &#39;CreatedBy&#39;, type: &#39;text&#39; },<br>{ label: &#39;FileName&#39;, fieldName: &#39;FileName&#39;, type: &#39;text&#39;, initialWidth: 400, wrapText: true }<br>];<br>handleRowAction(event) {<br>const actionName = event.detail.action.name;<br>const row = event.detail.row;<br>if (actionName === &#39;view_record&#39;) {<br>this[NavigationMixin.Navigate]({<br>type: &#39;standard__webPage&#39;,<br>attributes: {<br>url: &#39;/lightning/setup/DeploymentStatus/home?checkDeployStatus=${row.Id}&#39;<br>}<br>});<br>}<br>}<br>handleViewSpecificStatus() {<br>this[NavigationMixin.Navigate]({<br>type: &#39;standard__webPage&#39;,<br>attributes: {<br>url: &#39;/lightning/setup/DeploymentStatus/home?checkDeployStatus=${this.deploymentId}&#39;<br>}<br>});<br>}<br>handleStartDateChange(event) {<br>this.startDate = event.target.value;<br>}<br>handleEndDateChange(event) {<br>this.endDate = event.target.value;<br>}<br>applyFilter() {<br>this.fetchRecords();<br>}<br>connectedCallback() {<br>  this.fetchRecords(); // Fetch records initially without filters<br>}<br>fetchRecords() {<br>getFilteredRecords({<br>startDate: this.startDate,<br>endDate: this.endDate<br>})<br>.then(result =&gt; {<br>//this.records = result;<br>this.deploymentStatusData = result.map(item =&gt; ({<br>…item,<br>StartDate: item.StartDate<br>}));<br>this.error = undefined;<br>})<br>.catch(error =&gt; {<br>this.error = error.body.message;<br>this.records = undefined;<br>});<br>}<br>formatDateTime(dateTimeValue) {<br>  if (!dateTimeValue) {<br>    return &#39;&#39;; // Handle null or undefined values<br>  }<br>  const date = new Date(dateTimeValue);<br>  // Example formatting: &quot;MM/DD/YYYY HH:MM AM/PM&quot;<br>  const options = {<br>    year: &#39;numeric&#39;,<br>    month: &#39;2-digit&#39;,<br>    day: &#39;2-digit&#39;,<br>    hour: &#39;2-digit&#39;,<br>    minute: &#39;2-digit&#39;,<br>    hour12: true<br>  };<br>  return date.toLocaleString(); // e.g., &quot;8/28/2025, 7:44:00 PM&quot;<br>  }<br>}</pre><p><strong>.js-meta.xml file:</strong></p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;LightningComponentBundle xmlns=&quot;http://soap.sforce.com/2006/04/metadata&quot;&gt;<br>&lt;apiVersion&gt;64.0&lt;/apiVersion&gt;<br>&lt;isExposed&gt;true&lt;/isExposed&gt;<br>&lt;targets&gt;<br>&lt;target&gt;lightning__AppPage&lt;/target&gt;<br>&lt;target&gt;lightning__RecordPage&lt;/target&gt;<br>&lt;target&gt;lightning__HomePage&lt;/target&gt;<br>&lt;/targets&gt;<br>&lt;/LightningComponentBundle&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4aa72606916" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>