Note this :
I Create a conbination by Adding New Rule. This wil Create Event Dropdown. again I choose Ticket Create. and its fields. choices. it will come as another combination
Now the json should look like this .
{
"TicketCreate": {
"combinations": [
{
"isEnabled": true,
"fields": {
"status": "2",
"priority": "2"
}
}
]
}
}
if i want another combo with same event, i will click addnewrule and choose ticketcreate, then choosing field and choices. it should add as new combination . now the json should view like this.
{
"TicketCreate": {
"combinations": [
{
"isEnabled": true,
"fields": {
"status": "2",
"priority": "2"
}
},
{
"isEnabled": true,
"fields": {
"status": "4",
"priority": "3"
}
}
]
}
}
async function createEventDropdownSet(eventName) {
console.log("Creating Event Dropdown");
let fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let toggleContainer = container.querySelector('.toggle-container');
if (!fieldNameContainer) {
fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
container.appendChild(fieldNameContainer);
}
if (!choicesContainer) {
choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
container.appendChild(choicesContainer);
}
// If field mappings exist, initialize the fields
if (fieldMappings && fieldMappings.combinations.length > 0) {
for (const combination of fieldMappings.combinations) {
for (const [fieldName, fieldValue] of Object.entries(combination.fields)) {
await fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container, fieldName, [fieldValue]);
}
}
}
// Event listener for delete button
deleteButton.addEventListener('click', () => {
if (confirm('Are you sure you want to delete this event?')) {
container.remove();
delete ticketworkflowconditions[selectedEventValue];
console.log("Delete Event button clicked. Event removed from DOM and ticketworkflowconditions.");
}
});
// Initialize component accessibility and state
updateComponentsAccessibility(container, toggleSwitch.checked);
updateIsEnabledState(selectedEventValue, toggleSwitch.checked); // Capture initial state
function updateIsEnabledState(selectedEventValue, isChecked) {
if (!selectedEventValue) {
console.error("Event is not selected.");
return;
}
code
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
ticketworkflowconditions[selectedEventValue].combinations.forEach(combination => {
combination.isEnabled = isChecked;
});
console.log(`Toggle for ${selectedEventValue} set to ${isChecked ? 'enabled' : 'disabled'}.`);
console.log(`Updated ticketworkflowconditions after toggle change: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
}
}
async function fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container, selectedFieldName = null, selectedChoices = null) {
if (!selectedEventValue) {
console.error("fieldschoosingvalues called with an undefined selectedEventValue.");
return;
}
try {
let statusResp = await makeApiCall(apiKeyInput1.value, domainInput1.value);
code
if (statusResp && statusResp.ticket_fields) {
let fields = statusResp.ticket_fields.filter(field =>
field.field_type.startsWith('default_') &&
field.choices &&
field.choices.length > 0 &&
field.required_for_agents
);
console.log(`Starting fieldschoosingvalues with selectedEventValue: ${selectedEventValue}`);
console.log(`Mapping field name: ${selectedFieldName}`);
console.log(`Mapping choice value: ${selectedChoices}`);
if (selectedFieldName) {
const fieldContainer = document.createElement('div');
fieldContainer.classList.add('field-container');
fieldNameContainer.appendChild(fieldContainer);
const choicesDiv = document.createElement('div');
choicesDiv.classList.add('choices-container');
choicesContainer.appendChild(choicesDiv);
await getFieldnamesfrom1stapi(fieldContainer, fields, choicesDiv, selectedEventValue, buttonContainer, container, selectedFieldName, selectedChoices);
} else {
await getFieldnamesfrom1stapi(fieldNameContainer, fields, choicesContainer, selectedEventValue, buttonContainer, container);
}
} else {
console.error('No fields found or data not available');
}
} catch (error) {
console.error("Error fetching data for Dropdown:", error);
}
}
async function getFieldnamesfrom1stapi(fieldNameContainer, fields, choicesContainer, selectedEventValue, buttonContainer, container, selectedFieldName = null, selectedChoices = null) {
if (!selectedEventValue) {
console.error("Select an event before proceeding.");
return;
}
// Set the initial selected field if provided
if (selectedFieldName && field.name === selectedFieldName) {
option.setAttribute('selected', 'selected');
}
});
fieldNameContainer.appendChild(fieldDropdown);
// Initial mapping of choices in case a field is already selected
if (selectedFieldName) {
const selectedField = fields.find(field => field.name === selectedFieldName);
if (selectedField) {
await showingitschoices(choicesContainer, selectedField, selectedEventValue, selectedFieldName, buttonContainer, container, fieldNameContainer, selectedChoices);
code
// Update JSON directly with selected field and choice
ticketworkflowconditions[selectedEventValue] = ticketworkflowconditions[selectedEventValue] || { combinations: [{ isEnabled: true, fields: {} }] };
ticketworkflowconditions[selectedEventValue].combinations[0].fields[selectedFieldName] = selectedChoices ? selectedChoices[0] : null;
console.log(`Updated ticketworkflowconditions with mapped fields: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
} else {
console.error('Field not found in Dropdown');
}
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
}
});
choicesContainer.appendChild(choicesDropdown);
// Check if the button has already been added
if (!buttonContainer.querySelector('.btn-primary')) {
const addButton = document.createElement('button');
addButton.textContent = 'Add';
addButton.classList.add('btn', 'btn-primary', 'mt-2');
buttonContainer.appendChild(addButton);
The code you've provided seems to be part of a system where users can create conditions or rules for ticket events, allowing for specific fields and choices to be associated with each event type. The JSON structure captures these rule combinations for a given event. Let me help you organize and enhance the existing code to achieve a dynamic JSON-like structure. You have already provided a functional setup with multiple operations; I'll provide an explanation and note areas for possible improvements.
Key Functional Areas and Suggestions
Event Dropdown Creation:
Function: createEventDropdownSet(eventName)
Purpose: Creates a dropdown for selecting an event type.
Improvement: Ensure UI consistency by properly initializing and updating the dropdown state, especially focusing on dynamically updating the ticketworkflowconditions JSON structure.
Purpose: Initializes the dropdown and adds event listeners for toggle switches and delete buttons.
Improvement: Consider using more robust error handling to ensure UI changes are consistently mirrored in the ticketworkflowconditions object. Enhance accessibility by dynamically enabling/disabling form elements based on the toggle's state.
Field and Choices Interaction:
Function: fieldschoosingvalues(...) and getFieldnamesfrom1stapi(...)
Purpose: Populate fields and associated choices from an API, and update ticketworkflowconditions as they are selected.
Improvement: Use async/await effectively to handle API calls. Ensure data integrity in fieldMappings and ticketworkflowconditions by validating selected fields and choices.
JSON Structure Management:
Structure Creation: Make sure that when new rules/combinations with fields are added, the JSON reflects these changes accurately.
Logic: As new rules are added, dynamically update ticketworkflowconditions[selectedEvent].combinations to reflect these new combinations.
Button Actions for Adding More Rules:
Adding New Combinations: Utilize an 'Add' button to append new combinations to the existing JSON structure for the same event.
Improvement: Ensure the addition of buttons and new combination handling are intuitive for end-users. Make sure the JSON correctly appends items using array operations and maintains data consistency.
Enhancements and Considerations
Data Handling: Ensure your JavaScript logic effectively interacts with API data. Use more robust approaches for mapping API responses to UI elements.
UI/UX Consideration: UI elements such as dropdowns and switches should reflect the state of the internal JSON. Ensure clear feedback is provided when operations like 'add' or 'delete' are performed.
Debugging: Implement better console logging for improved development experience and trigger necessary updates to UI components or internal structures when events occur.
Performance: As UI operations involve DOM manipulations, focus on reducing unnecessary reflows/repaints to improve efficiency.
Implementing these suggestions should help achieve a better synergy between the UI elements and the underlying data structure, ensuring a more dynamic and responsive system.
Note this :
I Create a conbination by Adding New Rule. This wil Create Event Dropdown. again I choose Ticket Create. and its fields. choices. it will come as another combination
Now the json should look like this .
{
"TicketCreate": {
"combinations": [
{
"isEnabled": true,
"fields": {
"status": "2",
"priority": "2"
}
}
]
}
}
if i want another combo with same event, i will click addnewrule and choose ticketcreate, then choosing field and choices. it should add as new combination . now the json should view like this.
{
"TicketCreate": {
"combinations": [
{
"isEnabled": true,
"fields": {
"status": "2",
"priority": "2"
}
},
{
"isEnabled": true,
"fields": {
"status": "4",
"priority": "3"
}
}
]
}
}
async function createEventDropdownSet(eventName) {
console.log("Creating Event Dropdown");
let fieldNameContainer = container.querySelector('.field-name-container');
let choicesContainer = container.querySelector('.choices-container');
let buttonContainer = container.querySelector('.button-container');
let toggleContainer = container.querySelector('.toggle-container');
if (!fieldNameContainer) {
fieldNameContainer = document.createElement('div');
fieldNameContainer.classList.add('col-md-2', 'field-name-container');
container.appendChild(fieldNameContainer);
}
if (!choicesContainer) {
choicesContainer = document.createElement('div');
choicesContainer.classList.add('col-md-2', 'choices-container');
container.appendChild(choicesContainer);
}
// If field mappings exist, initialize the fields
if (fieldMappings && fieldMappings.combinations.length > 0) {
for (const combination of fieldMappings.combinations) {
for (const [fieldName, fieldValue] of Object.entries(combination.fields)) {
await fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container, fieldName, [fieldValue]);
}
}
}
// Event listener for delete button
deleteButton.addEventListener('click', () => {
if (confirm('Are you sure you want to delete this event?')) {
container.remove();
delete ticketworkflowconditions[selectedEventValue];
console.log("Delete Event button clicked. Event removed from DOM and ticketworkflowconditions.");
}
});
// Initialize component accessibility and state
updateComponentsAccessibility(container, toggleSwitch.checked);
updateIsEnabledState(selectedEventValue, toggleSwitch.checked); // Capture initial state
function updateIsEnabledState(selectedEventValue, isChecked) {
if (!selectedEventValue) {
console.error("Event is not selected.");
return;
}
code
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
ticketworkflowconditions[selectedEventValue].combinations.forEach(combination => {
combination.isEnabled = isChecked;
});
console.log(`Toggle for ${selectedEventValue} set to ${isChecked ? 'enabled' : 'disabled'}.`);
console.log(`Updated ticketworkflowconditions after toggle change: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
}
}
async function fieldschoosingvalues(selectedEventValue, fieldNameContainer, choicesContainer, buttonContainer, container, selectedFieldName = null, selectedChoices = null) {
if (!selectedEventValue) {
console.error("fieldschoosingvalues called with an undefined selectedEventValue.");
return;
}
try {
let statusResp = await makeApiCall(apiKeyInput1.value, domainInput1.value);
code
if (statusResp && statusResp.ticket_fields) {
let fields = statusResp.ticket_fields.filter(field =>
field.field_type.startsWith('default_') &&
field.choices &&
field.choices.length > 0 &&
field.required_for_agents
);
console.log(`Starting fieldschoosingvalues with selectedEventValue: ${selectedEventValue}`);
console.log(`Mapping field name: ${selectedFieldName}`);
console.log(`Mapping choice value: ${selectedChoices}`);
if (selectedFieldName) {
const fieldContainer = document.createElement('div');
fieldContainer.classList.add('field-container');
fieldNameContainer.appendChild(fieldContainer);
const choicesDiv = document.createElement('div');
choicesDiv.classList.add('choices-container');
choicesContainer.appendChild(choicesDiv);
await getFieldnamesfrom1stapi(fieldContainer, fields, choicesDiv, selectedEventValue, buttonContainer, container, selectedFieldName, selectedChoices);
} else {
await getFieldnamesfrom1stapi(fieldNameContainer, fields, choicesContainer, selectedEventValue, buttonContainer, container);
}
} else {
console.error('No fields found or data not available');
}
} catch (error) {
console.error("Error fetching data for Dropdown:", error);
}
}
async function getFieldnamesfrom1stapi(fieldNameContainer, fields, choicesContainer, selectedEventValue, buttonContainer, container, selectedFieldName = null, selectedChoices = null) {
if (!selectedEventValue) {
console.error("Select an event before proceeding.");
return;
}
// Set the initial selected field if provided
if (selectedFieldName && field.name === selectedFieldName) {
option.setAttribute('selected', 'selected');
}
});
fieldNameContainer.appendChild(fieldDropdown);
// Initial mapping of choices in case a field is already selected
if (selectedFieldName) {
const selectedField = fields.find(field => field.name === selectedFieldName);
if (selectedField) {
await showingitschoices(choicesContainer, selectedField, selectedEventValue, selectedFieldName, buttonContainer, container, fieldNameContainer, selectedChoices);
code
// Update JSON directly with selected field and choice
ticketworkflowconditions[selectedEventValue] = ticketworkflowconditions[selectedEventValue] || { combinations: [{ isEnabled: true, fields: {} }] };
ticketworkflowconditions[selectedEventValue].combinations[0].fields[selectedFieldName] = selectedChoices ? selectedChoices[0] : null;
console.log(`Updated ticketworkflowconditions with mapped fields: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
} else {
console.error('Field not found in Dropdown');
}
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
}
});
choicesContainer.appendChild(choicesDropdown);
// Check if the button has already been added
if (!buttonContainer.querySelector('.btn-primary')) {
const addButton = document.createElement('button');
addButton.textContent = 'Add';
addButton.classList.add('btn', 'btn-primary', 'mt-2');
buttonContainer.appendChild(addButton);
To achieve the desired behavior where a new rule (or combination) is added to your JSON structure, you need to ensure that each time a new rule is created, it is appended as a new combination for the same event. Let's detail how you should modify your code to properly add each new combination to the ticketworkflowconditions object.
Key Steps:
Modify JSON Updating Logic:
Every time a new combination is completed (i.e., event and its fields are selected), this combination should be added as a separate entry in the combinations array for that event.
Structure of ticketworkflowconditions:
Ensure that the JSON structure maintains all combinations for a given event and appends new ones rather than replacing existing ones.
Code Adjustments:
In the createEventDropdownSet Function:
Ensure that when starting a new set, it’s linked to the function that will eventually create a new entry in your JSON.
Updating the fieldschoosingvalues and showingitschoices Functions:
Change logic to append a new combination instead of altering the first one.
Here's how you can adjust your showingitschoices function to cater to this:
javascript
async function showingitschoices(
choicesContainer,
selectedField,
selectedEventValue,
selectedFieldName,
buttonContainer,
container,
fieldNameContainer,
selectedChoices = null
) {
choicesContainer.innerHTML = '';
const choicesDropdown = document.createElement('fw-select');
choicesDropdown.classList.add('choices-dropdown');
choicesDropdown.setAttribute('label', `${selectedFieldName}`);
choicesDropdown.setAttribute('required', 'true');
choicesDropdown.setAttribute('placeholder', `Choose ${selectedFieldName}`);
choicesDropdown.setAttribute('hint-text', 'Select singular option');
selectedField.choices.forEach(choice => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.id);
option.textContent = choice.value;
choicesDropdown.appendChild(option);
if (selectedChoices && selectedChoices.includes(String(choice.id))) {
option.setAttribute('selected', 'selected');
}
});
choicesContainer.appendChild(choicesDropdown);
// Check if the button has already been added
if (!buttonContainer.querySelector('.btn-primary')) {
const addButton = document.createElement('button');
addButton.textContent = 'Add';
addButton.classList.add('btn', 'btn-primary', 'mt-2');
buttonContainer.appendChild(addButton);
addButton.addEventListener('click', () => {
const newCombination = {
isEnabled: true,
fields: {
[selectedFieldName]: choicesDropdown.value
}
};
if (!ticketworkflowconditions[selectedEventValue]) {
ticketworkflowconditions[selectedEventValue] = { combinations: [] };
}
ticketworkflowconditions[selectedEventValue].combinations.push(newCombination);
console.log(`Added new combination for event: ${selectedEventValue}`);
console.log(`Updated ticketworkflowconditions: ${JSON.stringify(ticketworkflowconditions, null, 2)}`);
// Optionally reset fields for next input
fieldNameContainer.innerHTML = '';
choicesContainer.innerHTML = '';
createAdditionalDropdowns(container);
});
}
choicesDropdown.addEventListener('fwChange', (event) => {
const selectedChoiceId = event.target.value;
// Note: At this point just capture the efficient fields mapping to add later
console.log(`Selected choice for field: ${selectedFieldName}, choice: ${selectedChoiceId}`);
});
}
Explanation:
New Combination: Each time a user clicks 'Add', a new combination (newCombination) is created and added to the combinations array for the selected event.
Maintain JSON Structure: By using .push(), new entries are added without overwriting existing data.
Visual Feedback and Adjustments: Consider resetting or clearing current selections after a combination is recorded to improve user experience and avoid accidental duplicate entries.
This approach keeps the interaction intuitive and managing combinations straightforward, aligning closely with the desired output JSON format.