• Atiqah
  • NEWBIE
  • 40 Points
  • Member since 2021

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 10
    Questions
  • 6
    Replies
Hi all,

I would like to ask if it is possible to auto-approve the record if the case status is closed. Here is the scenario:

A user submits a case for approval, however, the approver closes the case. When the case is closed, the case should be auto-approved. 

I see we can auto-submit the record, but I don't see if it is possible to auto-approve records since we cannot update processInstence object
  • March 08, 2023
  • Like
  • 0
Hi, I need help.
I received the below error
EXCEPTION_THROWN [22]|System.QueryException: unexpected token: s0000014qrPAAQ

Here is the Apex code
public with sharing class toApproved {
    @AuraEnabled(cacheable=true)
    //public static list<ProcessInstanceWorkitem> getItemApprove(){
    public static list<ProcessInstanceWorkitem> getItemApprove(id ActorId){
        id actorid2 = ActorId;
        system.debug('Actor: '+ActorId);
        system.debug('Actor2: '+actorid2);

        String condition = 'ActorId = '+ActorId;
        system.debug('condition: '+condition);

        string query = 'select ProcessInstance.TargetObject.name, CreatedDate, CreatedBy.name, ActorId, Actor.name from ProcessInstanceWorkitem where ' +condition + ' order by CreatedDate limit 100';
        system.debug('query: '+query);

        list<ProcessInstanceWorkitem> records = Database.query(query);
        system.debug('records '+records);

        return records;
    }
}


 
  • January 06, 2023
  • Like
  • 0
Hi, anyone can help me how to call ApprovarId variable from JavaScript to Apex controller to replace value = :ActorId in query?
export default class ToApproved extends LightningElement {
    ApprovarId= Id;
    availableItems;
    error;
    columns = columns;

    @wire (toApproved)
    wiredAccount({error,data}){
        if(data){
            let tempRecs = [];
            data.forEach((record)=>{
                let tempRec = Object.assign({},record);

                //Name & target object id
                var objDes = JSON.stringify(tempRec.ProcessInstance.TargetObject);
                var finalObject = JSON.parse(objDes);
                tempRec.Object = '/'+tempRec.ProcessInstance.TargetObjectId;
                tempRec.recordName = finalObject.Name;

                //Name & created/submitted user id
                var createduser = JSON.stringify(tempRec.CreatedBy);
                var finalData = JSON.parse(createduser);
                tempRec.CreatedBy = '/'+tempRec.CreatedById;
                tempRec.createdByName = finalData.Name;

                //Name and approverid
                var approvar = JSON.stringify(tempRec.Actor);
                var finalApprovar = JSON.parse(approvar);
                tempRec.ApprovedBy = '/'+finalApprovar.name;
                tempRec.ApprovarName = tempRec.Actor.Name;

                tempRecs.push(tempRec);
            });
            this.availableItems = tempRecs;
            this.error = undefined;

        }else if(error){
            this.error = error;
            this.availableItems = undefined;
        }

    }

}
 
public with sharing class toApproved {
    @AuraEnabled(cacheable=true)
    public static list<ProcessInstanceWorkitem> getItemApprove(id ActorId){
        return[select ProcessInstance.TargetObject.name, CreatedDate, CreatedBy.name, ActorId, Actor.name from ProcessInstanceWorkitem
        where ActorId = :ActorId
        order by CreatedDate limit 100];
    }
}

Thank You
 
  • December 30, 2022
  • Like
  • 0
Hi, need your help to check on this code.
This code does not give me the expected result. By right object should display all record name and submitted y should display user name. But both field should be can clock and redirect to its record 
User-added image
Apex class
public with sharing class toApproved {
    @AuraEnabled(cacheable=true)
    public static list<ProcessInstanceWorkitem> getItemApprove(){
        return[select id, CreatedById,ProcessInstance.TargetObject.name,ProcessInstance.TargetObjectId,CreatedDate,CreatedBy.name from ProcessInstanceWorkitem order by CreatedDate limit 100];
    }
}
 
lwc js

import { LightningElement, wire } from 'lwc';
import toApproved from '@salesforce/apex/toApproved.getItemApprove';
const columns = [
    {label: 'CreatedDate', fieldName: 'CreatedDate' },
   
    {label: 'Object',
    fieldName:'ObjectId',
    type:'url',
    typeAttributes:{
        label:{
            fieldName:'ProcessInstance.TargetObject.Name'},
            target:'_blank'}
        },
        {label: 'Submitted By',
        fieldName:'CreatedById',
        type:'url',
        typeAttributes:{
            label:{
                fieldName:'CreatedBy.name'},
                target:'_blank'}
            }
   
];
export default class ToApproved extends LightningElement {
    availableItems;
    error;
    columns = columns;
    @wire (toApproved)
    wiredAccount({error,data}){
        if(data){
            let tempRecs = [];
            data.forEach((record)=>{
                let tempRec = Object.assign({},record);
                tempRec.ObjectId = '/'+tempRec.ProcessInstance.TargetObjectId;
                tempRec.CreatedById = '/'+tempRec.CreatedById;
                tempRecs.push(tempRec);
            });
            this.availableItems = tempRecs;
            this.error = undefined;
        }else if(error){
            this.error = error;
            this.availableItems = undefined;
        }
    }
}
 
HTML

<template>
    <lightning-card title="Item to Approve" icon-name="custom:custom63">
        <div class="slds-m-around_medium">
            <template if:true={availableItems}>
                <lightning-datatable
                key-field="Id"
                data={availableItems}
                columns={columns}
                hide-checkbox-column="true"
                show-row-number-column="true">
            </lightning-datatable>
            </template>
            <template if:true={error}>
                {error}
            </template>
        </div>
    </lightning-card>
</template>

 
  • December 21, 2022
  • Like
  • 0
Hi, need your help for this error
Illegal assignment from List<SObject> to List<ProcessInstance> (46:31)
public with sharing class ProcessInstance {
    @AuraEnabled(cacheable=true)
    public static List<ProcessInstance> getCases(
        String relatedTo,
        String submittedDate,
        String submittedBy
    ) {
        String query;
        String condition = (String.isNotBlank(relatedTo)
            ? 'TargetObject.name LIKE \'' + '%' + relatedTo + '%\''
            : '');

        condition += (String.isNotBlank(submittedDate)
            ? (String.isNotBlank(condition) ? +' AND ' : '') +
              ' LastModifiedDate LIKE \'' +
              '%' +
              submittedDate +
              '%\''
            : '');

        condition += (String.isNotBlank(submittedBy)
            ? (String.isNotBlank(condition) ? +' AND ' : '') +
              ' SubmittedBy.name LIKE \'' +
              '%' +
              submittedBy +
              '%\''
            : '');

        System.debug('condition ' + condition);
        if (String.isNotBlank(condition)) {
            query =
                'SELECT TargetObject.name,LastModifiedDate,SubmittedBy.name FROM ProcessInstance WHERE ' +
                condition +
                ' ORDER BY LastModifiedDate';
        } else {
            query = 'SELECT TargetObject.name,LastModifiedDate,SubmittedBy.name FROM ProcessInstance ORDER BY LastModifiedDate LIMIT 200';
        }

        List<ProcessInstance> records = Database.query(query);
        return records;
    }
}

 
  • November 23, 2022
  • Like
  • 0
Hi, I have LWC to help users search for products in my org. I need help with apex test code
 
public with sharing class FilterProduct {
    @AuraEnabled(cacheable=true)
    public static List<Product2> getproduct(
        String Name,
        String MaterialCode,
        String productType,

        ){
            String query;
            String condition = (String.isNotBlank(Name)? 'Name LIKE \'' + '%' + Name + '%\'': '');
            condition += (String.isNotBlank(MaterialCode)? (String.isNotBlank(condition) ? +' AND ' : '') +' Material_Code__c LIKE \'' + '%' +MaterialCode +'%\'': '');
            condition += (String.isNotBlank(productType)? (String.isNotBlank(condition) ? +' AND ' : '') +' product_Type__c LIKE \'' + '%' +productType +'%\'': '');
            System.debug('condition ' + condition);

            if (String.isNotBlank(condition)) {
                query =
                    'select name, Material_Code__c, product_Type__c from product2 WHERE ' +condition +' ORDER BY name limit 1000';
            } else {
                query = 'select name, Material_Code__c, product_Type__c from product2 ORDER BY Name LIMIT 200';
            }
    
            List<Product2> records = Database.query(query);
            return records;
        }
}

 
  • November 07, 2022
  • Like
  • 0
Hi,

Anyone can assist me with the code coverage for this class?
trigger CheckUserforBooth on Booth__c (after insert, before update) {
        
        List<booth__c> id=new List<booth__c>();
        for(Booth__c B : Trigger.new) {
            
            id=[select Tradeshow_Name__r.pic_1__r.id,Tradeshow_Name__r.pic_2__r.id from booth__c where Tradeshow_Name__c =: B.Tradeshow_Name__c];
            
            Id profileId = UserInfo.getProfileId();
            String profileName =[Select Id, Name from Profile where Id=:profileId].Name;
            system.debug('Profile Name'+profileName);
            
            
            if(UserInfo.getUserId()  <> id[0].Tradeshow_Name__r.pic_1__r.id 
               && UserInfo.getUserId()  <> id[0].Tradeshow_Name__r.pic_2__r.id
               && profileName<> 'User1') 
            {
                B.addError('You are not allowed to Save');
            }
        }
    }


 
Hi, my scenario I have 3 objects here. payment term credit limit, sales order and vehicle. let's say when users create new payment term records, the vehicle records will auto-populate based on the sales order. This code is working well for after insert only. but is I put After insert and after update, the vehicle records become double (duplicate value)
 
trigger CreateSOonPtcl on Payment_Term_Credit_Limit__c (after insert, after update) {
    set<Id> lstId = new set<Id>();
    set<date> startDate = New set<date>();
    set<date> endDate = New set<date>();
    List <Vehicle__c> vehToInsert = new List <Vehicle__c>(); 
    
    for (Payment_Term_Credit_Limit__c o : Trigger.new) {
        
        //meets the criteria
        if (o.Category__c == 'Increase / Decrease Credit Limit') {
            lstId.add(o.Name_of_Customer__c);
            startDate.add(o.Start_Order_Date__c);
            endDate.add(o.End_Order_Date__c);
        }
    }
    
    list<Sales_Order__c> lstOb1 =[select Id,Requested_Delivery_Date__c, account__c, Name,Po_No__c,Total_Qty_Pcs__c,Total_Amount_USD__c,Currency__c from Sales_Order__c where Account__c IN :lstId AND Status__c = 'E0005 ZSHP' and Order_Date__c >= :startDate and Order_Date__c <= :endDate order by CreatedDate ];
    for (Payment_Term_Credit_Limit__c oo : Trigger.new) {
        for(integer i=0; i<lstOb1.size(); i++){
            Vehicle__c v = new Vehicle__c ();
            v.Payment_Term_Credit_Limit__c = oo.id;
            V.Sales_Order__c = lstOb1[i].Id; 
            
            vehToInsert.add(v);
        }
    }
    
    try {
        insert vehToInsert;	
    } catch (system.Dmlexception e) {
        system.debug (e);
    }
    
}
User-added imageplease help me with this. I think It is because this code in loop
Vehicle__c v = new Vehicle__c ();


 
  • February 28, 2022
  • Like
  • 0
Hi, Can help me with the code coverage for this code?
if (SelectedMonth == 'Jan'){
                    a.January__c = double.valueOf(inputvalues[1]);
                    a.January_SO_Number__c = inputvalues[2];
                }else if(SelectedMonth == 'Feb'){
                    a.February__c = double.valueOf(inputvalues[1]);
                    a.February_SO_Number__c = inputvalues[2];
                }else if(SelectedMonth == 'Mar'){
                    a.March__c = double.valueOf(inputvalues[1]);
                    a.March_SO_Number__c = inputvalues[2];
                }else if(SelectedMonth == 'Apr'){
                    a.April__c = double.valueOf(inputvalues[1]);
                    a.April_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'May'){
                    a.Mei__c = double.valueOf(inputvalues[1]);
                    a.May_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Jun'){
                    a.June__c = double.valueOf(inputvalues[1]);
                    a.June_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Jul'){
                    a.July__c = double.valueOf(inputvalues[1]);
                    a.July_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Aug'){
                    a.August__c = double.valueOf(inputvalues[1]);
                    a.August_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Sep'){
                    a.September__c = double.valueOf(inputvalues[1]);
                    a.September_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Oct'){
                    a.October_del__c = double.valueOf(inputvalues[1]);
                    a.October_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Nov'){
                    a.November__c = double.valueOf(inputvalues[1]);
                    a.November_SO_Number__c = inputvalues[2];
                }else if(SelectedMonth == 'Dec'){
                    a.December__c = double.valueOf(inputvalues[1]);
                    a.December_SO_Number__c = inputvalues[2];
                }

User-added imageThis is the full code
 
public class UpdateIncentiveFile {
    
    public string nameFile{get;set;}
    public Blob contentFile{get;set;}
    public String selectedYear {get; set;}
    public String SelectedMonth {get; set;}
    
    String[] filelines = new String[]{};
        List<Incentive__c> accstoupload;
    List<id> listOfId;
    
    //years dropdown
    public List<SelectOption> getYears() {
        List<SelectOption> options = new List<SelectOption>();
        for (Integer i = System.Today().year() - 2; i < System.Today().year() + 3; i++) {
            options.add(new SelectOption(String.valueOf(i), String.valueOf(i)));
        }
        return options;
    }
    
    //Month
    public List<SelectOption> getItems() {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('--Select--','--Select--'));
        options.add(new SelectOption('Jan','January'));
        options.add(new SelectOption('Feb','February'));
        options.add(new SelectOption('Mar','March'));
        options.add(new SelectOption('Apr','April'));
        options.add(new SelectOption('May','May'));
        options.add(new SelectOption('Jun','June'));
        options.add(new SelectOption('Jul','July'));
        options.add(new SelectOption('Aug','August'));
        options.add(new SelectOption('Sep','September'));
        options.add(new SelectOption('Oct','October'));
        options.add(new SelectOption('Nov','November'));
        options.add(new SelectOption('Dec','December'));
        
        
        return options;
    }
    
    public UpdateIncentiveFile() {
        selectedYear = String.valueOf(System.Today().year());
        SelectedMonth = '--Select--';
        System.debug('The value is accstoupload: ' + SelectedMonth + selectedYear );
    }
    
    /***This function reads the CSV file and inserts records into the Incentive__c object. ***/
    public Pagereference ReadFile()
    {
        try{
            //Convert the uploaded file which is in BLOB format into a string
            nameFile =blobToString(contentFile,'ISO-8859-1');
            
            //Now sepatate every row of the excel file
            filelines = nameFile.split('\n');
            
            //Iterate through every line and create a Incentive__c record for each row
            accstoupload = new List<Incentive__c>();
            for (Integer i=1;i<filelines.size();i++)
            {
                String[] inputvalues = new String[]{};
                    inputvalues = filelines[i].split(',');
                
                
                Incentive__c a = new Incentive__c();
                //a.id= listOfId;
                a.Name = inputvalues[0];      
                a.Year__c = selectedYear;
                a.Unique_Record_Key__c = a.Name + a.Year__c;
                
                if (SelectedMonth == 'Jan'){
                    a.January__c = double.valueOf(inputvalues[1]);
                    a.January_SO_Number__c = inputvalues[2];
                }else if(SelectedMonth == 'Feb'){
                    a.February__c = double.valueOf(inputvalues[1]);
                    a.February_SO_Number__c = inputvalues[2];
                }else if(SelectedMonth == 'Mar'){
                    a.March__c = double.valueOf(inputvalues[1]);
                    a.March_SO_Number__c = inputvalues[2];
                }else if(SelectedMonth == 'Apr'){
                    a.April__c = double.valueOf(inputvalues[1]);
                    a.April_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'May'){
                    a.Mei__c = double.valueOf(inputvalues[1]);
                    a.May_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Jun'){
                    a.June__c = double.valueOf(inputvalues[1]);
                    a.June_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Jul'){
                    a.July__c = double.valueOf(inputvalues[1]);
                    a.July_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Aug'){
                    a.August__c = double.valueOf(inputvalues[1]);
                    a.August_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Sep'){
                    a.September__c = double.valueOf(inputvalues[1]);
                    a.September_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Oct'){
                    a.October_del__c = double.valueOf(inputvalues[1]);
                    a.October_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Nov'){
                    a.November__c = double.valueOf(inputvalues[1]);
                    a.November_SO_Number__c = inputvalues[2];
                }else if(SelectedMonth == 'Dec'){
                    a.December__c = double.valueOf(inputvalues[1]);
                    a.December_SO_Number__c = inputvalues[2];
                }

                accstoupload.add(a);
                System.debug('The value is accstoupload: ' + accstoupload);
            }
            Database.upsert(accstoupload, Incentive__c.Unique_Record_Key__c);
        }
        catch(Exception e){
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured reading the CSV file-- '+e.getMessage());
            ApexPages.addMessage(errormsg);
        }       
        //Finally, insert the collected records
        try{
            update accstoupload;
        }
        catch (Exception e)
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured inserting the records'+e.getMessage());
            ApexPages.addMessage(errormsg);
        }    
        return null;
    }
    
    /**** This function sends back to the visualforce page the list of account records that were inserted ****/ 
    public List<Incentive__c> getuploadedAccounts()
    {
        if (accstoupload!= NULL)
            if (accstoupload.size() > 0)
            return accstoupload;
        else
            return null;                    
        else
            return null;
    }

    public static String blobToString(Blob input, String inCharset){
        String hex = EncodingUtil.convertToHex(input);
        System.assertEquals(0, hex.length() & 1);
        final Integer bytesCount = hex.length() >> 1;
        String[] bytes = new String[bytesCount];
        for(Integer i = 0; i < bytesCount; ++i)
            bytes[i] =  hex.mid(i << 1, 2);
        return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
    }
    
}
And this is the code coverage

@IsTest(SeeAllData=true)
public class FileUploaderIncentive_TestMethod {
    static testmethod void testfileupload(){
        StaticResource testdoc = [Select Id,Body from StaticResource where name ='testMethodCSVUpload'];
        FileUploaderIncentive testUpload = new FileUploaderIncentive();
        testUpload.contentFile= testdoc.Body;
        testUpload.ReadFile();
        testUpload.getuploadedAccounts();
    }
    static testmethod void testfileupdate(){
        StaticResource testdoc = [Select Id,Body from StaticResource where name ='testMethodCSVUpload'];
        UpdateIncentiveFile testUpload = new UpdateIncentiveFile();
        testUpload.contentFile= testdoc.Body;
        testUpload.ReadFile();
        testUpload.getuploadedAccounts();
    }
    static testmethod void testfileupdateOption(){
        UpdateIncentiveFile controller = new UpdateIncentiveFile();
        Test.startTest();
        List<SelectOption> options = controller.getYears();
        List<SelectOption> option = controller.getItems();
        Test.stopTest();
        //system.assertNotEquals(null, options, 'The collection should be instantiated');
        //system.assert(!options.isEmpty(), 'The collection should be populated');
    }
}




 
  • February 25, 2022
  • Like
  • 0
Hi, we have created mass upload records using CSV file. but when we upload the file, the owner name will be the one who uploads the CSV. May I know how to make a record owner name based on the name that has in the CSV file? Any code that can refer? 
  • October 08, 2021
  • Like
  • 0
Hi, I need help.
I received the below error
EXCEPTION_THROWN [22]|System.QueryException: unexpected token: s0000014qrPAAQ

Here is the Apex code
public with sharing class toApproved {
    @AuraEnabled(cacheable=true)
    //public static list<ProcessInstanceWorkitem> getItemApprove(){
    public static list<ProcessInstanceWorkitem> getItemApprove(id ActorId){
        id actorid2 = ActorId;
        system.debug('Actor: '+ActorId);
        system.debug('Actor2: '+actorid2);

        String condition = 'ActorId = '+ActorId;
        system.debug('condition: '+condition);

        string query = 'select ProcessInstance.TargetObject.name, CreatedDate, CreatedBy.name, ActorId, Actor.name from ProcessInstanceWorkitem where ' +condition + ' order by CreatedDate limit 100';
        system.debug('query: '+query);

        list<ProcessInstanceWorkitem> records = Database.query(query);
        system.debug('records '+records);

        return records;
    }
}


 
  • January 06, 2023
  • Like
  • 0
Hi, need your help for this error
Illegal assignment from List<SObject> to List<ProcessInstance> (46:31)
public with sharing class ProcessInstance {
    @AuraEnabled(cacheable=true)
    public static List<ProcessInstance> getCases(
        String relatedTo,
        String submittedDate,
        String submittedBy
    ) {
        String query;
        String condition = (String.isNotBlank(relatedTo)
            ? 'TargetObject.name LIKE \'' + '%' + relatedTo + '%\''
            : '');

        condition += (String.isNotBlank(submittedDate)
            ? (String.isNotBlank(condition) ? +' AND ' : '') +
              ' LastModifiedDate LIKE \'' +
              '%' +
              submittedDate +
              '%\''
            : '');

        condition += (String.isNotBlank(submittedBy)
            ? (String.isNotBlank(condition) ? +' AND ' : '') +
              ' SubmittedBy.name LIKE \'' +
              '%' +
              submittedBy +
              '%\''
            : '');

        System.debug('condition ' + condition);
        if (String.isNotBlank(condition)) {
            query =
                'SELECT TargetObject.name,LastModifiedDate,SubmittedBy.name FROM ProcessInstance WHERE ' +
                condition +
                ' ORDER BY LastModifiedDate';
        } else {
            query = 'SELECT TargetObject.name,LastModifiedDate,SubmittedBy.name FROM ProcessInstance ORDER BY LastModifiedDate LIMIT 200';
        }

        List<ProcessInstance> records = Database.query(query);
        return records;
    }
}

 
  • November 23, 2022
  • Like
  • 0
Hi, I have LWC to help users search for products in my org. I need help with apex test code
 
public with sharing class FilterProduct {
    @AuraEnabled(cacheable=true)
    public static List<Product2> getproduct(
        String Name,
        String MaterialCode,
        String productType,

        ){
            String query;
            String condition = (String.isNotBlank(Name)? 'Name LIKE \'' + '%' + Name + '%\'': '');
            condition += (String.isNotBlank(MaterialCode)? (String.isNotBlank(condition) ? +' AND ' : '') +' Material_Code__c LIKE \'' + '%' +MaterialCode +'%\'': '');
            condition += (String.isNotBlank(productType)? (String.isNotBlank(condition) ? +' AND ' : '') +' product_Type__c LIKE \'' + '%' +productType +'%\'': '');
            System.debug('condition ' + condition);

            if (String.isNotBlank(condition)) {
                query =
                    'select name, Material_Code__c, product_Type__c from product2 WHERE ' +condition +' ORDER BY name limit 1000';
            } else {
                query = 'select name, Material_Code__c, product_Type__c from product2 ORDER BY Name LIMIT 200';
            }
    
            List<Product2> records = Database.query(query);
            return records;
        }
}

 
  • November 07, 2022
  • Like
  • 0
Hi, Can help me with the code coverage for this code?
if (SelectedMonth == 'Jan'){
                    a.January__c = double.valueOf(inputvalues[1]);
                    a.January_SO_Number__c = inputvalues[2];
                }else if(SelectedMonth == 'Feb'){
                    a.February__c = double.valueOf(inputvalues[1]);
                    a.February_SO_Number__c = inputvalues[2];
                }else if(SelectedMonth == 'Mar'){
                    a.March__c = double.valueOf(inputvalues[1]);
                    a.March_SO_Number__c = inputvalues[2];
                }else if(SelectedMonth == 'Apr'){
                    a.April__c = double.valueOf(inputvalues[1]);
                    a.April_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'May'){
                    a.Mei__c = double.valueOf(inputvalues[1]);
                    a.May_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Jun'){
                    a.June__c = double.valueOf(inputvalues[1]);
                    a.June_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Jul'){
                    a.July__c = double.valueOf(inputvalues[1]);
                    a.July_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Aug'){
                    a.August__c = double.valueOf(inputvalues[1]);
                    a.August_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Sep'){
                    a.September__c = double.valueOf(inputvalues[1]);
                    a.September_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Oct'){
                    a.October_del__c = double.valueOf(inputvalues[1]);
                    a.October_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Nov'){
                    a.November__c = double.valueOf(inputvalues[1]);
                    a.November_SO_Number__c = inputvalues[2];
                }else if(SelectedMonth == 'Dec'){
                    a.December__c = double.valueOf(inputvalues[1]);
                    a.December_SO_Number__c = inputvalues[2];
                }

User-added imageThis is the full code
 
public class UpdateIncentiveFile {
    
    public string nameFile{get;set;}
    public Blob contentFile{get;set;}
    public String selectedYear {get; set;}
    public String SelectedMonth {get; set;}
    
    String[] filelines = new String[]{};
        List<Incentive__c> accstoupload;
    List<id> listOfId;
    
    //years dropdown
    public List<SelectOption> getYears() {
        List<SelectOption> options = new List<SelectOption>();
        for (Integer i = System.Today().year() - 2; i < System.Today().year() + 3; i++) {
            options.add(new SelectOption(String.valueOf(i), String.valueOf(i)));
        }
        return options;
    }
    
    //Month
    public List<SelectOption> getItems() {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('--Select--','--Select--'));
        options.add(new SelectOption('Jan','January'));
        options.add(new SelectOption('Feb','February'));
        options.add(new SelectOption('Mar','March'));
        options.add(new SelectOption('Apr','April'));
        options.add(new SelectOption('May','May'));
        options.add(new SelectOption('Jun','June'));
        options.add(new SelectOption('Jul','July'));
        options.add(new SelectOption('Aug','August'));
        options.add(new SelectOption('Sep','September'));
        options.add(new SelectOption('Oct','October'));
        options.add(new SelectOption('Nov','November'));
        options.add(new SelectOption('Dec','December'));
        
        
        return options;
    }
    
    public UpdateIncentiveFile() {
        selectedYear = String.valueOf(System.Today().year());
        SelectedMonth = '--Select--';
        System.debug('The value is accstoupload: ' + SelectedMonth + selectedYear );
    }
    
    /***This function reads the CSV file and inserts records into the Incentive__c object. ***/
    public Pagereference ReadFile()
    {
        try{
            //Convert the uploaded file which is in BLOB format into a string
            nameFile =blobToString(contentFile,'ISO-8859-1');
            
            //Now sepatate every row of the excel file
            filelines = nameFile.split('\n');
            
            //Iterate through every line and create a Incentive__c record for each row
            accstoupload = new List<Incentive__c>();
            for (Integer i=1;i<filelines.size();i++)
            {
                String[] inputvalues = new String[]{};
                    inputvalues = filelines[i].split(',');
                
                
                Incentive__c a = new Incentive__c();
                //a.id= listOfId;
                a.Name = inputvalues[0];      
                a.Year__c = selectedYear;
                a.Unique_Record_Key__c = a.Name + a.Year__c;
                
                if (SelectedMonth == 'Jan'){
                    a.January__c = double.valueOf(inputvalues[1]);
                    a.January_SO_Number__c = inputvalues[2];
                }else if(SelectedMonth == 'Feb'){
                    a.February__c = double.valueOf(inputvalues[1]);
                    a.February_SO_Number__c = inputvalues[2];
                }else if(SelectedMonth == 'Mar'){
                    a.March__c = double.valueOf(inputvalues[1]);
                    a.March_SO_Number__c = inputvalues[2];
                }else if(SelectedMonth == 'Apr'){
                    a.April__c = double.valueOf(inputvalues[1]);
                    a.April_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'May'){
                    a.Mei__c = double.valueOf(inputvalues[1]);
                    a.May_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Jun'){
                    a.June__c = double.valueOf(inputvalues[1]);
                    a.June_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Jul'){
                    a.July__c = double.valueOf(inputvalues[1]);
                    a.July_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Aug'){
                    a.August__c = double.valueOf(inputvalues[1]);
                    a.August_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Sep'){
                    a.September__c = double.valueOf(inputvalues[1]);
                    a.September_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Oct'){
                    a.October_del__c = double.valueOf(inputvalues[1]);
                    a.October_SO_Number__c= inputvalues[2];
                }else if(SelectedMonth == 'Nov'){
                    a.November__c = double.valueOf(inputvalues[1]);
                    a.November_SO_Number__c = inputvalues[2];
                }else if(SelectedMonth == 'Dec'){
                    a.December__c = double.valueOf(inputvalues[1]);
                    a.December_SO_Number__c = inputvalues[2];
                }

                accstoupload.add(a);
                System.debug('The value is accstoupload: ' + accstoupload);
            }
            Database.upsert(accstoupload, Incentive__c.Unique_Record_Key__c);
        }
        catch(Exception e){
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured reading the CSV file-- '+e.getMessage());
            ApexPages.addMessage(errormsg);
        }       
        //Finally, insert the collected records
        try{
            update accstoupload;
        }
        catch (Exception e)
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured inserting the records'+e.getMessage());
            ApexPages.addMessage(errormsg);
        }    
        return null;
    }
    
    /**** This function sends back to the visualforce page the list of account records that were inserted ****/ 
    public List<Incentive__c> getuploadedAccounts()
    {
        if (accstoupload!= NULL)
            if (accstoupload.size() > 0)
            return accstoupload;
        else
            return null;                    
        else
            return null;
    }

    public static String blobToString(Blob input, String inCharset){
        String hex = EncodingUtil.convertToHex(input);
        System.assertEquals(0, hex.length() & 1);
        final Integer bytesCount = hex.length() >> 1;
        String[] bytes = new String[bytesCount];
        for(Integer i = 0; i < bytesCount; ++i)
            bytes[i] =  hex.mid(i << 1, 2);
        return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
    }
    
}
And this is the code coverage

@IsTest(SeeAllData=true)
public class FileUploaderIncentive_TestMethod {
    static testmethod void testfileupload(){
        StaticResource testdoc = [Select Id,Body from StaticResource where name ='testMethodCSVUpload'];
        FileUploaderIncentive testUpload = new FileUploaderIncentive();
        testUpload.contentFile= testdoc.Body;
        testUpload.ReadFile();
        testUpload.getuploadedAccounts();
    }
    static testmethod void testfileupdate(){
        StaticResource testdoc = [Select Id,Body from StaticResource where name ='testMethodCSVUpload'];
        UpdateIncentiveFile testUpload = new UpdateIncentiveFile();
        testUpload.contentFile= testdoc.Body;
        testUpload.ReadFile();
        testUpload.getuploadedAccounts();
    }
    static testmethod void testfileupdateOption(){
        UpdateIncentiveFile controller = new UpdateIncentiveFile();
        Test.startTest();
        List<SelectOption> options = controller.getYears();
        List<SelectOption> option = controller.getItems();
        Test.stopTest();
        //system.assertNotEquals(null, options, 'The collection should be instantiated');
        //system.assert(!options.isEmpty(), 'The collection should be populated');
    }
}




 
  • February 25, 2022
  • Like
  • 0