• Sabrina Oliveira 3
  • NEWBIE
  • 110 Points
  • Member since 2021

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 1
    Likes Given
  • 16
    Questions
  • 14
    Replies
I'm facing some problems to format some strings that are coming from an API.

User-added image

What can I do to convert it?
Class:

public with sharing class DocumentsService {
    public class DocumentException extends Exception{}
    
    public static void validateContractDocument(List<Document__c> m_lstObjNew,
        Map<Id, Document__c> m_mapObjOld){
        Map<Id, Document__c> contracts = new Map<Id, Document__c>();
        
        for(Document__c doc : m_lstObjNew){
            if(doc.Contract__c != null)
                contracts.put(doc.Contract__c, doc);
        }        
        List<Document__c> docs = [ select Contract__c from Document__c where Contract__c in: contracts.keyset() ];
        
        for(Document__c item : docs){
            Document__c doc = contracts.get(item.Contract__c);
            doc.addError(new DocumentException('Only 1 contract is allowed'));
        }
    }

}


Test class (0% of coverage):

@isTest
private class DocumentsServiceTest {
    
    @testSetup    
    static void makeData(){
        Account acc = AccountTestBuilder.getBuilder()
            .persist();

        Contract ctrt = ContractTestBuilder.getBuilder()
            .withAccountId(acc.Id)
            .persist();
        
        Document__c doc = DocumentTestBuilder.getBuilder()
            .withContractId(ctrt.Id)
            .persist();
       
    }
    
    @IsTest
    static void methodTest(){ 
        Contract ctrt = [SELECT Id FROM Contract LIMIT 1];
        
        Document__c doc = [SELECT id, Name FROM Document__c LIMIT 1];
        doc.Contract__c = ctrt.Id;
        update doc;
            
        Test.startTest(); 
        Document__c doc2 = DocumentTestBuilder.getBuilder()
            .withContractId(ctrt.Id)
            .persist();
        Test.stopTest();
           
    }
}
 
I've been trying to notify a Record Owner when a new FeedItem is created without having its username marked in the post.
I did this easily through the Process Builder for the Lead object, but for some reason it doesn't work the same for custom objects and from what I googled it's a known issue.

Now I'm trying to do it coding, but I really don't know how to get Record Owner.

My Code:
trigger FeedItemNotification on FeedItem (after insert) {
	List<Pre_Check_Compliance__c> PreCheckIds = new List<Pre_Check_Compliance__c>();
    PreCheckIds = [SELECT Id, OwnerId FROM Pre_Check_Compliance__c];
    Set<String> exstIds = new Set<String>();
    For (Pre_Check_Compliance__c pc : PreCheckIds) {
        exstIds.add(pc.Id);
    }
    
     For(FeedItem item : Trigger.New) {
         Boolean result = exstIds.contains(String.valueOf(item.ParentId));
         if(result = TRUE) {
             CustomNotificationType notificationType = 
            [SELECT Id, DeveloperName 
             FROM CustomNotificationType 
             WHERE DeveloperName='Notificao_Padrao'];
             
             Messaging.CustomNotification notification = new Messaging.CustomNotification();
    
            // Set the contents for the notification
            notification.setTitle('New Chatter post: '+item.Parent);
            notification.setBody('New chatter post has been created.');
    
            // Set the notification type and target
            notification.setNotificationTypeId(notificationType.Id);
            notification.setTargetId(item.ParentId);
             
             try {
                notification.send(item.Parent:Pre_Check_Compliance__c.OwnerId); // How to get Record Owner ID?
            }
            catch (Exception e) {
                System.debug('Problem sending notification: ' + e.getMessage());
            }
         }
    }
}

 
I would like to be notified everytime a new Item is created in the Chatter Feed of that record I'm the owner even if my @ is not tagged. Is it possible? 
Hi, guys!
I have 2 fields that I'd like to use in my VFP.
User-added image
Valores_ativos_e_passivos__c is working fine, but when I try to use Ativos_e_passivos__c I receive the Invalid field for SObject error. What am I missing?

Working FINE:
<table>
                <h4>
                   Ativos e passivos
                </h4> 
                {!KYC_Form__c.Valores_ativos_e_passivos__c}
 </table>

NOT working:
<table>
                <h4>
                   Ativos e passivos
                </h4> 
                {!KYC_Form__c.Ativos_e_passivos__c}
</table>

I've tried "KYC_Form__r.Ativos_e_Passivos__c" but the error still the same. The problem can be the type of the field?
 
When my account is active, only System Administrators and Compliance profiles can edit it.
The problem is that Controller needs to be able to edit some fields (Letters, Charge and Statement), but not all of them as the System Administrator and Compliance.
I'm stucked on this. Can you help me?

Validation rule:
(NOT(
$Profile.Name = 'System Administrator' ||
CONTAINS($Profile.Name, 'Compliance')
)
&&
ISPICKVAL(Status__c,'Active')
&& LastModifiedDate <> NOW()
&& not(ISCHANGED(Active__c)))
||
(NOT($Profile.Name = 'Controller') 
&&
ISPICKVAL(Status__c,'Active')
&& LastModifiedDate <> NOW()
&& not(ISCHANGED(Letters__c))
&& not(ISCHANGED(Charge__c))
&& not(ISCHANGED(Statement__c)))

 
Hi, guys!
I've created a "Retrieve" button in my object to return the Status value to the one before the one I am right now.

For example:
Status: Returned - Open - Starting - Writing - Completing - Closed
If I am at Writing and I need to go to the Returned, I'd like to go back to Writing after that just clicking the button.
It's working, the problem is that sometimes it updates to the Starting for example.
I can't understand why this happens and why this happens only sometimes. 
It is not a problem of permission or session, because I'm testing with Admin 

My code:
@AuraEnabled    
    public static String updateRecordAfterReturned(Id recordId){
        if (bankaccRcd == null){
            bankaccRcd = [SELECT Id, Status__c, Observations__c FROM Bank_Account_Request__c WHere Id =: recordId];    
        }
        try {
            List<Bank_Account_Request__History> bar = new List<Bank_Account_Request__History>();
            bar = [SELECT ParentId, OldValue, NewValue, Field, CreatedById, CreatedDate FROM Bank_Account_Request__History 
                   WHERE ParentId = :recordId and Field = 'Status__c' LIMIT 1]; 
            bankaccRcd.Status__c = String.valueOf(bar[0].OldValue);
            update bankaccRcd;    
            return 'Success';
        }catch (DmlException e){
            Return 'Error: '+e.getMessage();
        }
        
    }
 
I have this method:
@AuraEnabled    
    public static String updateRecordReturned(Id recordId){
        if (bankaccRcd == null){
            bankaccRcd = [SELECT Id, Status__c, Observations__c FROM Bank_Account_Request__c WHere Id =: recordId];    
        }
        try {
            String stt = bankaccRcd.Status__c; // that's the value I'd like to get to the following method.
            bankaccRcd.Status__c = 'Devolvido';
            update bankaccRcd;    
            FeedItem post = new FeedItem();
            post.Body = 'Devolution: '+bankaccRcd.Observations__c;
            post.ParentId = bankaccRcd.Id;
            insert post;
            return 'Success';
        }catch (DmlException e){
            Return 'Error: '+e.getMessage();
        }
        
    }


I'd like to get the bold value above to another method:

@AuraEnabled    
    public static String updateRecordAfterReturned(Id recordId){
        if (bankaccRcd == null){
            bankaccRcd = [SELECT Id, Status__c, Observations__c FROM Bank_Account_Request__c WHere Id =: recordId];    
        }
        try {
            bankaccRcd.Status__c = stt; // here is where I'd like to get the value above.
            update bankaccRcd;    
            return 'Success';
        }catch (DmlException e){
            Return 'Error: '+e.getMessage();
        }
        
    }

Is it possible?
 
My class:
public class getAccount {
	@AuraEnabled 
    public static Account getAcct(Id accountId){
        return (Account) Database.query( ' SELECT Name, Observations__c FROM Account WHERE Id =: accountId LIMIT 1 ' )[0];
    }

    @AuraEnabled 
    public static Account saveAcct(Account act){
        upsert act;
        return act;
    }  
}

My class test:
public class getAccountTest {
    
    @TestSetup
    static void dataSetup(){
        Account acc = new Account();
        acc.Name = 'Testing';
        acc.Status__c = 'Active';
        acc.Observations__c = 'teste';
        insert acc;
    }
    
    static testmethod void getAccountTestMethod() {
            Test.StartTest();
            getAccount instancevar = new getAccount();
            Test.StopTest(); 
        
        	List<Account> accResult = [SELECT Id FROM Account WHERE Name = 'Testing' ];
        
        	System.assertEquals(1, accResult.size() , 'Not created account');
	}

}

But I'm receiving 0% of coverage. What am I missing?
I'm using a Lightning Component to update a field called "Observations__c" in Account Object.
User-added image

It's working fine, but when I try to use it inside another component, I receive the following error:

EXCEPTION_THROWN [9]|System.NullPointerException: Attempted to upsert a null list

Component: 

<aura:component implements="force:lightningQuickActionWithoutHeader,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" controller="getAccount">

<aura:handler name="init" action="{!c.init}" value="{!this}" />
<aura:attribute name="accounts" type="Account" />
<aura:attribute name="recordId" type="Id" />

<ltng:require styles="/resource/slds103/assets/styles/salesforce-lightning-design-system.min.css"/>

 <form>
    <ui:inputText aura:id="client"
                  label="{!$ObjectType.Account.fields.Observations__c.Label}"
                  class="form-control"
                  value="{!v.accounts.Observations__c}"
                  placeholder="Insira, caso necessário, comentários adicionais"
    />
    <br />
    <ui:button class="form-control" aura:id="button" label="Anexar observação" press="{!c.save}"/>
</form>

 </aura:component>

Controller js:
({
init : function(component, event, helper) {
    var accId = component.get("v.recordId");
    var action = component.get("c.getAcct");

    action.setParams({
        "accountId": component.get("v.recordId")
    });

    action.setCallback(this, function(data) {
        component.set("v.accounts", data.getReturnValue());
    });

    $A.enqueueAction(action);
}, 
save : function(component, event, helper) {

    var action = component.get("c.saveAcct");
    var accounts = component.get("v.accounts");

    action.setParams({"act": accounts});
    $A.enqueueAction(action);

    console.log('save ran');

}
})

Apex Controller:
public class getAccount {
    @AuraEnabled 
    public static Account getAcct(Id accountId){
        return (Account) Database.query( ' SELECT Name, Observations__c FROM Account WHERE Id =: accountId LIMIT 1 ' )[0];
    }

    @AuraEnabled 
    public static Account saveAcct(Account act){
        upsert act;
        return act;
    }  
}

I'm calling <c:sparkAccount/> in my second component, but it is not working.
User-added image

What am I doing wrong? 
I'm creating a simple VFP to render as PDF and I would like to get some picklist fields. The problem is that I'm getting the API Name and not the label value. There's a way to do it using only VFP?

Example of how I'm doing:
Status: <br/>{!CPRMinutes__c.Status__c}
I have the Account object and the Especial Notes object.

I'd like do create a rule capable to manager the visualization of Especial Notes based on Account.

If I'm Account Owner, I would like to be capable to read all Especial Notes related to that Account whether I'm the owner of the Especial Note or not.

Is it possible?
Hi! I'm calling this class in a process builder. When the "Form" record reaches the approved status, an "Opportunity" is automatically created in the "Account". The question is: I need to automatically fill the Opportunity "Fee__c" field with the same value filled in the "Form". However, I am getting the error "Variable does not exist" on line 18 when I try to assign the value. The field exists and I cannot understand why I am getting this error. What am I missing?

public class Step1 {
    @invocablemethod(label='Step I')
    public static void CreateOpportunity(List<Id> recordId){
        List<Account> accs                         = new List<Account>();
        List<Opportunity> opps                      = new List<Opportunity>();  
        Form__c[] kycs = [Select ID, Fee__c FROM Form__c WHERE Contact__r.AccountId = :recordId ORDER BY LastModifiedDate DESC LIMIT 1];

        Map<Id, OpportunityData> listAccounts     = Opportunities(recordId);                
                 
        for(id item : listAccounts.keyset()){
            OpportunityData oppData = listAccounts.get(item);
            if(oppData.create){
                accs.add(new Account(Id = item, Step_I__c = true));
                opps.add(new Opportunity(Name        = oppData.accountName, 
                                         AccountId = item, 
                                         StageName = 'Qualification',
                                         CloseDate = date.today().addMonths(12),
                                         Fee__c = kycs.Fee__c));
            }
            else
                accs.add(new Account(Id = item, Step_I__c = false));
        }   
        update accs;
        insert opps;        
    }  
Hello,
I have 2 parents record types (Contact):
  • Physical Person
  • Juridical Person
My child object (Form) has 4 record types:
  • Physical Pre Form
  • Physical Form
  • Juridical Pre Form
  • Juridical Form
When I create a new Form using the related list button "New" is it possible to display only Physical Pre Form and Physical Form options if my Contact is a Physical Person?

I'm using a validation rule, but it's a big form and users will only get the notification that are filling out the wrong form when they save, after all the filling work.
It is the first time that I write test classes and it is being a bit complicated. With these test classes I am only getting coverage for the beginning part of the batch.

Class 1:
global class Manage_Documents_RM implements
    Database.Batchable<sObject>, Database.Stateful, Database.AllowsCallouts {
    global Database.QueryLocator start(Database.BatchableContext bc) {
        String query = 'SELECT Account__c, Contract__c, ExpeditionDate__c, ExpirationDate__c, Contact__c, OwnerId, Id FROM Document__c WHERE ExpirationDate__c > LAST_N_DAYS:60 OR ExpirationDate__c < TODAY';
        return Database.getQueryLocator(query);
    }
        
   
    global void execute(Database.BatchableContext bc, List<Document__c> scope){
        date deadline1 = date.today().addDays(60);
        date deadline2 = date.today().addDays(30);
        date deadline3 = date.today().addDays(15);
        List<Task> newTask = new List<Task>();
        
     	Set<String> myIds =  new Set<String>(); 
        Task[] cList = [Select ID, Subject, WhatId FROM Task WHERE Subject = 'Update Due Date' AND Status = 'Open'];
		Set<String> exstIds = new Set<String>();
        
        for(Task c : cList) {
            exstIds.add(c.WhatId);
        }
        
        for (Document__c document : scope) {
            if(document.ExpirationDate__c <= deadline1 || document.ExpirationDate__c <= deadline2 || document.ExpirationDate__c <= deadline3) {
                Task tsk = new Task();  
                tsk.RecordTypeId = SObjectType.Task.getRecordTypeInfosByDeveloperName().get('CallReport').getRecordTypeId();
                tsk.WhatId = document.Id;
                tsk.Subject = 'Update Due Date';                
                tsk.Status = 'Open';
                tsk.Priority = 'Normal';
                tsk.OwnerId = document.OwnerId;
                tsk.ActivityDate = document.ExpirationDate__c;
                
                if(exstIds.isEmpty() || !exstIds.Contains(document.Id)) { 
                    newTask.add(tsk);
                } 
                
            }
        }
        insert newTask;
    }
    global void finish(Database.BatchableContext bc){
       
    }
}
Test Class 1:
@isTest
public class Manage_Documents_RM_Test {
    static testmethod void ManageDocumentsRMTestMethod(){
        Task tsk = new Task(Subject='Teste', Status='Open');
		insert tsk;
		Manage_Documents_RM a = new Manage_Documents_RM();
		Database.executeBatch(a);
	}
}

Class 2:
global class SendEmailToOwnerTask implements Database.Batchable<sObject>  {
    Map<string,List<Task>> userEmailTasklistmap = new Map<string,List<Task>>();
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([SELECT ID, CreatedDate, What.Id, What.Name, Owner.Email, OwnerId, Owner.Name, Status, ActivityDate, Subject from Task WHERE Status != 'Completed' and Owner.IsActive = true]);
    }
    
    global void execute(Database.BatchableContext BC, List<Task> scope){
        for(Task Tsk : scope){
            if(!userEmailTasklistmap.Containskey(tsk.Owner.Email)){
                userEmailTasklistmap.put(tsk.Owner.Email, new List<Task>());
            }
            userEmailTasklistmap.get(tsk.Owner.Email).add(tsk);
            
          }  
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    
            for(string email : userEmailTasklistmap.keyset()){
                
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                list<string> toAddresses = new list<string>();
                toAddresses.add(email);
                mail.setToAddresses(toAddresses);
                mail.setSubject('Tarefas em aberto');                
                String username = userEmailTasklistmap.get(email)[0].Owner.Name;
                String htmlBody = '';
                
                htmlBody = '<body style="height: auto; min-height: auto; font-family: Arial, sans-serif; font-style: normal; font-weight: normal; font-size: 14px; line-height: 16px;">'+
                    +'<style type="text/css">p {margin: 0 0 15px;}</style>'+
                    +'<div style="max-width: 550px; width: 100%; margin: 0 auto;">'+
                    +'<div style="background: #001489; padding: 50px 0; text-align: center;"><img alt="ab" src="logo.png" style="width: 200px; height: 60px; display: inline-block;" title="AB" /></div>'+
                    +'<div style="padding: 45px 35px; background: #fff;">'+
                    +'<p style="font-weight: bold; font-size: 24px; line-height: 28px; margin-bottom: 15px;">Tarefas em aberto</p></div>'+
                    +'Hey, ' + username + '! Check these open Tasks.<br/><br/>';
 
                for(Task tsk : userEmailTasklistmap.get(email)){
                    
                    String duedate = '';
                    if (tsk.ActivityDate != null)
                        duedate = tsk.ActivityDate.format();                    
                    else
                        duedate = '';
                    String Subject = tsk.subject;
                    String wn = tsk.what.name;
                    string what = tsk.what.id;
                    string link = URL.getSalesforceBaseUrl().toExternalForm()+'/'+ tsk.id;
                    htmlBody += 'Subject: ' + Subject + '<br/>Document: ' + wn + '<br/>Due Date: ' + duedate + '<br/>Link: ' + link + '<br/><br/>';                    
                }
                 String label = Label.Mensagem_MarginEmail;
                 htmlBody += '<div style="border-top: 9px solid #001489; background: #fff; padding: 15px 35px;">'+
                     		+'<p style="font-size: 9px; text-align: center; line-height: 10px; color: #5B5B5B; margin: 0;">'+ label +'</p></div>'+
                     		+'<div style="padding: 25px 0;">'+
        					+'<p style="font-size: 9px; line-height: 10px; text-align: center; color: #141C4B;">De: <a href="" style="font-size: 9px; line-height: 10px; text-align: center; color: #141C4B; text-decoration: underline;">Salesforce</a></p>'+
        					+'</div></div></body>';
                 mail.sethtmlBody(htmlBody);
                 mails.add(mail);                    
            }
             if(mails.size()>0)
             Messaging.sendEmail(mails);
    }
    global void finish(Database.BatchableContext BC){        
    }
}

User-added image
 
I created a class scheduled to run once a week to let task owners know which tasks are open for them.
I am trying to compose the body of the email only with the open tasks of that specific user. With what I have so far, I am composing the email with all open tasks for all users. How can I do this?
public EmailTasksWeekly() {
        Map<Id, List<Task>> tasksByUser = new Map<Id, List<Task>>();
    for(Task taskRecord: [SELECT OwnerId, Id, Status, Subject, What.Name, ActivityDate FROM Task WHERE 
                          IsClosed = false AND Owner.IsActive = true]) {
        List<Task> userTasks = tasksByUser.get(taskRecord.OwnerId);
        if(userTasks == null) {
            tasksByUser.put(taskRecord.OwnerId, userTasks = new List<Task>());
        }
                              
        userTasks.add(taskRecord);
    }
tasks = [Select ID, OwnerId, Status, Subject, What.Name, ActivityDate FROM Task WHERE 
                 Status = 'Open' AND OwnerId = :tasksByUser.keySet()];
        }

 
I'm using a Lightning Component to update a field called "Observations__c" in Account Object.
User-added image

It's working fine, but when I try to use it inside another component, I receive the following error:

EXCEPTION_THROWN [9]|System.NullPointerException: Attempted to upsert a null list

Component: 

<aura:component implements="force:lightningQuickActionWithoutHeader,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" controller="getAccount">

<aura:handler name="init" action="{!c.init}" value="{!this}" />
<aura:attribute name="accounts" type="Account" />
<aura:attribute name="recordId" type="Id" />

<ltng:require styles="/resource/slds103/assets/styles/salesforce-lightning-design-system.min.css"/>

 <form>
    <ui:inputText aura:id="client"
                  label="{!$ObjectType.Account.fields.Observations__c.Label}"
                  class="form-control"
                  value="{!v.accounts.Observations__c}"
                  placeholder="Insira, caso necessário, comentários adicionais"
    />
    <br />
    <ui:button class="form-control" aura:id="button" label="Anexar observação" press="{!c.save}"/>
</form>

 </aura:component>

Controller js:
({
init : function(component, event, helper) {
    var accId = component.get("v.recordId");
    var action = component.get("c.getAcct");

    action.setParams({
        "accountId": component.get("v.recordId")
    });

    action.setCallback(this, function(data) {
        component.set("v.accounts", data.getReturnValue());
    });

    $A.enqueueAction(action);
}, 
save : function(component, event, helper) {

    var action = component.get("c.saveAcct");
    var accounts = component.get("v.accounts");

    action.setParams({"act": accounts});
    $A.enqueueAction(action);

    console.log('save ran');

}
})

Apex Controller:
public class getAccount {
    @AuraEnabled 
    public static Account getAcct(Id accountId){
        return (Account) Database.query( ' SELECT Name, Observations__c FROM Account WHERE Id =: accountId LIMIT 1 ' )[0];
    }

    @AuraEnabled 
    public static Account saveAcct(Account act){
        upsert act;
        return act;
    }  
}

I'm calling <c:sparkAccount/> in my second component, but it is not working.
User-added image

What am I doing wrong? 
I'm facing some problems to format some strings that are coming from an API.

User-added image

What can I do to convert it?
I've been trying to notify a Record Owner when a new FeedItem is created without having its username marked in the post.
I did this easily through the Process Builder for the Lead object, but for some reason it doesn't work the same for custom objects and from what I googled it's a known issue.

Now I'm trying to do it coding, but I really don't know how to get Record Owner.

My Code:
trigger FeedItemNotification on FeedItem (after insert) {
	List<Pre_Check_Compliance__c> PreCheckIds = new List<Pre_Check_Compliance__c>();
    PreCheckIds = [SELECT Id, OwnerId FROM Pre_Check_Compliance__c];
    Set<String> exstIds = new Set<String>();
    For (Pre_Check_Compliance__c pc : PreCheckIds) {
        exstIds.add(pc.Id);
    }
    
     For(FeedItem item : Trigger.New) {
         Boolean result = exstIds.contains(String.valueOf(item.ParentId));
         if(result = TRUE) {
             CustomNotificationType notificationType = 
            [SELECT Id, DeveloperName 
             FROM CustomNotificationType 
             WHERE DeveloperName='Notificao_Padrao'];
             
             Messaging.CustomNotification notification = new Messaging.CustomNotification();
    
            // Set the contents for the notification
            notification.setTitle('New Chatter post: '+item.Parent);
            notification.setBody('New chatter post has been created.');
    
            // Set the notification type and target
            notification.setNotificationTypeId(notificationType.Id);
            notification.setTargetId(item.ParentId);
             
             try {
                notification.send(item.Parent:Pre_Check_Compliance__c.OwnerId); // How to get Record Owner ID?
            }
            catch (Exception e) {
                System.debug('Problem sending notification: ' + e.getMessage());
            }
         }
    }
}

 
Hi, guys!
I have 2 fields that I'd like to use in my VFP.
User-added image
Valores_ativos_e_passivos__c is working fine, but when I try to use Ativos_e_passivos__c I receive the Invalid field for SObject error. What am I missing?

Working FINE:
<table>
                <h4>
                   Ativos e passivos
                </h4> 
                {!KYC_Form__c.Valores_ativos_e_passivos__c}
 </table>

NOT working:
<table>
                <h4>
                   Ativos e passivos
                </h4> 
                {!KYC_Form__c.Ativos_e_passivos__c}
</table>

I've tried "KYC_Form__r.Ativos_e_Passivos__c" but the error still the same. The problem can be the type of the field?
 
When my account is active, only System Administrators and Compliance profiles can edit it.
The problem is that Controller needs to be able to edit some fields (Letters, Charge and Statement), but not all of them as the System Administrator and Compliance.
I'm stucked on this. Can you help me?

Validation rule:
(NOT(
$Profile.Name = 'System Administrator' ||
CONTAINS($Profile.Name, 'Compliance')
)
&&
ISPICKVAL(Status__c,'Active')
&& LastModifiedDate <> NOW()
&& not(ISCHANGED(Active__c)))
||
(NOT($Profile.Name = 'Controller') 
&&
ISPICKVAL(Status__c,'Active')
&& LastModifiedDate <> NOW()
&& not(ISCHANGED(Letters__c))
&& not(ISCHANGED(Charge__c))
&& not(ISCHANGED(Statement__c)))

 
I have this method:
@AuraEnabled    
    public static String updateRecordReturned(Id recordId){
        if (bankaccRcd == null){
            bankaccRcd = [SELECT Id, Status__c, Observations__c FROM Bank_Account_Request__c WHere Id =: recordId];    
        }
        try {
            String stt = bankaccRcd.Status__c; // that's the value I'd like to get to the following method.
            bankaccRcd.Status__c = 'Devolvido';
            update bankaccRcd;    
            FeedItem post = new FeedItem();
            post.Body = 'Devolution: '+bankaccRcd.Observations__c;
            post.ParentId = bankaccRcd.Id;
            insert post;
            return 'Success';
        }catch (DmlException e){
            Return 'Error: '+e.getMessage();
        }
        
    }


I'd like to get the bold value above to another method:

@AuraEnabled    
    public static String updateRecordAfterReturned(Id recordId){
        if (bankaccRcd == null){
            bankaccRcd = [SELECT Id, Status__c, Observations__c FROM Bank_Account_Request__c WHere Id =: recordId];    
        }
        try {
            bankaccRcd.Status__c = stt; // here is where I'd like to get the value above.
            update bankaccRcd;    
            return 'Success';
        }catch (DmlException e){
            Return 'Error: '+e.getMessage();
        }
        
    }

Is it possible?
 
My class:
public class getAccount {
	@AuraEnabled 
    public static Account getAcct(Id accountId){
        return (Account) Database.query( ' SELECT Name, Observations__c FROM Account WHERE Id =: accountId LIMIT 1 ' )[0];
    }

    @AuraEnabled 
    public static Account saveAcct(Account act){
        upsert act;
        return act;
    }  
}

My class test:
public class getAccountTest {
    
    @TestSetup
    static void dataSetup(){
        Account acc = new Account();
        acc.Name = 'Testing';
        acc.Status__c = 'Active';
        acc.Observations__c = 'teste';
        insert acc;
    }
    
    static testmethod void getAccountTestMethod() {
            Test.StartTest();
            getAccount instancevar = new getAccount();
            Test.StopTest(); 
        
        	List<Account> accResult = [SELECT Id FROM Account WHERE Name = 'Testing' ];
        
        	System.assertEquals(1, accResult.size() , 'Not created account');
	}

}

But I'm receiving 0% of coverage. What am I missing?
I'm using a Lightning Component to update a field called "Observations__c" in Account Object.
User-added image

It's working fine, but when I try to use it inside another component, I receive the following error:

EXCEPTION_THROWN [9]|System.NullPointerException: Attempted to upsert a null list

Component: 

<aura:component implements="force:lightningQuickActionWithoutHeader,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" controller="getAccount">

<aura:handler name="init" action="{!c.init}" value="{!this}" />
<aura:attribute name="accounts" type="Account" />
<aura:attribute name="recordId" type="Id" />

<ltng:require styles="/resource/slds103/assets/styles/salesforce-lightning-design-system.min.css"/>

 <form>
    <ui:inputText aura:id="client"
                  label="{!$ObjectType.Account.fields.Observations__c.Label}"
                  class="form-control"
                  value="{!v.accounts.Observations__c}"
                  placeholder="Insira, caso necessário, comentários adicionais"
    />
    <br />
    <ui:button class="form-control" aura:id="button" label="Anexar observação" press="{!c.save}"/>
</form>

 </aura:component>

Controller js:
({
init : function(component, event, helper) {
    var accId = component.get("v.recordId");
    var action = component.get("c.getAcct");

    action.setParams({
        "accountId": component.get("v.recordId")
    });

    action.setCallback(this, function(data) {
        component.set("v.accounts", data.getReturnValue());
    });

    $A.enqueueAction(action);
}, 
save : function(component, event, helper) {

    var action = component.get("c.saveAcct");
    var accounts = component.get("v.accounts");

    action.setParams({"act": accounts});
    $A.enqueueAction(action);

    console.log('save ran');

}
})

Apex Controller:
public class getAccount {
    @AuraEnabled 
    public static Account getAcct(Id accountId){
        return (Account) Database.query( ' SELECT Name, Observations__c FROM Account WHERE Id =: accountId LIMIT 1 ' )[0];
    }

    @AuraEnabled 
    public static Account saveAcct(Account act){
        upsert act;
        return act;
    }  
}

I'm calling <c:sparkAccount/> in my second component, but it is not working.
User-added image

What am I doing wrong? 
I'm creating a simple VFP to render as PDF and I would like to get some picklist fields. The problem is that I'm getting the API Name and not the label value. There's a way to do it using only VFP?

Example of how I'm doing:
Status: <br/>{!CPRMinutes__c.Status__c}
Hi! I'm calling this class in a process builder. When the "Form" record reaches the approved status, an "Opportunity" is automatically created in the "Account". The question is: I need to automatically fill the Opportunity "Fee__c" field with the same value filled in the "Form". However, I am getting the error "Variable does not exist" on line 18 when I try to assign the value. The field exists and I cannot understand why I am getting this error. What am I missing?

public class Step1 {
    @invocablemethod(label='Step I')
    public static void CreateOpportunity(List<Id> recordId){
        List<Account> accs                         = new List<Account>();
        List<Opportunity> opps                      = new List<Opportunity>();  
        Form__c[] kycs = [Select ID, Fee__c FROM Form__c WHERE Contact__r.AccountId = :recordId ORDER BY LastModifiedDate DESC LIMIT 1];

        Map<Id, OpportunityData> listAccounts     = Opportunities(recordId);                
                 
        for(id item : listAccounts.keyset()){
            OpportunityData oppData = listAccounts.get(item);
            if(oppData.create){
                accs.add(new Account(Id = item, Step_I__c = true));
                opps.add(new Opportunity(Name        = oppData.accountName, 
                                         AccountId = item, 
                                         StageName = 'Qualification',
                                         CloseDate = date.today().addMonths(12),
                                         Fee__c = kycs.Fee__c));
            }
            else
                accs.add(new Account(Id = item, Step_I__c = false));
        }   
        update accs;
        insert opps;        
    }  
It is the first time that I write test classes and it is being a bit complicated. With these test classes I am only getting coverage for the beginning part of the batch.

Class 1:
global class Manage_Documents_RM implements
    Database.Batchable<sObject>, Database.Stateful, Database.AllowsCallouts {
    global Database.QueryLocator start(Database.BatchableContext bc) {
        String query = 'SELECT Account__c, Contract__c, ExpeditionDate__c, ExpirationDate__c, Contact__c, OwnerId, Id FROM Document__c WHERE ExpirationDate__c > LAST_N_DAYS:60 OR ExpirationDate__c < TODAY';
        return Database.getQueryLocator(query);
    }
        
   
    global void execute(Database.BatchableContext bc, List<Document__c> scope){
        date deadline1 = date.today().addDays(60);
        date deadline2 = date.today().addDays(30);
        date deadline3 = date.today().addDays(15);
        List<Task> newTask = new List<Task>();
        
     	Set<String> myIds =  new Set<String>(); 
        Task[] cList = [Select ID, Subject, WhatId FROM Task WHERE Subject = 'Update Due Date' AND Status = 'Open'];
		Set<String> exstIds = new Set<String>();
        
        for(Task c : cList) {
            exstIds.add(c.WhatId);
        }
        
        for (Document__c document : scope) {
            if(document.ExpirationDate__c <= deadline1 || document.ExpirationDate__c <= deadline2 || document.ExpirationDate__c <= deadline3) {
                Task tsk = new Task();  
                tsk.RecordTypeId = SObjectType.Task.getRecordTypeInfosByDeveloperName().get('CallReport').getRecordTypeId();
                tsk.WhatId = document.Id;
                tsk.Subject = 'Update Due Date';                
                tsk.Status = 'Open';
                tsk.Priority = 'Normal';
                tsk.OwnerId = document.OwnerId;
                tsk.ActivityDate = document.ExpirationDate__c;
                
                if(exstIds.isEmpty() || !exstIds.Contains(document.Id)) { 
                    newTask.add(tsk);
                } 
                
            }
        }
        insert newTask;
    }
    global void finish(Database.BatchableContext bc){
       
    }
}
Test Class 1:
@isTest
public class Manage_Documents_RM_Test {
    static testmethod void ManageDocumentsRMTestMethod(){
        Task tsk = new Task(Subject='Teste', Status='Open');
		insert tsk;
		Manage_Documents_RM a = new Manage_Documents_RM();
		Database.executeBatch(a);
	}
}

Class 2:
global class SendEmailToOwnerTask implements Database.Batchable<sObject>  {
    Map<string,List<Task>> userEmailTasklistmap = new Map<string,List<Task>>();
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([SELECT ID, CreatedDate, What.Id, What.Name, Owner.Email, OwnerId, Owner.Name, Status, ActivityDate, Subject from Task WHERE Status != 'Completed' and Owner.IsActive = true]);
    }
    
    global void execute(Database.BatchableContext BC, List<Task> scope){
        for(Task Tsk : scope){
            if(!userEmailTasklistmap.Containskey(tsk.Owner.Email)){
                userEmailTasklistmap.put(tsk.Owner.Email, new List<Task>());
            }
            userEmailTasklistmap.get(tsk.Owner.Email).add(tsk);
            
          }  
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    
            for(string email : userEmailTasklistmap.keyset()){
                
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                list<string> toAddresses = new list<string>();
                toAddresses.add(email);
                mail.setToAddresses(toAddresses);
                mail.setSubject('Tarefas em aberto');                
                String username = userEmailTasklistmap.get(email)[0].Owner.Name;
                String htmlBody = '';
                
                htmlBody = '<body style="height: auto; min-height: auto; font-family: Arial, sans-serif; font-style: normal; font-weight: normal; font-size: 14px; line-height: 16px;">'+
                    +'<style type="text/css">p {margin: 0 0 15px;}</style>'+
                    +'<div style="max-width: 550px; width: 100%; margin: 0 auto;">'+
                    +'<div style="background: #001489; padding: 50px 0; text-align: center;"><img alt="ab" src="logo.png" style="width: 200px; height: 60px; display: inline-block;" title="AB" /></div>'+
                    +'<div style="padding: 45px 35px; background: #fff;">'+
                    +'<p style="font-weight: bold; font-size: 24px; line-height: 28px; margin-bottom: 15px;">Tarefas em aberto</p></div>'+
                    +'Hey, ' + username + '! Check these open Tasks.<br/><br/>';
 
                for(Task tsk : userEmailTasklistmap.get(email)){
                    
                    String duedate = '';
                    if (tsk.ActivityDate != null)
                        duedate = tsk.ActivityDate.format();                    
                    else
                        duedate = '';
                    String Subject = tsk.subject;
                    String wn = tsk.what.name;
                    string what = tsk.what.id;
                    string link = URL.getSalesforceBaseUrl().toExternalForm()+'/'+ tsk.id;
                    htmlBody += 'Subject: ' + Subject + '<br/>Document: ' + wn + '<br/>Due Date: ' + duedate + '<br/>Link: ' + link + '<br/><br/>';                    
                }
                 String label = Label.Mensagem_MarginEmail;
                 htmlBody += '<div style="border-top: 9px solid #001489; background: #fff; padding: 15px 35px;">'+
                     		+'<p style="font-size: 9px; text-align: center; line-height: 10px; color: #5B5B5B; margin: 0;">'+ label +'</p></div>'+
                     		+'<div style="padding: 25px 0;">'+
        					+'<p style="font-size: 9px; line-height: 10px; text-align: center; color: #141C4B;">De: <a href="" style="font-size: 9px; line-height: 10px; text-align: center; color: #141C4B; text-decoration: underline;">Salesforce</a></p>'+
        					+'</div></div></body>';
                 mail.sethtmlBody(htmlBody);
                 mails.add(mail);                    
            }
             if(mails.size()>0)
             Messaging.sendEmail(mails);
    }
    global void finish(Database.BatchableContext BC){        
    }
}

User-added image
 
I created a class scheduled to run once a week to let task owners know which tasks are open for them.
I am trying to compose the body of the email only with the open tasks of that specific user. With what I have so far, I am composing the email with all open tasks for all users. How can I do this?
public EmailTasksWeekly() {
        Map<Id, List<Task>> tasksByUser = new Map<Id, List<Task>>();
    for(Task taskRecord: [SELECT OwnerId, Id, Status, Subject, What.Name, ActivityDate FROM Task WHERE 
                          IsClosed = false AND Owner.IsActive = true]) {
        List<Task> userTasks = tasksByUser.get(taskRecord.OwnerId);
        if(userTasks == null) {
            tasksByUser.put(taskRecord.OwnerId, userTasks = new List<Task>());
        }
                              
        userTasks.add(taskRecord);
    }
tasks = [Select ID, OwnerId, Status, Subject, What.Name, ActivityDate FROM Task WHERE 
                 Status = 'Open' AND OwnerId = :tasksByUser.keySet()];
        }

 
I am trying to pull picklist values in to my component using schema and its methods. I am getting all the values through server controller, but in my component labels are not populating but it is showing picklist structure.

Lightning Component:

<aura:component controller="PickListController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <aura:attribute name="aname" type="Account" default="{'sObjectType':'Account'}"/>
    <aura:attribute name="picvalue" type="List"/>
   <aura:handler name="init" value="{!this}" action="{!c.doInit}" /> 
        <lightning:input label="Enter Your Name: " value="{!v.aname.Name}"/>
        <lightning:input label="Phone Number: " value="{!v.aname.Phone}"/>
       <lightning:select value="{!v.aname.Rating}" label="Rating">       
            <option value="choose">Choose one...</option> 
            <aura:iteration items="{!v.picvalue}" var="s">
                <option value="{!s.value}"/>             
            </aura:iteration> 
        </lightning:select> 
    <lightning:button label="Submit" onclick="{!c.go}"/>
</aura:component>

Js:

({
    doInit : function(component) {        
        var pickvar = component.get("c.getPickListValuesIntoList");
        pickvar.setCallback(this, function(response) {
            var state = response.getState();
            if(state === 'SUCCESS'){
                var list = response.getReturnValue();
                component.set("v.picvalue", list);
            }
            else if(state === 'ERROR'){
                //var list = response.getReturnValue();
                //component.set("v.picvalue", list);
                alert('ERROR OCCURED.');
            }
        })
        $A.enqueueAction(pickvar);
    },
    go : function(component){
        var cvar = component.get("v.aname");
        var action = component.get("c.insertValues");
        action.setParams({acc: cvar});
        action.setCallback(this, function(response) {
            var state = response.getState();
            if(state === 'SUCCESS'){
            var list1 = response.getReturnValue();
            //component.set("v.picklistValues", list);
            alert('Record Created Successfully '+list1);
            }
            else if(state === 'INCOMPLETE'){
                alert('Something is missing');   
            }
            else if(state === 'ERROR'){
                alert('Insertion Failed');   
            }
        })
        $A.enqueueAction(action);
    }
})

Server Controller:

public class PickListController {
    @AuraEnabled        
    public static List<String> getPickListValuesIntoList(){
        List<String> pickListValuesList = new List<String>();
        Schema.DescribeFieldResult fieldResult = Account.Rating.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for( Schema.PicklistEntry pickListVal : ple){
            pickListValuesList.add(pickListVal.getLabel());
            System.debug('Values in Rating are: '+pickListValuesList);
        }     
        return pickListValuesList;
    }
    @AuraEnabled        
    public static Id insertValues(Account acc){
        insert acc;   
        return acc.id;
    }
}

User-added image