Skip to content

Commit

Permalink
Merge pull request #305 from Accenture/299-bug-not-getting-progressst…
Browse files Browse the repository at this point in the history
…atus-on-functions

299 bug not getting progressstatus on functions
  • Loading branch information
JoernBerkefeld committed Dec 5, 2022
2 parents 8cd57fa + 47367b7 commit 159e288
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 34 deletions.
2 changes: 1 addition & 1 deletion copado-function/app/Retrieve.fn.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,6 @@ async function run() {
Log.error('Saving metadata JSON failed:' + ex.message);
throw ex;
}
Log.result(`Found ${metadataJson.length} items on server`, 'Refresh done');
try {
Log.info('');
Log.info('Attach JSON');
Expand All @@ -171,6 +170,7 @@ async function run() {
Log.error('Attaching JSON file failed:' + ex.message);
throw ex;
}
Log.result(`Found ${metadataJson.length} items on server`, 'Refresh done');
Log.info('');
Log.info('===================');
Log.info('');
Expand Down
4 changes: 2 additions & 2 deletions copado-function/dist/Retrieve.fn.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env node

/*
* mcdev-copado v1.2.0 (built 2022-11-21T11:25:57.041Z)
* mcdev-copado v1.2.0 (built 2022-12-05T14:16:30.690Z)
* Function: Retrieve.fn.js
* Dependenies: mcdev@>=4.1.12, Copado Deployer@20.1
* Homepage: https://github.com/Accenture/sfmc-devtools-copado#readme
Expand Down Expand Up @@ -472,7 +472,6 @@ async function run() {
Log.error("Saving metadata JSON failed:" + ex.message);
throw ex;
}
Log.result(`Found ${metadataJson.length} items on server`, "Refresh done");
try {
Log.info("");
Log.info("Attach JSON");
Expand All @@ -488,6 +487,7 @@ async function run() {
Log.error("Attaching JSON file failed:" + ex.message);
throw ex;
}
Log.result(`Found ${metadataJson.length} items on server`, "Refresh done");
Log.info("");
Log.info("===================");
Log.info("");
Expand Down
26 changes: 26 additions & 0 deletions force-app/main/default/classes/mcdo_RunCopadoFunctionFromLWC.cls
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,30 @@ public with sharing class mcdo_RunCopadoFunctionFromLWC {
throw new AuraHandledException(e.getMessage());
}
}

/**
* This function calls returns the last resultId from the received jobExecution
* @param jobExecutionId JobExecution Id from the jobExecution that we want to find the latest result id
* @return Returs the list of IDs form the results created on the respective jobExecution
*/
@AuraEnabled
public static List<Id> getResultIds(String jobExecutionId) {
// get the newest result associated with this job execution
copado__Result__c[] results = [
SELECT Id
FROM copado__Result__c
WHERE
copado__JobStep__r.copado__JobExecution__c = :jobExecutionId
AND copado__Status__c NOT IN ('Failed', 'Cancelled', 'Success')
WITH SECURITY_ENFORCED
ORDER BY CreatedDate DESC
];
List<Id> ids = new List<Id>();

for (copado__Result__c item : results) {
ids.add(item.Id);
}

return ids;
}
}
90 changes: 59 additions & 31 deletions force-app/main/default/lwc/mcdo_RetrieveTable/mcdo_RetrieveTable.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ import {
} from "lightning/empApi";

// Apex Methods for retrieving and committing metadata (And Communication with the Copado Package)
// Apex functions to retrieve Recorddata from LWC
import ExecuteRetrieveFromCopado from "@salesforce/apex/mcdo_RunCopadoFunctionFromLWC.executeRetrieve";
import getMetadataFromEnvironment from "@salesforce/apex/mcdo_RunCopadoFunctionFromLWC.getMetadataFromEnvironment";

// Apex functions to retrieve Recorddata from LWC
import getResultIds from "@salesforce/apex/mcdo_RunCopadoFunctionFromLWC.getResultIds";

// "Commit Changes" Page Tab related
import COMMIT_PAGE_COMMUNICATION_CHANNEL from "@salesforce/messageChannel/copado__CommitPageCommunication__c";
Expand Down Expand Up @@ -157,15 +157,18 @@ export default class mcdo_RetrieveTable extends LightningElement {
showTable = false;
refreshButtonDisabled = true;
progressStatus = "Loading data";
currentResultIds = undefined;

// Subscription related variables
empSubscription = {};
channelName = "/event/copado__Event__e";
getProgressSubscription = {};
reloadTableSubscription = {};
resultChannelName = "/event/copado__MC_Result__e";
eventChannelName = "/event/copado__Event__e";

_subscribeToMessageService() {
subscribeMessageService(this._context, COMMIT_PAGE_COMMUNICATION_CHANNEL, (message) =>
this._handleCommitPageCommunicationMessage(message)
);
subscribeMessageService(this._context, COMMIT_PAGE_COMMUNICATION_CHANNEL, (message) => {
this._handleCommitPageCommunicationMessage(message);
});
}

/**
Expand Down Expand Up @@ -310,8 +313,6 @@ export default class mcdo_RetrieveTable extends LightningElement {
const jobExecutionId = await ExecuteRetrieveFromCopado({
userStoryId: this.userStoryId
});
// TODO get result ID from Job step related to job execution
//! has to be last result created for that job step if there are multiple
this.subscribeToCompletionEvent(jobExecutionId);
} catch (error) {
this.loadingState(false);
Expand All @@ -333,30 +334,52 @@ export default class mcdo_RetrieveTable extends LightningElement {
* @returns {Promise<void>} resolves when the job is done
*/
async subscribeToCompletionEvent(jobExecutionId) {
const messageCallback = async (response) => {
// get result ID from Job step related to job execution
try {
this.currentResultIds = await getResultIds({ jobExecutionId: jobExecutionId });
} catch (error) {
console.error(`ERROR STATUS: ${error.status} ${error.statusText}`);
}

const progressMessageCallback = async (response) => {
if (
this.currentResultIds.includes(response?.data?.payload?.copado__ResultId__c) &&
response?.data?.payload?.copado__Progress_Status__c
) {
// show progress update to user
this.progressStatus = response?.data?.payload?.copado__Progress_Status__c;
}
};

const reloadTableCallBack = async (response) => {
if (
response.data.payload.copado__Topic_Uri__c ===
`/execution-completed/${jobExecutionId}`
) {
// retrieve is done: refresh table with new data
this.updateMetadataGrid(response, jobExecutionId);
} else if (
response.data.payload.copado__Topic_Uri__c.startsWith(
"/events/copado/v1/step-monitor/" // + resultId
)
) {
try {
// show progress on screen; try-catch is needed because copado__Payload__c sometimes contains bad JSON
const stepStatus = JSON.parse(response.data.payload.copado__Payload__c);
this.progressStatus = stepStatus.data.progressStatus || this.progressStatus;
} catch {
// ignore
}
}
};

try {
this.empSubscription = await subscribeEmp(this.channelName, -1, messageCallback);
this.getProgressSubscription = await subscribeEmp(
this.resultChannelName,
-1,
progressMessageCallback
);
} catch (err) {
this.showError(
`${err.name}: An error occurred while subscribing to Emp API`,
err.message
);
}

try {
this.reloadTableSubscription = await subscribeEmp(
this.eventChannelName,
-1,
reloadTableCallBack
);
} catch (err) {
this.showError(
`${err.name}: An error occurred while subscribing to Emp API`,
Expand All @@ -365,21 +388,26 @@ export default class mcdo_RetrieveTable extends LightningElement {
}
}

/**
* helper for retrieve() called when refreshing metadata is done to update the table
* @param {object} response empApi response
* @param {string} jobExecutionId sfid
* @returns {Promise<void>} resolves when the job is done
*/
async updateMetadataGrid(response, jobExecutionId) {
async unsubscribeThisSubscription(subscription) {
try {
unsubscribeEmp(this.empSubscription);
unsubscribeEmp(subscription, () => {});
} catch (err) {
this.showError(
`${err.name}: An error occurred while unsubscribing from Emp API`,
err.message
);
}
}

/**
* helper for retrieve() called when refreshing metadata is done to update the table
* @param {object} response empApi response
* @param {string} jobExecutionId sfid
* @returns {Promise<void>} resolves when the job is done
*/
async updateMetadataGrid(response, jobExecutionId) {
this.unsubscribeThisSubscription(this.getProgressSubscription);
this.unsubscribeThisSubscription(this.reloadTableSubscription);
const jobExecution = JSON.parse(response.data.payload.copado__Payload__c);
if (jobExecution.copado__Status__c === "Successful") {
try {
Expand Down

0 comments on commit 159e288

Please sign in to comment.