# Trigger를 사용한 청구서 자동 이메일 전송

* Quote 개체 Status 값이 Accepted가 되었을 때 함수를 호출하는 예제

```apex
trigger Quote on Quote (after update) {
    
    public List<Quote>      newObjList  {get; set;}
    public Map<Id, Quote>   oldObj      {get; set;}

    newObjList = (List<Quote>)Trigger.new;
    oldObj = (Map<Id, Quote>)Trigger.oldMap;
    if (trigger.isAfter && trigger.isUpdate){   
        for(Quote qu : trigger.new){   
            if (qu.Status == 'Accepted' && qu.Status != oldObj.get(qu.id).Status){
                // template Id와 recordId를 parameter 값으로 넘겨준다.
                String templateId = DocumentCustomController.getTemplateId();
                DocumentCustomController.triggeredSavePdf(qu.Id, templateId);
            }
        }        
    }
    
}
```

***

* Document Builder Template 이름 기준으로 template Id를 가져오는 함수 예제

```apex
public static String getTemplateId() {
    String templateId = [SELECT Id 
                            FROM SBLD__DocumentBuilder__c
                            WHERE name = 'BillingStatement' 
                            WITH SECURITY_ENFORCED
                            ORDER BY CreatedDate DESC
                            LIMIT 1][0].Id;
    return templateId;
}

```

***

* 사용자에게 이메일을 보내는 함수 예제

```apex
public static void sendEmailToUser( List<String> listAttachement) {
    // 이메일 기본정보 추가
    Messaging.SingleEmailMessage clsSingleEmailMessage = new Messaging.SingleEmailMessage();
    clsSingleEmailMessage.setToAddresses(new List<String>{'abc@example.com'});
    clsSingleEmailMessage.setSubject('Email Subject');
    clsSingleEmailMessage.setPlainTextBody('Email Body');
    
    // attachement 추가
    ContentVersion clsContentVersion = [SELECT VersionData, PathOnClient FROM ContentVersion WHERE ContentDocumentId = :listAttachement.get(0) WITH SECURITY_ENFORCED][0];
    Messaging.EmailFileAttachment clsEmailFileAttachment = new Messaging.EmailFileAttachment();
    clsEmailFileAttachment.setFileName(clsContentVersion.pathOnClient); 
    clsEmailFileAttachment.setBody(clsContentVersion.versionData);
    clsSingleEmailMessage.setFileAttachments(new Messaging.EmailFileAttachment[] {clsEmailFileAttachment});
    
    // 이메일 전송
    Messaging.sendEmail(new Messaging.SingleEmailMessage[]{clsSingleEmailMessage});     
        
}
```

***

* Document Template을 PDF로 저장하는 예제

```apex
// Document Template PDF 저장
@future(callout = true)
public static void triggeredSavePdf(String recordId, String templateId) {

    // PDF 생성
    PageReference pdfPage = new PageReference('/apex/SBLD__DocumentBuilderTemplate?recordId=' + templateId + '&targetId=' + recordId);
    Blob pdfContent;

    if(Test.isRunningTest()) { 
        pdfContent = blob.valueOf('Unit.Test'); 
    }else {
        pdfContent = pdfPage.getContentAsPDF();
    }
        
    String title = 'BillingStatement.pdf';

    // ContentVersion 추가    
    ContentVersion cv           = new ContentVersion();
    cv.VersionData              = pdfContent;
    cv.Title                    = title;
    cv.PathOnClient             = title;
    cv.OwnerId                  = UserInfo.getUserId();
    cv.ContentLocation          = 'S';

    insert cv;
    
    // ContentDocumentLink 추가
    Id conDocId = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:cv.Id WITH SECURITY_ENFORCED ].ContentDocumentId;
    ContentDocumentLink cdl = new ContentDocumentLink();
    cdl.ContentDocumentId = conDocId;
    cdl.LinkedEntityId = recordId;
    cdl.ShareType = 'V';
    cdl.Visibility = 'AllUsers';
		
    if (Schema.sObjectType.ContentDocumentLink.fields.ContentDocumentId.isCreateable()) {
            Database.insert(cdl);
    }
    
    // Attachement가 추가된 email 전송 메서드 호출
    listAttachement = new List<String>{conDocId};
    sendEmailToUser(listAttachement);
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://help.smallbuilder.com/ko/smallbuilder-documents/undefined-2/trigger.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
