-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcopyData.js
84 lines (76 loc) · 2.22 KB
/
copyData.js
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/***
* This script moves Account, Contact and Opportunity data from a source instance to the current SF instance.
* The source instance is expected to be configured using a named credential named 'source'
*/
let baseurl = "callout:source/services/data/v48.0/query?q=";
let resp = await callout(baseurl + "Select+Id,Name+from+Account", "GET", {
Accept: "application/json"
});
resp = JSON.parse(resp.body);
if (!resp.done) {
toast("Request to fetch Accounts failed", "error");
}
let accts = resp.records;
resp = await callout(baseurl + "Select+Id,LastName,FirstName,Email,AccountId+from+Contact", "GET", {
Accept: "application/json"
});
resp = JSON.parse(resp.body);
if (!resp.done) {
toast("Request to fetch Contacts failed", "error");
}
let contacts = resp.records;
resp = await callout(baseurl + "Select+Id,Name,CloseDate,StageName,AccountId,ContactId+from+Opportunity", "GET", {
Accept: "application/json"
});
resp = JSON.parse(resp.body);
if (!resp.done) {
toast("Request to fetch Opportunities failed", "error");
}
let opps = resp.records;
let acctsToInsert = accts.map((a) => {
let b = { ...a };
delete b.Id;
delete b.attributes;
return b;
});
let newAcctIds = [];
try {
newAcctIds = await dml.insert(acctsToInsert, "Account");
} catch (err) {
toast(JSON.stringify(err), "error");
}
let acctIdMap = accts.reduce((obj, a, i) => ({ ...obj, [a.Id]: newAcctIds[i] }), {});
let contactsToInsert = contacts
.map((c) => {
let d = { ...c, AccountId: acctIdMap[c.AccountId] };
delete d.Id;
delete d.attributes;
return d;
})
.filter((c) => c.AccountId);
let newCtctIds = [];
try {
newCtctIds = await dml.insert(contactsToInsert, "Contact");
} catch (err) {
toast(JSON.stringify(err), "error");
}
let ctctIdMap = contacts.reduce((obj, c, i) => ({ ...obj, [c.Id]: newCtctIds[i] }), {});
let oppsToInsert = opps
.map((o) => {
let p = {
...o,
AccountId: acctIdMap[o.AccountId],
ContactId: ctctIdMap[o.ContactId]
};
delete p.Id;
delete p.attributes;
return p;
})
.filter((o) => o.AccountId);
let newOppIds = [];
try {
newOppIds = dml.insert(oppsToInsert, "Opportunity");
} catch (err) {
toast(JSON.stringify(err), "error");
}
toast("Data transfer complete", "success");