mirror of
https://github.com/xtr-dev/payload-automation.git
synced 2025-12-11 17:23:23 +00:00
Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e138176878 | |||
| 6245a71516 | |||
| 59a97e519e | |||
| b3d2877f0a | |||
| c050ee835a | |||
| 1f80028042 | |||
| 14d1ecf036 | |||
| 3749881d5f | |||
| c46b58f43e | |||
| 398a2d160e |
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "@xtr-dev/payload-workflows",
|
"name": "@xtr-dev/payload-workflows",
|
||||||
"version": "0.0.30",
|
"version": "0.0.35",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@xtr-dev/payload-workflows",
|
"name": "@xtr-dev/payload-workflows",
|
||||||
"version": "0.0.30",
|
"version": "0.0.35",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"jsonpath-plus": "^10.3.0",
|
"jsonpath-plus": "^10.3.0",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@xtr-dev/payload-automation",
|
"name": "@xtr-dev/payload-automation",
|
||||||
"version": "0.0.30",
|
"version": "0.0.35",
|
||||||
"description": "PayloadCMS Automation Plugin - Comprehensive workflow automation system with visual workflow building, execution tracking, and step types",
|
"description": "PayloadCMS Automation Plugin - Comprehensive workflow automation system with visual workflow building, execution tracking, and step types",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
|||||||
@@ -319,17 +319,45 @@ export const createWorkflowCollection: <T extends string>(options: WorkflowsPlug
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
...(steps || []).flatMap(step => (step.inputSchema || []).map(field => ({
|
...(steps || []).flatMap(step => (step.inputSchema || []).map(field => {
|
||||||
...field,
|
const originalName = (field as any).name;
|
||||||
admin: {
|
const resultField: any = {
|
||||||
...(field.admin || {}),
|
...field,
|
||||||
condition: (...args) => args[1]?.step === step.slug && (
|
// Prefix field name with step slug to avoid conflicts
|
||||||
field.admin?.condition ?
|
name: `__step_${step.slug}_${originalName}`,
|
||||||
field.admin.condition.call(this, ...args) :
|
admin: {
|
||||||
true
|
...(field.admin || {}),
|
||||||
),
|
condition: (...args: any[]) => args[1]?.step === step.slug && (
|
||||||
},
|
(field.admin as any)?.condition ?
|
||||||
} as Field))),
|
(field.admin as any).condition.call(this, ...args) :
|
||||||
|
true
|
||||||
|
),
|
||||||
|
},
|
||||||
|
virtual: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add hooks to store/retrieve from the step's input data
|
||||||
|
resultField.hooks = {
|
||||||
|
...((field as any).hooks || {}),
|
||||||
|
afterRead: [
|
||||||
|
...(((field as any).hooks)?.afterRead || []),
|
||||||
|
({ siblingData }: any) => {
|
||||||
|
// Read from step input data using original field name
|
||||||
|
return siblingData?.[originalName] || (field as any).defaultValue;
|
||||||
|
}
|
||||||
|
],
|
||||||
|
beforeChange: [
|
||||||
|
...(((field as any).hooks)?.beforeChange || []),
|
||||||
|
({ siblingData, value }: any) => {
|
||||||
|
// Store in step data using original field name
|
||||||
|
siblingData[originalName] = value;
|
||||||
|
return undefined; // Don't store the prefixed field
|
||||||
|
}
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
return resultField as Field;
|
||||||
|
})),
|
||||||
{
|
{
|
||||||
name: 'dependencies',
|
name: 'dependencies',
|
||||||
type: 'text',
|
type: 'text',
|
||||||
|
|||||||
@@ -990,12 +990,6 @@ export class WorkflowExecutor {
|
|||||||
previousDoc: unknown,
|
previousDoc: unknown,
|
||||||
req: PayloadRequest
|
req: PayloadRequest
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
console.log('🚨 EXECUTOR: executeTriggeredWorkflows called!')
|
|
||||||
console.log('🚨 EXECUTOR: Collection =', collection)
|
|
||||||
console.log('🚨 EXECUTOR: Operation =', operation)
|
|
||||||
console.log('🚨 EXECUTOR: Doc ID =', (doc as any)?.id)
|
|
||||||
console.log('🚨 EXECUTOR: Has payload?', !!this.payload)
|
|
||||||
console.log('🚨 EXECUTOR: Has logger?', !!this.logger)
|
|
||||||
|
|
||||||
this.logger.info({
|
this.logger.info({
|
||||||
collection,
|
collection,
|
||||||
@@ -1032,13 +1026,7 @@ export class WorkflowExecutor {
|
|||||||
this.logger.debug({
|
this.logger.debug({
|
||||||
workflowId: workflow.id,
|
workflowId: workflow.id,
|
||||||
workflowName: workflow.name,
|
workflowName: workflow.name,
|
||||||
triggerCount: triggers?.length || 0,
|
triggerCount: triggers?.length || 0
|
||||||
triggers: triggers?.map(t => ({
|
|
||||||
type: t.type,
|
|
||||||
collection: t.parameters?.collection,
|
|
||||||
collectionSlug: t.parameters?.collectionSlug,
|
|
||||||
operation: t.parameters?.operation
|
|
||||||
}))
|
|
||||||
}, 'Checking workflow triggers')
|
}, 'Checking workflow triggers')
|
||||||
|
|
||||||
const matchingTriggers = triggers?.filter(trigger =>
|
const matchingTriggers = triggers?.filter(trigger =>
|
||||||
@@ -1087,12 +1075,9 @@ export class WorkflowExecutor {
|
|||||||
collection,
|
collection,
|
||||||
operation,
|
operation,
|
||||||
condition: trigger.condition,
|
condition: trigger.condition,
|
||||||
docId: (doc as any)?.id,
|
|
||||||
docFields: doc ? Object.keys(doc) : [],
|
|
||||||
previousDocId: (previousDoc as any)?.id,
|
|
||||||
workflowId: workflow.id,
|
workflowId: workflow.id,
|
||||||
workflowName: workflow.name
|
workflowName: workflow.name
|
||||||
}, 'Evaluating collection trigger condition')
|
}, 'Evaluating trigger condition')
|
||||||
|
|
||||||
const conditionMet = this.evaluateCondition(trigger.condition, context)
|
const conditionMet = this.evaluateCondition(trigger.condition, context)
|
||||||
|
|
||||||
|
|||||||
@@ -145,7 +145,7 @@ export const workflowsPlugin =
|
|||||||
// CRITICAL: Modify existing collection configs BEFORE PayloadCMS processes them
|
// CRITICAL: Modify existing collection configs BEFORE PayloadCMS processes them
|
||||||
// This is the ONLY time we can add hooks that will actually work
|
// This is the ONLY time we can add hooks that will actually work
|
||||||
const logger = getConfigLogger()
|
const logger = getConfigLogger()
|
||||||
logger.info('Attempting to modify collection configs before PayloadCMS initialization...')
|
logger.debug('Modifying collection configs...')
|
||||||
|
|
||||||
if (config.collections && pluginOptions.collectionTriggers) {
|
if (config.collections && pluginOptions.collectionTriggers) {
|
||||||
for (const [triggerSlug, triggerConfig] of Object.entries(pluginOptions.collectionTriggers)) {
|
for (const [triggerSlug, triggerConfig] of Object.entries(pluginOptions.collectionTriggers)) {
|
||||||
@@ -159,7 +159,7 @@ export const workflowsPlugin =
|
|||||||
}
|
}
|
||||||
|
|
||||||
const collection = config.collections[collectionIndex]
|
const collection = config.collections[collectionIndex]
|
||||||
logger.info(`Found collection '${triggerSlug}' - modifying its hooks...`)
|
logger.debug(`Found collection '${triggerSlug}' - modifying its hooks...`)
|
||||||
|
|
||||||
// Initialize hooks if needed
|
// Initialize hooks if needed
|
||||||
if (!collection.hooks) {
|
if (!collection.hooks) {
|
||||||
@@ -186,19 +186,40 @@ export const workflowsPlugin =
|
|||||||
}, 'Collection automation hook triggered')
|
}, 'Collection automation hook triggered')
|
||||||
|
|
||||||
if (!registry.isInitialized) {
|
if (!registry.isInitialized) {
|
||||||
logger.warn('Workflow executor not yet initialized, skipping execution')
|
logger.warn('Workflow executor not yet initialized, attempting lazy initialization')
|
||||||
return undefined
|
|
||||||
|
try {
|
||||||
|
// Try to create executor if we have a payload instance
|
||||||
|
if (args.req?.payload) {
|
||||||
|
logger.info('Creating workflow executor via lazy initialization')
|
||||||
|
const { WorkflowExecutor } = await import('../core/workflow-executor.js')
|
||||||
|
const executor = new WorkflowExecutor(args.req.payload, logger)
|
||||||
|
setWorkflowExecutor(executor, logger)
|
||||||
|
logger.info('Lazy initialization successful')
|
||||||
|
} else {
|
||||||
|
logger.error('Cannot lazy initialize - no payload instance available')
|
||||||
|
await createFailedWorkflowRun(args, 'Workflow executor not initialized and lazy initialization failed - no payload instance', logger)
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Lazy initialization failed:', error)
|
||||||
|
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||||
|
await createFailedWorkflowRun(args, `Workflow executor lazy initialization failed: ${errorMessage}`, logger)
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!registry.executor) {
|
// Re-check registry after potential lazy initialization
|
||||||
|
const updatedRegistry = getExecutorRegistry()
|
||||||
|
if (!updatedRegistry.executor) {
|
||||||
logger.error('Workflow executor is null despite being marked as initialized')
|
logger.error('Workflow executor is null despite being marked as initialized')
|
||||||
// Create a failed workflow run to track this issue
|
// Create a failed workflow run to track this issue
|
||||||
await createFailedWorkflowRun(args, 'Executor not available', logger)
|
await createFailedWorkflowRun(args, 'Executor not available after initialization', logger)
|
||||||
return undefined
|
return undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.debug('Executing triggered workflows...')
|
logger.debug('Executing triggered workflows...')
|
||||||
await registry.executor.executeTriggeredWorkflows(
|
await updatedRegistry.executor.executeTriggeredWorkflows(
|
||||||
args.collection.slug,
|
args.collection.slug,
|
||||||
args.operation,
|
args.operation,
|
||||||
args.doc,
|
args.doc,
|
||||||
@@ -245,7 +266,7 @@ export const workflowsPlugin =
|
|||||||
|
|
||||||
// Add the hook to the collection config
|
// Add the hook to the collection config
|
||||||
collection.hooks.afterChange.push(automationHook)
|
collection.hooks.afterChange.push(automationHook)
|
||||||
logger.info(`Added automation hook to '${triggerSlug}' - hook count: ${collection.hooks.afterChange.length}`)
|
logger.debug(`Added automation hook to '${triggerSlug}' - hook count: ${collection.hooks.afterChange.length}`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -254,7 +275,7 @@ export const workflowsPlugin =
|
|||||||
}
|
}
|
||||||
|
|
||||||
const configLogger = getConfigLogger()
|
const configLogger = getConfigLogger()
|
||||||
configLogger.info(`Configuring workflow plugin with ${Object.keys(pluginOptions.collectionTriggers || {}).length} collection triggers`)
|
configLogger.debug(`Configuring workflow plugin with ${Object.keys(pluginOptions.collectionTriggers || {}).length} collection triggers`)
|
||||||
|
|
||||||
// Generate cron tasks for workflows with cron triggers
|
// Generate cron tasks for workflows with cron triggers
|
||||||
generateCronTasks(config)
|
generateCronTasks(config)
|
||||||
@@ -290,10 +311,8 @@ export const workflowsPlugin =
|
|||||||
logger.info(`Plugin configuration: ${Object.keys(pluginOptions.collectionTriggers || {}).length} collection triggers, ${pluginOptions.steps?.length || 0} steps`)
|
logger.info(`Plugin configuration: ${Object.keys(pluginOptions.collectionTriggers || {}).length} collection triggers, ${pluginOptions.steps?.length || 0} steps`)
|
||||||
|
|
||||||
// Create workflow executor instance
|
// Create workflow executor instance
|
||||||
console.log('🚨 CREATING WORKFLOW EXECUTOR INSTANCE')
|
logger.debug('Creating workflow executor instance')
|
||||||
const executor = new WorkflowExecutor(payload, logger)
|
const executor = new WorkflowExecutor(payload, logger)
|
||||||
console.log('🚨 EXECUTOR CREATED:', typeof executor)
|
|
||||||
console.log('🚨 EXECUTOR METHODS:', Object.getOwnPropertyNames(Object.getPrototypeOf(executor)))
|
|
||||||
|
|
||||||
// Register executor with proper dependency injection
|
// Register executor with proper dependency injection
|
||||||
setWorkflowExecutor(executor, logger)
|
setWorkflowExecutor(executor, logger)
|
||||||
|
|||||||
@@ -40,13 +40,6 @@ export function initCollectionHooks<T extends string>(pluginOptions: WorkflowsPl
|
|||||||
collection.config.hooks.afterChange.push(async (change) => {
|
collection.config.hooks.afterChange.push(async (change) => {
|
||||||
const operation = change.operation as 'create' | 'update'
|
const operation = change.operation as 'create' | 'update'
|
||||||
|
|
||||||
// AGGRESSIVE LOGGING - this should ALWAYS appear
|
|
||||||
console.log('🚨 AUTOMATION PLUGIN HOOK CALLED! 🚨')
|
|
||||||
console.log('Collection:', change.collection.slug)
|
|
||||||
console.log('Operation:', operation)
|
|
||||||
console.log('Doc ID:', change.doc?.id)
|
|
||||||
console.log('Has executor?', !!executor)
|
|
||||||
console.log('Executor type:', typeof executor)
|
|
||||||
|
|
||||||
logger.info({
|
logger.info({
|
||||||
slug: change.collection.slug,
|
slug: change.collection.slug,
|
||||||
@@ -55,10 +48,9 @@ export function initCollectionHooks<T extends string>(pluginOptions: WorkflowsPl
|
|||||||
previousDocId: change.previousDoc?.id,
|
previousDocId: change.previousDoc?.id,
|
||||||
hasExecutor: !!executor,
|
hasExecutor: !!executor,
|
||||||
executorType: typeof executor
|
executorType: typeof executor
|
||||||
}, 'AUTOMATION PLUGIN: Collection hook triggered')
|
}, 'Collection automation hook triggered')
|
||||||
|
|
||||||
try {
|
try {
|
||||||
console.log('🚨 About to call executeTriggeredWorkflows')
|
|
||||||
|
|
||||||
// Execute workflows for this trigger
|
// Execute workflows for this trigger
|
||||||
await executor.executeTriggeredWorkflows(
|
await executor.executeTriggeredWorkflows(
|
||||||
@@ -69,15 +61,13 @@ export function initCollectionHooks<T extends string>(pluginOptions: WorkflowsPl
|
|||||||
change.req
|
change.req
|
||||||
)
|
)
|
||||||
|
|
||||||
console.log('🚨 executeTriggeredWorkflows completed without error')
|
|
||||||
|
|
||||||
logger.info({
|
logger.info({
|
||||||
slug: change.collection.slug,
|
slug: change.collection.slug,
|
||||||
operation,
|
operation,
|
||||||
docId: change.doc?.id
|
docId: change.doc?.id
|
||||||
}, 'AUTOMATION PLUGIN: executeTriggeredWorkflows completed successfully')
|
}, 'Workflow execution completed successfully')
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log('🚨 AUTOMATION PLUGIN ERROR:', error)
|
|
||||||
|
|
||||||
logger.error({
|
logger.error({
|
||||||
slug: change.collection.slug,
|
slug: change.collection.slug,
|
||||||
|
|||||||
@@ -7,8 +7,7 @@ export function initWebhookEndpoint(config: Config, webhookPrefix = 'webhook'):
|
|||||||
const logger = getConfigLogger()
|
const logger = getConfigLogger()
|
||||||
// Ensure the prefix starts with a slash
|
// Ensure the prefix starts with a slash
|
||||||
const normalizedPrefix = webhookPrefix.startsWith('/') ? webhookPrefix : `/${webhookPrefix}`
|
const normalizedPrefix = webhookPrefix.startsWith('/') ? webhookPrefix : `/${webhookPrefix}`
|
||||||
logger.debug(`Adding webhook endpoint to config with prefix: ${normalizedPrefix}`)
|
logger.debug(`Adding webhook endpoint: ${normalizedPrefix}`)
|
||||||
logger.debug('Current config.endpoints length:', config.endpoints?.length || 0)
|
|
||||||
|
|
||||||
// Define webhook endpoint
|
// Define webhook endpoint
|
||||||
const webhookEndpoint = {
|
const webhookEndpoint = {
|
||||||
@@ -172,7 +171,7 @@ export function initWebhookEndpoint(config: Config, webhookPrefix = 'webhook'):
|
|||||||
// Combine existing endpoints with the webhook endpoint
|
// Combine existing endpoints with the webhook endpoint
|
||||||
config.endpoints = [...(config.endpoints || []), webhookEndpoint]
|
config.endpoints = [...(config.endpoints || []), webhookEndpoint]
|
||||||
logger.debug(`Webhook endpoint added at path: ${webhookEndpoint.path}`)
|
logger.debug(`Webhook endpoint added at path: ${webhookEndpoint.path}`)
|
||||||
logger.debug('New config.endpoints length:', config.endpoints.length)
|
logger.debug('Webhook endpoint added')
|
||||||
} else {
|
} else {
|
||||||
logger.debug(`Webhook endpoint already exists at path: ${webhookEndpoint.path}`)
|
logger.debug(`Webhook endpoint already exists at path: ${webhookEndpoint.path}`)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user