Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
caf43b8
feat: show proposed changes with clickable entity links in approval t…
yan-3005 Apr 9, 2026
72f2e52
fix: drop owner links (user/team ambiguous), escape FQN HTML, widen d…
yan-3005 Apr 9, 2026
91a537a
Merge branch 'main' into ram/approval-task-proposed-changes
yan-3005 Apr 9, 2026
06022f2
Merge branch 'main' into ram/approval-task-proposed-changes
yan-3005 Apr 12, 2026
0e25087
feat(governance): structured JSON proposed-changes preview in approva…
yan-3005 Apr 13, 2026
4c1aca6
feat(governance): strikethrough on removed chips in proposed changes
yan-3005 Apr 13, 2026
8654f1b
fix(governance): null-safe field list iteration and correct JSON stri…
yan-3005 Apr 13, 2026
f890b62
fix(governance): non-null thread.message fallback and single parsePro…
yan-3005 Apr 13, 2026
d99f82b
fix(governance): O(n) set operations and resilient threshold parsing
yan-3005 Apr 13, 2026
cc9b11c
i18n: translate proposed-change-plural key in all 18 locale files
yan-3005 Apr 13, 2026
5debf82
Addressed comments
anuj-kumary Apr 13, 2026
170b55f
Merge branch 'main' into ram/approval-task-proposed-changes
anuj-kumary Apr 13, 2026
970d6bf
fix lint issue
anuj-kumary Apr 13, 2026
f8bcddd
Merge branch 'ram/approval-task-proposed-changes' of https://github.c…
anuj-kumary Apr 13, 2026
66717fc
Fix Playwright: use dedicated i18n key for approval notification, fal…
yan-3005 Apr 14, 2026
cee1be7
Fix review: handle List/Map inputs in extractIdentifiers, gate propos…
yan-3005 Apr 14, 2026
caf8d21
Fix: add trailing space to approval notification i18n key
yan-3005 Apr 14, 2026
0759607
Fix review: empty Map/List guard, startCase field labels, chip keys w…
yan-3005 Apr 14, 2026
0241f27
Merge branch 'main' into ram/approval-task-proposed-changes
anuj-kumary Apr 14, 2026
d446d44
refactor(workflows): simplify ChangePreviewUtils — single JSON path, …
yan-3005 Apr 16, 2026
ad71742
Merge branch 'main' into ram/approval-task-proposed-changes
yan-3005 Apr 16, 2026
d3b107b
fix(workflows): null-safe FieldDiff compact constructor, zh-CN locale…
yan-3005 Apr 16, 2026
38b5ea5
i18n: translate request-approval-notification for all 17 locales
yan-3005 Apr 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,15 @@
import org.openmetadata.service.exception.EntityNotFoundException;
import org.openmetadata.service.governance.workflows.WorkflowHandler;
import org.openmetadata.service.governance.workflows.WorkflowVariableHandler;
import org.openmetadata.service.governance.workflows.util.ChangePreviewUtils;
import org.openmetadata.service.jdbi3.FeedRepository;
import org.openmetadata.service.resources.feeds.FeedMapper;
import org.openmetadata.service.resources.feeds.MessageParser;
import org.openmetadata.service.util.WebsocketNotificationHandler;

@Slf4j
public class CreateApprovalTaskImpl implements TaskListener {

private Expression inputNamespaceMapExpr;
private Expression approvalThresholdExpr;
private Expression rejectionThresholdExpr;
Expand All @@ -57,31 +59,14 @@ public void notify(DelegateTask delegateTask) {
inputNamespaceMap.get(RELATED_ENTITY_VARIABLE), RELATED_ENTITY_VARIABLE));
EntityInterface entity = Entity.getEntity(entityLink, "*", Include.ALL);

// Get approval threshold, default to 1 if not set
int approvalThreshold = 1;
if (approvalThresholdExpr != null) {
String thresholdStr = (String) approvalThresholdExpr.getValue(delegateTask);
if (thresholdStr != null && !thresholdStr.isEmpty()) {
approvalThreshold = Integer.parseInt(thresholdStr);
}
}

// Get rejection threshold, default to 1 if not set
int rejectionThreshold = 1;
if (rejectionThresholdExpr != null) {
String thresholdStr = (String) rejectionThresholdExpr.getValue(delegateTask);
if (thresholdStr != null && !thresholdStr.isEmpty()) {
rejectionThreshold = Integer.parseInt(thresholdStr);
}
}
int approvalThreshold = resolveThreshold(approvalThresholdExpr, delegateTask, 1);
int rejectionThreshold = resolveThreshold(rejectionThresholdExpr, delegateTask, 1);

Thread task = createApprovalTask(entity, assignees);
WorkflowHandler.getInstance().setCustomTaskId(delegateTask.getId(), task.getId());

// Set the thresholds as task variables for use in WorkflowHandler
delegateTask.setVariable("approvalThreshold", approvalThreshold);
delegateTask.setVariable("rejectionThreshold", rejectionThreshold);
// Use separate lists for approvers and rejecters - simpler and cleaner
delegateTask.setVariable("approversList", new ArrayList<String>());
delegateTask.setVariable("rejectersList", new ArrayList<String>());
} catch (Exception exc) {
Expand All @@ -94,9 +79,24 @@ public void notify(DelegateTask delegateTask) {
}
}

private static int resolveThreshold(
Expression expr, DelegateTask delegateTask, int defaultValue) {
if (expr == null) return defaultValue;
String raw = (String) expr.getValue(delegateTask);
if (raw == null || raw.trim().isEmpty()) return defaultValue;
try {
return Integer.parseInt(raw.trim());
} catch (NumberFormatException exc) {
LOG.warn(
"Invalid threshold value '{}' resolved from workflow expression. Falling back to default value {}.",
raw,
defaultValue);
return defaultValue;
}
}

private List<EntityReference> getAssignees(DelegateTask delegateTask) {
List<EntityReference> assignees = new ArrayList<>();

Set<IdentityLink> candidates = delegateTask.getCandidates();
if (!candidates.isEmpty()) {
for (IdentityLink candidate : candidates) {
Expand All @@ -121,22 +121,17 @@ private Thread createApprovalTask(EntityInterface entity, List<EntityReference>
Entity.getEntityTypeFromObject(entity), entity.getFullyQualifiedName());

Thread thread;

ChangeEvent changeEvent;
try {
thread = feedRepository.getTask(about, TaskType.RequestApproval, TaskStatus.Open);
// Update the existing thread with new assignees before terminating the workflow
thread.getTask().setAssignees(FeedMapper.formatAssignees(assignees));

ChangePreviewUtils.applyChangePreview(thread, entity, thread.getMessage());
thread.withUpdatedBy(entity.getUpdatedBy()).withUpdatedAt(System.currentTimeMillis());

// Save the updated thread to database
Entity.getCollectionDAO().feedDAO().update(thread.getId(), JsonUtils.pojoToJson(thread));

// Now terminate the old workflow instance
WorkflowHandler.getInstance()
.terminateTaskProcessInstance(thread.getId(), "A Newer Process Instance is Running.");
// Create and publish ChangeEvent for notification system
changeEvent =
new ChangeEvent()
.withId(UUID.randomUUID())
Expand All @@ -157,16 +152,15 @@ private Thread createApprovalTask(EntityInterface entity, List<EntityReference>
new Thread()
.withId(UUID.randomUUID())
.withThreadTs(System.currentTimeMillis())
.withMessage("Approval required for ")
.withCreatedBy(entity.getUpdatedBy())
.withAbout(about.getLinkString())
.withType(ThreadType.Task)
.withTask(taskDetails)
.withUpdatedBy(entity.getUpdatedBy())
.withUpdatedAt(System.currentTimeMillis());
ChangePreviewUtils.applyChangePreview(thread, entity, null);
feedRepository.create(thread);

// Create and publish ChangeEvent for notification system
changeEvent =
new ChangeEvent()
.withId(UUID.randomUUID())
Expand All @@ -178,7 +172,6 @@ private Thread createApprovalTask(EntityInterface entity, List<EntityReference>
.withEntity(thread);
}
Entity.getCollectionDAO().changeEventDAO().insert(JsonUtils.pojoToMaskedJson(changeEvent));
// Send WebSocket Notification
WebsocketNotificationHandler.handleTaskNotification(thread);
return thread;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
/*
* Copyright 2021 Collate
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.openmetadata.service.governance.workflows.util;

import static org.openmetadata.common.utils.CommonUtil.listOrEmpty;
import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty;

import com.fasterxml.jackson.core.type.TypeReference;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import lombok.extern.slf4j.Slf4j;
import org.openmetadata.schema.EntityInterface;
import org.openmetadata.schema.entity.feed.Thread;
import org.openmetadata.schema.type.ChangeDescription;
import org.openmetadata.schema.type.FieldChange;
import org.openmetadata.schema.utils.JsonUtils;

/**
* Builds and merges structured change-preview JSON stored in {@code thread.message} for approval
* tasks. The message format is a JSON object mapping field names to {@code {added, removed}} arrays
* of human-readable identifiers (tagFQN, fullyQualifiedName, displayName, or name).
*/
@Slf4j
public final class ChangePreviewUtils {

private static final List<String> ID_KEYS =
List.of("tagFQN", "fullyQualifiedName", "displayName", "name");

private static final TypeReference<Map<String, FieldDiff>> CHANGE_MAP_TYPE =
new TypeReference<>() {};

private ChangePreviewUtils() {}

public record FieldDiff(List<String> added, List<String> removed) {
public FieldDiff {
added = added != null ? added : List.of();
removed = removed != null ? removed : List.of();
}

FieldDiff merge(FieldDiff next) {
return new FieldDiff(
union(minus(added, next.removed), minus(next.added, removed)),
union(minus(removed, next.added), minus(next.removed, added)));
}

boolean isEmpty() {
return added.isEmpty() && removed.isEmpty();
Comment thread
gitar-bot[bot] marked this conversation as resolved.
Resolved
}
}

public static List<String> extractIdentifiers(Object value) {
return collect(normalize(value));
}

private static Object normalize(Object value) {
if (!(value instanceof String raw)) return value;
String stripped = raw.strip();
if (stripped.isEmpty()) return null;
try {
return JsonUtils.readValue(stripped, Object.class);
} catch (Exception e) {
return stripped;
}
}

private static List<String> collect(Object value) {
if (value == null) return List.of();
if (value instanceof Collection<?> collection) {
return collection.stream().flatMap(item -> collect(item).stream()).toList();
}
if (value instanceof Map<?, ?> map) {
for (String key : ID_KEYS) {
if (map.get(key) instanceof String idValue && !idValue.isBlank())
return List.of(idValue.strip());
}
List<String> nested =
map.values().stream()
.filter(item -> item instanceof Map || item instanceof Collection)
.flatMap(item -> collect(item).stream())
.toList();
return nested.isEmpty() ? List.of(JsonUtils.pojoToJson(map)) : nested;
}
String str = value.toString().strip();
return str.isEmpty() ? List.of() : List.of(str);
}

private static List<String> union(List<String> left, List<String> right) {
return Stream.concat(left.stream(), right.stream()).distinct().toList();
}

private static List<String> minus(List<String> source, Collection<String> exclusions) {
Set<String> exclusionSet = new HashSet<>(exclusions);
return source.stream().filter(item -> !exclusionSet.contains(item)).toList();
}

public static Map<String, FieldDiff> buildChangeMap(ChangeDescription changeDescription) {
Map<String, FieldDiff> result = new LinkedHashMap<>();
for (FieldChange fieldChange : listOrEmpty(changeDescription.getFieldsAdded())) {
result.put(
fieldChange.getName(),
new FieldDiff(extractIdentifiers(fieldChange.getNewValue()), List.of()));
}
for (FieldChange fieldChange : listOrEmpty(changeDescription.getFieldsDeleted())) {
result.put(
fieldChange.getName(),
new FieldDiff(List.of(), extractIdentifiers(fieldChange.getOldValue())));
}
for (FieldChange fieldChange : listOrEmpty(changeDescription.getFieldsUpdated())) {
result.put(
fieldChange.getName(),
new FieldDiff(
extractIdentifiers(fieldChange.getNewValue()),
extractIdentifiers(fieldChange.getOldValue())));
}
return result;
}

public static Map<String, FieldDiff> mergeChangeMaps(
Map<String, FieldDiff> oldMap, Map<String, FieldDiff> newMap) {
Map<String, FieldDiff> merged = new LinkedHashMap<>(oldMap);
for (Map.Entry<String, FieldDiff> entry : newMap.entrySet()) {
String field = entry.getKey();
merged.put(
field,
merged.containsKey(field) ? merged.get(field).merge(entry.getValue()) : entry.getValue());
}
merged.entrySet().removeIf(entry -> entry.getValue().isEmpty());
return merged;
}

public static boolean hasNoChanges(ChangeDescription changeDescription) {
return changeDescription == null
|| (nullOrEmpty(changeDescription.getFieldsAdded())
&& nullOrEmpty(changeDescription.getFieldsUpdated())
&& nullOrEmpty(changeDescription.getFieldsDeleted()));
}

public static Map<String, FieldDiff> parseChangeMap(String message) {
if (nullOrEmpty(message) || !message.strip().startsWith("{")) return new LinkedHashMap<>();
try {
return JsonUtils.readValue(message, CHANGE_MAP_TYPE);
} catch (Exception e) {
return new LinkedHashMap<>();
}
}

public static void applyChangePreview(
Thread taskThread, EntityInterface entity, String oldMessage) {
taskThread.withCardStyle(null).withFieldOperation(null).withFeedInfo(null);
final ChangeDescription changeDescription = entity.getChangeDescription();
if (hasNoChanges(changeDescription)) {
taskThread.withMessage(oldMessage != null ? oldMessage : "{}");
return;
}
try {
Map<String, FieldDiff> merged =
mergeChangeMaps(parseChangeMap(oldMessage), buildChangeMap(changeDescription));
taskThread.withMessage(merged.isEmpty() ? "{}" : JsonUtils.pojoToJson(merged));
} catch (Exception e) {
Comment on lines +171 to +175

Copilot AI Apr 16, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

applyChangePreview() serializes the change preview into thread.message (JSON like { "tags": ... }). Thread.message is consumed as human-readable text in other channels (e.g., task assignment email templates populate taskName from thread.getMessage()), so this will leak raw JSON into email/Slack/Teams notifications and other renderers. Consider keeping message human-readable (e.g., "Approval required for") and storing the structured preview elsewhere (task fields), or prefixing with a readable string and updating UI parsing to extract only the JSON portion; alternatively update downstream notification/template renderers to detect/format the JSON payload for RequestApproval tasks.

Copilot uses AI. Check for mistakes.
LOG.warn(
"Failed to build change preview for approval task on {}",
entity.getFullyQualifiedName(),
e);
taskThread.withMessage(oldMessage != null ? oldMessage : "{}");
}
}
}
Loading
Loading