Skip to content

Commit

Permalink
#984: enable updating notes or email addresses, additional checks, mo…
Browse files Browse the repository at this point in the history
…ved repetitive code into a method
  • Loading branch information
phjulia committed Aug 7, 2023
1 parent 76dda3e commit 49440b9
Show file tree
Hide file tree
Showing 2 changed files with 162 additions and 75 deletions.
17 changes: 14 additions & 3 deletions docs/dist/documentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,9 @@ Provides default functionality that can be overwritten by child metadata type cl
<dt><a href="#Automation.">Automation.(metadataMap, key)</a> ⇒ <code>Promise.&lt;void&gt;</code></dt>
<dd><p>helper for <a href="#Automation.postDeployTasks">postDeployTasks</a></p>
</dd>
<dt><a href="#Automation.">Automation.()</a> ⇒ <code>string</code></dt>
<dd></dd>
<dt><a href="#Automation.">Automation.(key, programId, notificationBody)</a> ⇒ <code>string</code></dt>
<dd><p>helper function to send POST request to update notifications</p>
</dd>
<dt><a href="#Automation.">Automation.(metadataMap, originalMetadataMap, key)</a> ⇒ <code>Promise.&lt;{key:string, response:object}&gt;</code></dt>
<dd><p>helper for <a href="#Automation.postDeployTasks">postDeployTasks</a></p>
</dd>
Expand Down Expand Up @@ -8585,8 +8586,18 @@ helper for [postDeployTasks](#Automation.postDeployTasks)

<a name="Automation."></a>

## Automation.() ⇒ <code>string</code>
## Automation.(key, programId, notificationBody) ⇒ <code>string</code>
helper function to send POST request to update notifications

**Kind**: global function
**Returns**: <code>string</code> - returns "OK" or "Error"

| Param | Type | Description |
| --- | --- | --- |
| key | <code>string</code> | current customer key |
| programId | <code>string</code> | legacy automation id |
| notificationBody | <code>string</code> | notification payload |

<a name="Automation."></a>

## Automation.(metadataMap, originalMetadataMap, key) ⇒ <code>Promise.&lt;{key:string, response:object}&gt;</code>
Expand Down
220 changes: 148 additions & 72 deletions lib/metadataTypes/Automation.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,13 +115,15 @@ class Automation extends MetadataType {
const foundKeys = Object.keys(metadataMap);

// get encodedAutomationID to retrieve notification information
const iteratorBackup = this.definition.bodyIteratorField;
this.definition.bodyIteratorField = 'entry';
const automationLegacyMapObj = await super.retrieveREST(
undefined,
`/legacy/v1/beta/bulk/automations/automation/definition/`
);
this.definition.bodyIteratorField = iteratorBackup;
const automationLegacyMapObj = await this.#getEncodedAutomationIDs();
// const iteratorBackup = this.definition.bodyIteratorField;
// this.definition.bodyIteratorField = 'entry';
// const automationLegacyMapObj = await super.retrieveREST(
// undefined,
// `/legacy/v1/beta/bulk/automations/automation/definition/`
// );
// console.log('metadata:', automationLegacyMapObj.metadata);
// this.definition.bodyIteratorField = iteratorBackup;
const automationLegacyMap = Object.keys(automationLegacyMapObj.metadata)
.filter((key) => foundKeys.includes(key))
// ! using the `id` field to retrieve notifications does not work. instead one needs to use the URL in the `notifications` field
Expand Down Expand Up @@ -239,16 +241,17 @@ class Automation extends MetadataType {
const resultsConverted = {};
if (Array.isArray(results?.Results)) {
// get encodedAutomationID to retrieve notification information
const keyBackup = this.definition.keyField;
const iteratorBackup = this.definition.bodyIteratorField;
this.definition.keyField = 'key';
this.definition.bodyIteratorField = 'entry';
const automationsLegacy = await super.retrieveREST(
undefined,
`/legacy/v1/beta/bulk/automations/automation/definition/`
);
this.definition.keyField = keyBackup;
this.definition.bodyIteratorField = iteratorBackup;
const automationsLegacy = await this.#getEncodedAutomationIDs();
// const keyBackup = this.definition.keyField;
// const iteratorBackup = this.definition.bodyIteratorField;
// this.definition.keyField = 'key';
// this.definition.bodyIteratorField = 'entry';
// const automationsLegacy = await super.retrieveREST(
// undefined,
// `/legacy/v1/beta/bulk/automations/automation/definition/`
// );
// this.definition.keyField = keyBackup;
// this.definition.bodyIteratorField = iteratorBackup;

// merge encodedAutomationID into results
for (const m of results.Results) {
Expand Down Expand Up @@ -916,7 +919,7 @@ class Automation extends MetadataType {
await Automation.#scheduleAutomation(metadataMap, originalMetadataMap, key);

// need to update notifications separately if there are any
await Automation.#updateNotificationInfoREST(metadataMap, key);
await Automation.#updateNotificationInfo(metadataMap, key);

// rewrite upsert to retrieve fields
const metadata = metadataMap[key];
Expand All @@ -939,7 +942,7 @@ class Automation extends MetadataType {
* @param {string} key current customer key
* @returns {Promise.<void>} -
*/
static async #updateNotificationInfoREST(metadataMap, key) {
static async #updateNotificationInfo(metadataMap, key) {
if (this.notificationUpdates[key]) {
// create & update automation calls return programId as 'legacyId'; retrieve does not return it
const programId = metadataMap[key]?.legacyId;
Expand All @@ -956,26 +959,59 @@ class Automation extends MetadataType {
channelType: 'Account',
})),
};
try {
const result = await this.client.rest.post(
'/legacy/v1/beta/automations/notifications/' + programId,
notificationBody
);
if (result) {
// should be empty if all OK
throw new Error(result);
}
} catch (ex) {
Util.logger.error(
`Error updating notifications for automation '${metadataMap[key].name}': ${ex.message} (${ex.code}))`
);
}
this.#updateNotificationInfoREST(key, programId, notificationBody);
// try {
// const result = await this.client.rest.post(
// '/legacy/v1/beta/automations/notifications/' + programId,
// notificationBody
// );
// if (result) {
// // should be empty if all OK
// throw new Error(result);
// }
// } catch (ex) {
// Util.logger.error(
// `Error updating notifications for automation '${metadataMap[key].name}': ${ex.message} (${ex.code}))`
// );
// }
// Util.logger.info(
// Util.getGrayMsg(
// ` - updated notifications for automation '${metadataMap[key].name}'`
// )
// );
}
}
}
/**
* helper function to send POST request to update notifications
*
* @param {string} key current customer key
* @param {string} programId legacy automation id
* @param {string} notificationBody notification payload
* @returns {string} returns "OK" or "Error"
*/
static async #updateNotificationInfoREST(key, programId, notificationBody) {
try {
const result = await this.client.rest.post(
'/legacy/v1/beta/automations/notifications/' + programId,
notificationBody
);
if (result) {
// should be empty if all OK
throw new Error(result);
} else {
Util.logger.info(
Util.getGrayMsg(
` - updated notifications for automation '${metadataMap[key].name}'`
)
Util.getGrayMsg(` - updated notifications for automation '${key}'`)
);
return 'OK';
}
} catch (ex) {
let error = `Error updating notifications for automation '${key}': ${ex.message} (${ex.code})).`;
ex.code === 'ERR_BAD_REQUEST'
? (error += 'Make sure that the email address is correct.')
: '';
Util.logger.error(error);
return 'Error';
}
}

Expand Down Expand Up @@ -1583,12 +1619,12 @@ class Automation extends MetadataType {
* @returns {Promise.<string[]>} keys of the automations where notifications were updated
*/
static async updateNotifications(keys) {
const emailComplete = Array.isArray(Util.OPTIONS.emailComplete)
? Util.OPTIONS.emailComplete.join(',')
: Util.OPTIONS.emailComplete;
const emailError = Array.isArray(Util.OPTIONS.emailError)
? Util.OPTIONS.emailError.join(',')
: Util.OPTIONS.emailError;
const completionEmail = Util.OPTIONS.completionEmail
? Util.OPTIONS.completionEmail.split(',')
: undefined;
const errorEmail = Util.OPTIONS.errorEmail ? Util.OPTIONS.errorEmail.split(',') : undefined;
let completionNote = Util.OPTIONS.completionNote;
let errorNote = Util.OPTIONS.errorNote;
const updatedKeys = [];
let notificationsResult;
const automationLegacyMapObj = await this.#getEncodedAutomationIDs(); // retrieve automation legacy keys to update notifications
Expand All @@ -1604,60 +1640,90 @@ class Automation extends MetadataType {
`Error retrieving notifications for automation '${key}': ${ex.message} (${ex.code}))`
);
}
// if a note was provided and email address was not - check if notif email address exists
if (completionNote && !completionEmail) {
if (
!notificationsResult.workers.find(
(notification) => notification.notificationType === 'Complete'
)
) {
Util.logger.info(
` ☇ skipping --completionNote' - the email address for Run completion was not set`
);
completionNote = undefined;
// TODO interactive question "do you want to set completionEmail" then ask for email ?
}
} else if (
errorNote &&
!errorEmail &&
!notificationsResult.workers.find(
(notification) => notification.notificationType === 'Error'
)
) {
Util.logger.info(
` ☇ skipping --errorNote' - the email address for Runtime error was not set`
);
errorNote = undefined;
// TODO interactive question "do you want to set errorEmail" then ask for email ?
}
// check again if there is anything else to update
if (!completionEmail && !errorEmail) {
Util.logger.info(` ☇ skipping ${key}' - nothing to update`);
}
// if the parameters provided are the same as the email addresses/notes already in the notifications - skip this automation
if (
else if (
notificationsResult.workers.find(
(notification) =>
(notification.notificationType === 'Complete' &&
(emailComplete !== notification.definition ||
(completionEmail !== notification.definition ||
Util.OPTIONS.completionNote !== notification.body)) ||
notificationsResult.workers.find(
(notification) =>
notification.notificationType === 'Error' &&
(emailError !== notification.definition ||
(errorEmail !== notification.definition ||
Util.OPTIONS.errorNote !== notification.body)
)
)
) {
// create payload
const notificationBody = {
programId: automationLegacyMapObj.metadata[key].id,
workers: [
{
workers: [],
};

if (completionEmail || completionNote) {
// completionEmail is an array even if there is only one email
for (const email of completionEmail) {
// TODO validate email addresses (simple validation)
// if(email.match('\\.+@\\.+.\\'))
notificationBody.workers.push({
programId: automationLegacyMapObj.metadata[key].id,
notificationType: 'Complete',
definition: emailComplete,
body: Util.OPTIONS.completionNote,
definition: email,
body: completionNote,
channelType: 'Account',
},
{
});
}
} else {
for (const email of errorEmail) {
notificationBody.workers.push({
programId: automationLegacyMapObj.metadata[key].id,
notificationType: 'Error',
definition: emailError,
body: Util.OPTIONS.errorNote,
definition: email,
body: errorNote,
channelType: 'Account',
},
],
};
try {
const result = await this.client.rest.post(
'/legacy/v1/beta/automations/notifications/' +
automationLegacyMapObj.metadata[key].id,
notificationBody
);
if (result) {
// should be empty if all OK
throw new Error(result);
});
}
}
if (
(await this.#updateNotificationInfoREST(
key,
automationLegacyMapObj.metadata[key].id,
notificationBody
)) === 'OK'
) {
updatedKeys.push(key);
} catch (ex) {
Util.logger.error(
`Error updating notifications for automation '${key}': ${ex.message} (${ex.code}))`
);
}
Util.logger.info(
Util.getGrayMsg(` - updated notifications for automation '${key}'`)
);
} else {
Util.logger.info(
` ☇ skipping automation '${key}' - email addresses provided and run notes are the same`
Expand All @@ -1666,6 +1732,16 @@ class Automation extends MetadataType {
}
}
}
// const deployOrder = Util.getMetadataHierachy(metadataTypes);
// Util.logger.info(`Caching dependent Metadata: ${type}`);
// Util.logSubtypes(subTypeArr);
// result = await MetadataTypeInfo[type].retrieveForCache(null, subTypeArr);
// const retrieved = await this.retrieve('/retrieve', null, null, keys);
//const retrieved = await retriever.retrieve([this.definition.type], keys, null, false);
// console.log(retrieved);

//save updated automation
//this.saveResults(retrieved, this.retrieve, null, null);
return updatedKeys;
}
}
Expand Down

0 comments on commit 49440b9

Please sign in to comment.