iachat/app/javascript/dashboard/helper/validations.js
Cayo P. R. Oliveira f9d1146cb0
feat: mensagens agendadas (#198)
* feat:  Adds model for scheduling messages

* feat: Implement scheduled message handling and processing jobs

* feat: Add ScheduledMessagesController and associated specs for managing scheduled messages

* refactor: Simplify scheduled message job specs and improve metadata handling

* feat: Add ScheduledMessagePolicy for managing access to scheduled messages

* feat: Add routes for managing scheduled messages

* feat: Add scheduled message event handling and broadcasting

* feat: Add JSON views for scheduled messages creation, destruction, updating, and indexing

* feat: Update scheduled message status and dispatch update event after message creation

* feat: Ensure scheduled message updates trigger dispatch event

* feat: Add mutation types for managing scheduled messages

* feat: Add additionalAttributes prop to Message component and provider

* feat: Implement scheduled message handling in ActionCable and Vuex store

* feat: Add unit tests for scheduled messages actions and mutations

* feat: implement scheduled messages functionality

- Added support for scheduling messages in the conversation dashboard.
- Introduced new components: ScheduledMessageModal and ScheduledMessages for managing scheduled messages.
- Enhanced ReplyBottomPanel to include scheduling options.
- Updated Base.vue to handle scheduled message styling.
- Integrated Vuex store module for managing scheduled messages state.
- Added necessary translations for scheduled messages in English and Portuguese.

* feat: add pagination to scheduled messages index and update tests accordingly

* chore: update scheduled messages specs for future time validation and response status

* chore: enhance scheduled messages API with pagination and add skeleton loader component

* feat: add create_scheduled_message action to automation rule attributes

* feat: implement create_scheduled_message action and enhance attachment handling

* feat: add scheduled message functionality with UI components and localization

* test: enhance scheduledMessages mutations tests with meta handling and structure

* chore: update label to display file name upon successful upload in AutomationFileInput component

* feat: add initialAttachment prop to ScheduledMessageModal and update ReplyBox to pass attachment

* chore: prepend_mod_with to ScheduledMessagesController for better module handling

* fix: attachment visibility in ScheduledMessageItem component

* chore: enhance ScheduledMessage model with validations and reduce controller load

* refactor: simplify ScheduledMessagesAPI methods by removing unnecessary instance variable

* chore: update event emission for scheduled message creation in ReplyBox and ScheduledMessageModal

* refactor: update status configuration to use label keys

* chore: update date formatting in ScheduledMessageItem component

* refactor: collapse logic to checkOverflow and update related functionality

* chore: add author indication for current user in scheduled messages

* chore: enhance scheduled message metadata with author information and localization

* fix: send message shortcut

* chore: handle errors in scheduled message submission

* chore: update scheduled message modal to use combined date and time input

* chore: refactor scheduled messages handling to remove pagination and update related tests

* fix: ensure scheduled messages update status and dispatch on failure

* fix: update scheduled message due date logic and simplify sending checks

* refactor: rename build_message method for send_message

* fix: update scheduled message creation time and improve test reliability

* chore: ignore unnecessary check

* chore: add scheduled message metadata handling  in message builder, add scheduled message factorie and update specs

* refactor: use scheduled message factorie creation in specs

* chore: streamline error handling in scheduled message job and remove dispatch logic

* fix: change scheduled_messages association to destroy dependent records

* refactor: remove unused attributes from scheduled message payload builder

* chore: update scheduled message retrieval to use conversation association

* chore: correct cron format for scheduled messages job

* chore: remove migration for author_type in scheduled_messages

* feat: enhance scheduled messages management with delete confirmation and error handling

* chore: set cron poll interval to 10 seconds for improved scheduling precision

* feat: include additional_attributes in message JSON response

* feat: enhance scheduled message validation and localization support

* chore: update scheduled message display

* Merge branch 'main' into Cayo-Oliveira/CU-86aenh268/Mensagens-agendadas

* feat: add scheduled message indicators and validation for message length

* fix: remove unnecessary condition from line-clamp class binding

* feat: update scheduled messages localization and enhance content validation

* feat: update scheduled messages order, enhance scheduledAt computation, and add message association

* fix: reorder condition for Facebook channel message length computation

* fix:  change detection for attachments in scheduled messages

* fix: remove unnecessary colon from close-on-backdrop-click prop in ScheduledMessageModal

* chore: add error handling for scheduled message deletion and update localization for delete failure

* fix: enforce minimum delay of 1 minute for scheduled messages and update validation

* fix: remove unused private property and improve locale formatting for scheduled messages

* fix: adjust positioning of DropdownBody in ReplyBottomPanel and clean up schema foreign keys

* docs: add scheduled messages management APIs and payload definitions

---------

Co-authored-by: gabrieljablonski <contact@gabrieljablonski.com>
2026-01-30 22:08:16 -03:00

205 lines
6.2 KiB
JavaScript

export const ATTRIBUTE_KEY_REQUIRED = 'ATTRIBUTE_KEY_REQUIRED';
export const FILTER_OPERATOR_REQUIRED = 'FILTER_OPERATOR_REQUIRED';
export const VALUE_REQUIRED = 'VALUE_REQUIRED';
export const VALUE_MUST_BE_BETWEEN_1_AND_998 =
'VALUE_MUST_BE_BETWEEN_1_AND_998';
export const ACTION_PARAMETERS_REQUIRED = 'ACTION_PARAMETERS_REQUIRED';
export const ATLEAST_ONE_CONDITION_REQUIRED = 'ATLEAST_ONE_CONDITION_REQUIRED';
export const ATLEAST_ONE_ACTION_REQUIRED = 'ATLEAST_ONE_ACTION_REQUIRED';
const isEmptyValue = value => {
if (!value) {
return true;
}
if (Array.isArray(value)) {
return !value.length;
}
// We can safely check the type here as both the null value
// and the array is ruled out earlier.
if (typeof value === 'object') {
return !Object.keys(value).length;
}
return false;
};
// ------------------------------------------------------------------
// ------------------------ Filter Validation -----------------------
// ------------------------------------------------------------------
/**
* Validates a single filter for conversations or contacts.
*
* @param {Object} filter - The filter object to validate.
* @param {string} filter.attribute_key - The key of the attribute to filter on.
* @param {string} filter.filter_operator - The operator to use for filtering.
* @param {string|number|Array} [filter.values] - The value(s) to filter by (required for most operators).
*
* @returns {string|null} An error message if validation fails, or null if validation passes.
*/
export const validateSingleFilter = filter => {
if (!filter.attribute_key) {
return ATTRIBUTE_KEY_REQUIRED;
}
if (!filter.filter_operator) {
return FILTER_OPERATOR_REQUIRED;
}
const operatorRequiresValue = !['is_present', 'is_not_present'].includes(
filter.filter_operator
);
if (operatorRequiresValue && isEmptyValue(filter.values)) {
return VALUE_REQUIRED;
}
if (
filter.filter_operator === 'days_before' &&
(parseInt(filter.values, 10) <= 0 || parseInt(filter.values, 10) >= 999)
) {
return VALUE_MUST_BE_BETWEEN_1_AND_998;
}
return null;
};
// ------------------------------------------------------------------
// ---------------------- Automation Validation ---------------------
// ------------------------------------------------------------------
/**
* Validates the basic fields of an automation object.
*
* @param {Object} automation - The automation object to validate.
* @returns {Object} An object containing any validation errors.
*/
const validateBasicFields = automation => {
const errors = {};
const requiredFields = ['name', 'description', 'event_name'];
requiredFields.forEach(field => {
if (!automation[field]) {
errors[field] = `${
field.charAt(0).toUpperCase() + field.slice(1)
} is required`;
}
});
return errors;
};
/**
* Validates the conditions of an automation object.
*
* @param {Array} conditions - The conditions to validate.
* @returns {Object} An object containing any validation errors.
*/
export const validateConditions = conditions => {
const errors = {};
if (!conditions || conditions.length === 0) {
errors.conditions = ATLEAST_ONE_CONDITION_REQUIRED;
return errors;
}
conditions.forEach((condition, index) => {
const error = validateSingleFilter(condition);
if (error) {
errors[`condition_${index}`] = error;
}
});
return errors;
};
/**
* Validates a single action of an automation object.
*
* @param {Object} action - The action to validate.
* @returns {string|null} An error message if validation fails, or null if validation passes.
*/
const validateSingleAction = action => {
const noParamActions = [
'mute_conversation',
'snooze_conversation',
'resolve_conversation',
'remove_assigned_team',
'open_conversation',
];
if (
!noParamActions.includes(action.action_name) &&
(!action.action_params || action.action_params.length === 0)
) {
return ACTION_PARAMETERS_REQUIRED;
}
if (action.action_name === 'create_scheduled_message') {
const params = action.action_params?.[0];
if (!params || typeof params !== 'object') {
return ACTION_PARAMETERS_REQUIRED;
}
const hasContent = params.content?.trim?.();
const hasAttachment = params.blob_id;
const hasDelay = params.delay_minutes && params.delay_minutes >= 1;
if (!hasContent && !hasAttachment) {
return ACTION_PARAMETERS_REQUIRED;
}
if (!hasDelay) {
return ACTION_PARAMETERS_REQUIRED;
}
}
return null;
};
/**
* Validates the actions of an automation object.
*
* @param {Array} actions - The actions to validate.
* @returns {Object} An object containing any validation errors.
*/
export const validateActions = actions => {
if (!actions || actions.length === 0) {
return { actions: ATLEAST_ONE_ACTION_REQUIRED };
}
return actions.reduce((errors, action, index) => {
const error = validateSingleAction(action);
if (error) {
errors[`action_${index}`] = error;
}
return errors;
}, {});
};
/**
* Validates an automation object.
*
* @param {Object} automation - The automation object to validate.
* @param {string} automation.name - The name of the automation.
* @param {string} automation.description - The description of the automation.
* @param {string} automation.event_name - The name of the event that triggers the automation.
* @param {Array} automation.conditions - An array of condition objects for the automation.
* @param {string} automation.conditions[].filter_operator - The operator for the condition.
* @param {string|number} [automation.conditions[].values] - The value(s) for the condition.
* @param {Array} automation.actions - An array of action objects for the automation.
* @param {string} automation.actions[].action_name - The name of the action.
* @param {Array} [automation.actions[].action_params] - The parameters for the action.
*
* @returns {Object} An object containing any validation errors.
*/
export const validateAutomation = automation => {
const basicErrors = validateBasicFields(automation);
const conditionErrors = validateConditions(automation.conditions);
const actionErrors = validateActions(automation.actions);
return {
...basicErrors,
...conditionErrors,
...actionErrors,
};
};