Implemented the functionality to add a WL Action
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
function createWorkloadActionForm({ MODAL_ID, allowsCrmActivities, isMissingAction, getOpportunity, formatDate, createCloseIcon, environment }) {
|
||||
function createWorkloadActionForm({ MODAL_ID, allowsCrmActivities, isMissingAction, getOpportunity, getProducts,
|
||||
requestTeamMembers, requestLookup, getCurrentUserId, saveAction, onActionSaved, notify, formatDate, createCloseIcon, environment }) {
|
||||
const { document } = environment;
|
||||
let active = null;
|
||||
function element(tag, className, text) {
|
||||
@@ -7,8 +8,112 @@ function createWorkloadActionForm({ MODAL_ID, allowsCrmActivities, isMissingActi
|
||||
if (text !== undefined) node.textContent = text;
|
||||
return node;
|
||||
}
|
||||
function searchableSelect(select, field, onChange) {
|
||||
const box = element("div", "opportunities-extension-action-combobox");
|
||||
const input = element("input");
|
||||
input.type = "text";
|
||||
input.autocomplete = "off";
|
||||
input.required = !!select.required;
|
||||
input.setAttribute("aria-required", String(!!select.required));
|
||||
select.addEventListener("invalid", event => { event.preventDefault(); input.focus(); });
|
||||
input.id = `${select.id}-search`;
|
||||
field.htmlFor = input.id;
|
||||
const list = element("div", "opportunities-extension-action-options");
|
||||
list.id = `${select.id}-options`;
|
||||
list.setAttribute("role", "listbox");
|
||||
input.setAttribute("role", "combobox");
|
||||
input.setAttribute("aria-autocomplete", "list");
|
||||
input.setAttribute("aria-controls", list.id);
|
||||
input.setAttribute("aria-expanded", "false");
|
||||
select.hidden = true;
|
||||
select.tabIndex = -1;
|
||||
box.append(input, list);
|
||||
field.append(box);
|
||||
let matches = [], index = -1;
|
||||
const options = () => Array.from(select.children).filter(item => item.value);
|
||||
const normalize = value => String(value).normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
|
||||
function closeList() {
|
||||
list.hidden = true;
|
||||
input.setAttribute("aria-expanded", "false");
|
||||
input.setAttribute("aria-activedescendant", "");
|
||||
}
|
||||
function sync() {
|
||||
closeList();
|
||||
input.disabled = !!select.disabled;
|
||||
input.placeholder = select.children[0]?.textContent || "Select";
|
||||
input.value = options().find(item => item.value === select.value)?.textContent || "";
|
||||
input.title = input.value;
|
||||
}
|
||||
function highlight() {
|
||||
Array.from(list.children).forEach((node, i) => node.setAttribute("aria-selected", String(i === index)));
|
||||
input.setAttribute("aria-activedescendant", matches[index] ? `${list.id}-${index}` : "");
|
||||
list.children[index]?.scrollIntoView?.({ block: "nearest" });
|
||||
}
|
||||
function choose(i) {
|
||||
if (!matches[i]) return;
|
||||
const changed = select.value !== matches[i].value;
|
||||
select.value = matches[i].value;
|
||||
sync();
|
||||
if (changed) onChange?.();
|
||||
}
|
||||
function positionList() {
|
||||
const bounds = input.closest?.(".opportunities-extension-action-form-dialog")?.getBoundingClientRect();
|
||||
const anchor = input.getBoundingClientRect?.();
|
||||
if (!bounds || !anchor) return;
|
||||
const below = Math.max(0, bounds.bottom - anchor.bottom - 8);
|
||||
const above = Math.max(0, anchor.top - bounds.top - 8);
|
||||
const opensAbove = below < 180 && above > below;
|
||||
list.setAttribute("data-placement", opensAbove ? "above" : "below");
|
||||
list.style.maxHeight = `${Math.min(180, opensAbove ? above : below)}px`;
|
||||
}
|
||||
function render(query = "") {
|
||||
if (input.disabled) return;
|
||||
matches = options().filter(item => normalize(`${item.textContent} ${item.value}`).includes(normalize(query)));
|
||||
index = -1;
|
||||
list.textContent = "";
|
||||
matches.forEach((item, i) => {
|
||||
const row = element("div", "opportunities-extension-action-option", item.textContent);
|
||||
row.id = `${list.id}-${i}`;
|
||||
row.setAttribute("role", "option");
|
||||
row.setAttribute("aria-selected", "false");
|
||||
row.addEventListener("mousedown", event => event.preventDefault());
|
||||
row.addEventListener("click", event => { event.preventDefault(); choose(i); });
|
||||
list.append(row);
|
||||
});
|
||||
if (!matches.length) {
|
||||
const empty = element("div", "opportunities-extension-action-option", "No results");
|
||||
empty.setAttribute("role", "status");
|
||||
list.append(empty);
|
||||
}
|
||||
positionList();
|
||||
list.hidden = false;
|
||||
input.setAttribute("aria-expanded", "true");
|
||||
input.setAttribute("aria-activedescendant", "");
|
||||
}
|
||||
input.addEventListener("click", () => { render(); input.select?.(); });
|
||||
input.addEventListener("input", () => render(input.value));
|
||||
input.addEventListener("blur", sync);
|
||||
input.addEventListener("keydown", event => {
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
||||
event.preventDefault();
|
||||
if (list.hidden) render();
|
||||
if (matches.length) index = (index + (event.key === "ArrowDown" ? 1 : index < 0 ? 0 : -1) + matches.length) % matches.length;
|
||||
highlight();
|
||||
} else if (event.key === "Enter" && !list.hidden) {
|
||||
event.preventDefault();
|
||||
choose(index < 0 && matches.length === 1 ? 0 : index);
|
||||
} else if (event.key === "Escape" && !list.hidden) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
sync();
|
||||
} else if (event.key === "Tab") sync();
|
||||
});
|
||||
sync();
|
||||
return { input, sync };
|
||||
}
|
||||
function close(restoreFocus = true) {
|
||||
if (!active) return false;
|
||||
if (active.saving) return true;
|
||||
const previous = active;
|
||||
active = null;
|
||||
previous.modal.remove();
|
||||
@@ -61,23 +166,52 @@ function createWorkloadActionForm({ MODAL_ID, allowsCrmActivities, isMissingActi
|
||||
dismiss.addEventListener("click", () => close());
|
||||
header.append(heading, dismiss);
|
||||
const form = element("form", "opportunities-extension-action-form");
|
||||
// Form-only version: never submit or navigate until the API contract is provided.
|
||||
form.addEventListener("submit", event => event.preventDefault());
|
||||
form.noValidate = true;
|
||||
const workloads = [...new Map(getProducts(optyNumber).filter(product => /^\d+$/.test(String(product?.RevnId ?? "")))
|
||||
.map(product => [String(product.RevnId), product])).entries()];
|
||||
const workloadField = element("label", "opportunities-extension-action-form-field opportunities-extension-action-form-wide");
|
||||
const workload = element("select");
|
||||
workload.id = "opportunities-extension-action-form-workload";
|
||||
workloadField.htmlFor = workload.id;
|
||||
function option(select, value, label) {
|
||||
const item = element("option", "", label);
|
||||
item.value = value;
|
||||
select.append(item);
|
||||
}
|
||||
option(workload, "", "Select workload");
|
||||
for (const [id, product] of workloads) option(workload, id, `${product.WorkloadName_c || product.ProdGroupName || "Workload"} (${id})`);
|
||||
workload.value = workloads.length === 1 ? workloads[0][0] : "";
|
||||
workloadField.hidden = workloads.length <= 1;
|
||||
workloadField.append(element("span", "", "Workload"), workload);
|
||||
const status = element("p", "opportunities-extension-action-form-status opportunities-extension-action-form-wide");
|
||||
status.setAttribute("role", "status");
|
||||
form.append(workloadField, status);
|
||||
const searchable = new Map();
|
||||
searchable.set(workload, searchableSelect(workload, workloadField, () => loadOptions()));
|
||||
const fields = [];
|
||||
const selects = [];
|
||||
const lookupKeys = { role: "WWB_ACTION_ROLE", action: "WWB_ACTION_NAME", team: "WWB_ACTION_TEAM",
|
||||
status: "WWB_ACTION_STATUS", complexity: "WWB_ACTION_COMPLEXITY" };
|
||||
for (const [name, label, type] of [
|
||||
["team", "Team", "text"], ["startDate", "Start date", "date"],
|
||||
["endDate", "End Date", "date"], ["status", "Status", "text"],
|
||||
["complexity", "Complexity", "text"], ["notes", "Notes", "textarea"]
|
||||
["owner", "Owner", "select"], ["role", "Role", "select"], ["action", "Action", "select"],
|
||||
["team", "Team", "select"], ["startDate", "Start date", "date"],
|
||||
["endDate", "End Date", "date"], ["status", "Status", "select"],
|
||||
["complexity", "Complexity", "select"], ["notes", "Notes", "textarea"]
|
||||
]) {
|
||||
const field = element("label", "opportunities-extension-action-form-field");
|
||||
const input = element(type === "textarea" ? "textarea" : "input");
|
||||
if (type !== "textarea") input.type = type;
|
||||
else input.rows = 5;
|
||||
const input = element(type === "select" || type === "textarea" ? type : "input");
|
||||
if (type === "select") selects.push({ input, label, name });
|
||||
else if (type === "textarea") input.rows = 5;
|
||||
else input.type = type;
|
||||
input.disabled = true;
|
||||
input.required = name !== "notes";
|
||||
input.setAttribute("aria-required", String(input.required));
|
||||
input.name = name;
|
||||
input.id = `opportunities-extension-action-form-${name}`;
|
||||
field.htmlFor = input.id;
|
||||
if (name === "notes" || name === "team") field.className += " opportunities-extension-action-form-wide";
|
||||
field.append(element("span", "", label), input);
|
||||
if (["notes", "team", "action"].includes(name)) field.className += " opportunities-extension-action-form-wide";
|
||||
field.append(element("span", "", `${label} (${input.required ? "required" : "optional"})`), input);
|
||||
if (type === "select") searchable.set(input, searchableSelect(input, field));
|
||||
form.append(field);
|
||||
fields.push(input);
|
||||
}
|
||||
@@ -85,27 +219,189 @@ function createWorkloadActionForm({ MODAL_ID, allowsCrmActivities, isMissingActi
|
||||
const save = element("button", "opportunities-extension-action-form-save", "Save");
|
||||
save.type = "submit";
|
||||
save.disabled = true;
|
||||
save.title = "Gravacao ainda nao disponivel";
|
||||
save.title = "Save Action";
|
||||
const retry = element("button", "", "Retry");
|
||||
retry.type = "button";
|
||||
retry.hidden = true;
|
||||
const cancel = element("button", "", "Cancel");
|
||||
cancel.type = "button";
|
||||
cancel.addEventListener("click", () => close());
|
||||
footer.append(save, cancel);
|
||||
footer.append(retry, save, cancel);
|
||||
form.append(footer);
|
||||
dialog.append(header, form);
|
||||
modal.append(dialog);
|
||||
host.append(modal);
|
||||
active = { modal, trigger };
|
||||
const view = { modal, trigger, generation: 0, lookup: null, loadingId: null };
|
||||
active = view;
|
||||
const isOpen = () => active === view && allowsCrmActivities();
|
||||
let ready = false;
|
||||
function validate() {
|
||||
const invalid = [];
|
||||
const value = name => String(fields.find(field => field.name === name)?.value || "").trim();
|
||||
for (const field of fields) {
|
||||
let valid = !field.required || !!value(field.name);
|
||||
if (field.required && searchable.has(field)) valid = Array.from(field.children).some(option => option.value && option.value === field.value);
|
||||
if (field.type === "date") {
|
||||
const date = value(field.name);
|
||||
valid = /^\d{4}-\d{2}-\d{2}$/.test(date) && Number.isFinite(Date.parse(`${date}T00:00:00.000Z`));
|
||||
if (valid) valid = new Date(`${date}T00:00:00.000Z`).toISOString().slice(0, 10) === date;
|
||||
if (field.name === "endDate" && value("startDate") > date) valid = false;
|
||||
}
|
||||
const control = searchable.get(field)?.input || field;
|
||||
control.setAttribute("aria-invalid", String(!valid));
|
||||
if (!valid) invalid.push(control);
|
||||
}
|
||||
return { invalid, value };
|
||||
}
|
||||
form.addEventListener("submit", async event => {
|
||||
event.preventDefault();
|
||||
if (!ready || !isOpen() || view.saving) return;
|
||||
const { invalid, value } = validate();
|
||||
if (invalid.length) {
|
||||
status.hidden = false;
|
||||
status.setAttribute("role", "alert");
|
||||
status.textContent = "Complete the highlighted required fields. End date must be on or after start date.";
|
||||
invalid[0].focus();
|
||||
return;
|
||||
}
|
||||
const userId = getCurrentUserId();
|
||||
if (!userId) { notify("Unable to save: current user is unavailable.", true); return; }
|
||||
const payload = { parentType: "WORKLOAD", parentId: workload.value, action: {
|
||||
ownerEmail: value("owner"), role: value("role"), name: value("action"), team: value("team"), tags: "",
|
||||
startDate: `${value("startDate")}T00:00:00.000Z`, endDate: `${value("endDate")}T00:00:00.000Z`,
|
||||
status: value("status"), complexity: value("complexity"), notes: value("notes") ? [value("notes")] : [],
|
||||
objective: "", createdBy: userId, updatedBy: userId
|
||||
} };
|
||||
view.saving = true;
|
||||
save.disabled = cancel.disabled = dismiss.disabled = workload.disabled = true;
|
||||
fields.forEach(field => { field.disabled = true; });
|
||||
searchable.forEach(control => control.sync());
|
||||
save.textContent = "Saving...";
|
||||
form.setAttribute("aria-busy", "true");
|
||||
status.hidden = true;
|
||||
try {
|
||||
const result = await saveAction(payload, isOpen);
|
||||
if (!result) return;
|
||||
view.saving = false;
|
||||
close();
|
||||
try {
|
||||
await onActionSaved(optyNumber, payload.parentId, result.result, payload.action);
|
||||
} catch {
|
||||
notify("Action saved, but the local badge could not be updated.", true);
|
||||
return;
|
||||
}
|
||||
notify("Action saved successfully.");
|
||||
} catch (error) {
|
||||
status.hidden = false;
|
||||
status.setAttribute("role", "alert");
|
||||
status.textContent = error.message || "Unable to save Action.";
|
||||
notify(status.textContent, true);
|
||||
} finally {
|
||||
view.saving = false;
|
||||
if (active === view) {
|
||||
save.disabled = cancel.disabled = dismiss.disabled = workload.disabled = false;
|
||||
fields.forEach(field => { field.disabled = false; });
|
||||
searchable.forEach(control => control.sync());
|
||||
save.textContent = "Save";
|
||||
form.setAttribute("aria-busy", "false");
|
||||
}
|
||||
}
|
||||
});
|
||||
const settled = promise => promise.then(result => ({ result }), error => ({ error }));
|
||||
async function loadOptions(refresh = false) {
|
||||
const id = workload.value;
|
||||
if (!isOpen() || (view.loadingId === id && !refresh)) return;
|
||||
const generation = ++view.generation;
|
||||
const isCurrent = () => isOpen() && view.generation === generation;
|
||||
ready = false;
|
||||
save.disabled = true;
|
||||
retry.hidden = true;
|
||||
status.hidden = false;
|
||||
status.setAttribute("role", "status");
|
||||
fields.forEach(input => { input.disabled = true; });
|
||||
selects.forEach(({ input }) => { input.textContent = ""; option(input, "", "Loading..."); });
|
||||
const syncSearch = () => selects.forEach(({ input }) => searchable.get(input).sync());
|
||||
syncSearch();
|
||||
if (!workloads.length) {
|
||||
form.setAttribute("data-state", "error");
|
||||
form.setAttribute("aria-busy", "false");
|
||||
status.setAttribute("role", "alert");
|
||||
status.textContent = "No product with a valid RevnId is available for this opportunity.";
|
||||
selects.forEach(({ input }) => { input.textContent = ""; option(input, "", "Unavailable"); });
|
||||
syncSearch();
|
||||
return;
|
||||
}
|
||||
if (!view.lookup || refresh) view.lookup = settled(requestLookup(isOpen));
|
||||
if (!workloads.some(([value]) => value === id)) {
|
||||
view.loadingId = null;
|
||||
form.setAttribute("data-state", "waiting");
|
||||
form.setAttribute("aria-busy", "false");
|
||||
status.textContent = "Select a workload to load Action options.";
|
||||
return;
|
||||
}
|
||||
view.loadingId = id;
|
||||
form.setAttribute("data-state", "loading");
|
||||
form.setAttribute("aria-busy", "true");
|
||||
status.textContent = "Loading Action options...";
|
||||
try {
|
||||
const [lookup, team] = await Promise.all([view.lookup, settled(requestTeamMembers(id, isCurrent))]);
|
||||
if (!isCurrent()) return;
|
||||
if (lookup.error || team.error) throw lookup.error || team.error;
|
||||
const values = selects.map(({ name }) => name === "owner"
|
||||
? team.result.members.map(({ email }) => ({ code: email, name: email }))
|
||||
: lookup.result.lookups[lookupKeys[name]]);
|
||||
const defaults = { owner: getCurrentUserId(), role: "Cloud Architect",
|
||||
action: "Success Plan & Consumption review", status: "Complete" };
|
||||
const normalize = value => String(value ?? "").trim().toLowerCase();
|
||||
for (const [index, { input, label, name }] of selects.entries()) {
|
||||
input.textContent = "";
|
||||
option(input, "", values[index].length ? `Select ${label.toLowerCase()}` : "No options available");
|
||||
for (const item of values[index]) option(input, item.code, item.name);
|
||||
const match = defaults[name] && values[index].find(item =>
|
||||
normalize(name === "owner" ? item.code : item.name) === normalize(defaults[name]));
|
||||
input.value = match ? match.code : "";
|
||||
}
|
||||
fields.forEach(input => { input.disabled = false; });
|
||||
selects.forEach(({ input }, index) => { input.disabled = !values[index].length; });
|
||||
form.setAttribute("data-state", "ready");
|
||||
ready = true;
|
||||
save.disabled = false;
|
||||
status.hidden = true;
|
||||
syncSearch();
|
||||
if (document.activeElement === dismiss) {
|
||||
const first = fields.find(field => !field.disabled);
|
||||
(searchable.get(first)?.input || first)?.focus();
|
||||
}
|
||||
} catch (error) {
|
||||
if (!isCurrent()) return;
|
||||
form.setAttribute("data-state", "error");
|
||||
status.setAttribute("role", "alert");
|
||||
status.textContent = error.message || "Unable to load Action options.";
|
||||
selects.forEach(({ input }) => { input.textContent = ""; option(input, "", "Unavailable"); });
|
||||
syncSearch();
|
||||
retry.hidden = false;
|
||||
} finally {
|
||||
if (isCurrent()) { view.loadingId = null; form.setAttribute("aria-busy", "false"); }
|
||||
}
|
||||
}
|
||||
retry.addEventListener("click", () => { if (!view.loadingId) loadOptions(true); });
|
||||
workload.addEventListener("change", () => loadOptions());
|
||||
modal.addEventListener("click", event => { if (event.target === modal) close(); });
|
||||
modal.addEventListener("keydown", event => {
|
||||
if (event.key !== "Tab") return;
|
||||
const controls = [dismiss, ...fields, cancel];
|
||||
const controls = [dismiss, ...(!workloadField.hidden ? [workload] : []), ...fields, retry, save, cancel]
|
||||
.map(control => searchable.get(control)?.input || control)
|
||||
.filter(control => !control.disabled && !control.hidden);
|
||||
const index = controls.indexOf(document.activeElement);
|
||||
if (!controls.length) { event.preventDefault(); return; }
|
||||
if (index === -1 || (!event.shiftKey && index === controls.length - 1) || (event.shiftKey && index === 0)) {
|
||||
event.preventDefault();
|
||||
controls[event.shiftKey ? controls.length - 1 : 0].focus();
|
||||
}
|
||||
});
|
||||
fields[0].focus();
|
||||
if (!workloadField.hidden) searchable.get(workload).input.focus();
|
||||
else dismiss.focus();
|
||||
loadOptions();
|
||||
}
|
||||
return { createButton, open, close };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user