yumenghui
2023-08-04 17bd5b18e21c9f46aefdbf3400262764f0def4da
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
trigger SetAttToDocForEmail on SMARM__c (before update) {
    for (SMARM__c s : Trigger.new) {
        if (Trigger.oldMap.get(s.Id).get('Status__c') != s.Status__c && s.Status__c == '填写完毕') {
            Schema.DescribeSobjectResult smarm = SMARM__c.sObjectType.getDescribe();
            Map<String, Schema.SObjectField> fieldMap = smarm.fields.getMap();
            
            List<Document> docList = new List<Document>();
            List<ContentDocumentLink> linkList = [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId =: s.Id];
            List<Id> linkIdList = new List<Id>();
            for (ContentDocumentLink link : linkList) {
                linkIdList.add(link.ContentDocumentId);
            }
            List<ContentVersion> versionList =[SELECT Title,VersionData FROM ContentVersion WHERE ContentDocumentId in: linkIdList];
            for (ContentVersion cVersion : versionList) {
                docList.add(new Document(
                    Name = cVersion.Title,
                    DeveloperName = 'sm_' + s.Id + '_' + ControllerUtil.generateRandomStr(18),
                    Type = 'png',
                    Body = cVersion.VersionData
                ));
            }
            // AttachmentをDocumentに
            // for (Attachment att : ControllerUtil.getSmarmAtts(s.Id)) {
            //     docList.add(new Document(
            //         Name = att.Name,
            //         DeveloperName = 'sm_' + s.Id + '_' + ControllerUtil.generateRandomStr(18),
            //         Type = 'png',
            //         Body = att.Body
            //     ));
            // }
            List<Document> docInsertList = new List<Document>();
            docInsertList = ControllerUtil.createDocForEmail(docList);
            Map<String, String> docMap = new Map<String, String>();
            for (Document doc : docInsertList) {
                docMap.put(doc.Name, doc.Id);
            }
            
            for (Integer i = 1; i <= Integer.valueOf(System.Label.SmarmClipNum); i++) {
                String reportNameApi = 'ReportName' + i + '__c';
                if (fieldMap.get(reportNameApi) != null && s.get(reportNameApi) != null) {
                    if (docMap.containsKey(i + '.' + s.get(reportNameApi))) {
                        s.put('Doc' + i + '__c', docMap.get(i + '.' + s.get(reportNameApi)));
                    }
                }
            }
            s.DocSaveFinish__c = true;
        }
    }
}