Fluentcrm funnel benchmark

From Lonsdale201/wp-agent-skills · View interactive version

Fluentcrm funnel benchmark is an AI agent skill from the GitHub repository Lonsdale201/wp-agent-skills. Build a custom FluentCRM funnel benchmark — a goal/wait point inside a sequence that pauses execution until a matching event occurs (tag applied, list joined, course completed, custom event). Extends BaseBenchMark. Covers the three abstract methods (getBlock, getBlockFields, handle), Optional vs Ess

How to use this skill

Skill file

FluentCRM: register a custom funnel benchmark

For developers building a funnel wait point — a node placed inside an automation that pauses the contact until a specific event matches the configured criteria (tag applied, course completed, payment received, custom event from your plugin). Unlike a trigger (which STARTS a funnel) or an action (which DOES something), a benchmark gates progress mid-flow. Extends FluentCrm\App\Services\Funnel\BaseBenchMark. Verified against FluentCRM 3.1.8.

API stability note

BaseBenchMark, the registration triplet (fluentcrm_funnel_blocks + fluentcrm_funnel_block_fields + fluentcrm_funnel_benchmark_start_{name}), the assertCurrentGoalState filter, and FunnelProcessor::startFunnelFromSequencePoint() have been stable since FluentCRM 2.6.0 (when goal-state assertion was introduced). The Optional vs Essential semantics and the can_enter direct-entry mechanism are part of that 2.6 baseline.

Misconception this skill corrects

"Benchmarks are special wait nodes — they have their own action listener separate from triggers."

Wrong. Benchmarks listen on the same WP action as triggers — FunnelHandler::mapTriggers() handles both in one pass. After dispatching fluentcrm_funnel_start_{triggerName} for matching trigger funnels, it queries FunnelSequence for benchmark sequences with action_name === $triggerName whose funnel is published, and dispatches fluentcrm_funnel_benchmark_start_{triggerName} for each.

Practical consequences:

  1. The same fluentcrm_funnel_arg_num_{name} filter timing rule applies. Instantiate on fluentcrm_loaded priority below 10. Hook on fluent_crm/after_init and your benchmark misses both active-trigger listener passes; hook too late in init and events fired by other init callbacks can be missed or reduced to the default one accepted arg.
  2. triggerName collision is fine between a trigger and a benchmark — they coexist on the same action. TagAppliedBenchmark::triggerName = 'fluentcrm_contact_added_to_tags' is used by both the trigger flow ("Tag Applied" trigger that starts a funnel) and the benchmark flow ("Tag Applied" wait point).
  3. fluentcrm_funnel_settings option lifecycle includes benchmarks. resetFunnelIndexes() queries published-funnel benchmark sequences — saving a funnel that uses your benchmark adds the trigger name to the listener registry.

Other AI-prone misconceptions:

When to use this skill

Trigger when ANY of the following is true:

Triggers vs Actions vs Benchmarks — a one-line decider

If you find yourself wanting "an action that conditionally pauses", you want a benchmark.

Step 1 — Register on the right hook

// Inside your TriggerManager / ActionManager / BenchmarkManager class:
add_action('fluentcrm_loaded', [$this, 'registerBenchmarks'], 5);

Same lifecycle constraint as triggers and actions. The fluentcrm_funnel_arg_num_{name} filter must be in place before FluentCRM's init:2 early active-trigger listener pass. See fluentcrm-funnel-trigger for the lifecycle diagram.

Step 2 — Extend BaseBenchMark

<?php
namespace MyPlugin\Modules\Benchmarks;

use FluentCrm\App\Services\Funnel\BaseBenchMark;
use FluentCrm\App\Services\Funnel\FunnelProcessor;
use FluentCrm\Framework\Support\Arr;

final class MyEventBenchmark extends BaseBenchMark
{
    public function __construct()
    {
        // The WP action this benchmark listens for. If your plugin doesn't
        // already fire one, see Step 3 about dispatchers — pick a custom name
        // and do_action() it yourself from a bridge.
        $this->triggerName  = 'my_plugin_thing_happened';

        $this->actionArgNum = 2; // matches do_action('my_plugin_thing_happened', $thingId, $subscriber)
        $this->priority     = 20;

        parent::__construct();
    }

    public function getBlock()
    {
        return [
            'title'       => __('Thing Happened', 'my-plugin'),
            'description' => __('Wait until "thing" happens for the contact.', 'my-plugin'),
            'icon'        => 'fc-icon-tag_applied',
            // CRITICAL — 'settings' seeds new block instances. The editor's
            // Vue components bind directly to settings.<field_key>; omit
            // this and dragging the block in throws
            // `TypeError: Cannot read properties of undefined (reading
            // '<first_field>')` in start.js, leaving the panel empty.
            // Keys MUST match getBlockFields()['fields'] keys exactly,
            // including the auto-rendered `type` and `can_enter` fields.
            'settings'    => [
                'thing_ids' => [],
                'type'      => 'optional',  // 'required' for Essential
                'can_enter' => 'yes',       // 'no' to disable direct entry
            ],
        ];
    }

    public function getBlockFields($funnel)
    {
        return [
            'title'     => __('Thing Happened', 'my-plugin'),
            'sub_title' => __('Wait until selected things happen for the contact.', 'my-plugin'),
            'fields'    => [
                'thing_ids' => [
                    'type'        => 'rest_selector',
                    'option_key'  => 'my_plugin_things',
                    'is_multiple' => true,
                    'label'       => __('Target Things', 'my-plugin'),
                    'inline_help' => __('Leave blank to match any thing.', 'my-plugin'),
                ],
                'type'      => $this->benchmarkTypeField(),  // Optional vs Essential — provided by BaseBenchMark
                'can_enter' => $this->canEnterField(),       // direct-entry toggle — provided by BaseBenchMark
            ],
        ];
    }

    public function handle($benchMark, $originalArgs)
    {
        $thingId    = (int) ($originalArgs[0] ?? 0);
        $subscriber = $originalArgs[1] ?? null;

        if (!$thingId || !$subscriber) {
            return;
        }

        $settings  = $benchMark->settings;
        $thingIds  = (array) Arr::get($settings, 'thing_ids', []);

        // Empty filter → match anything. Otherwise must match one of the configured ids.
        if (!empty($thingIds) && !in_array($thingId, array_map('intval', $thingIds), true)) {
            return;
        }

        // Resume the funnel run from THIS benchmark — NOT startFunnelSequence.
        // startFunnelFromSequencePoint advances the existing funnel-subscriber
        // past the goal point; startFunnelSequence creates a NEW run.
        (new FunnelProcessor())->startFunnelFromSequencePoint($benchMark, $subscriber);
    }

    /**
     * Filter — called when FluentCRM needs to know whether a contact ALREADY
     * meets the goal criteria (e.g. they had the tag before they entered the
     * funnel). Used for the admin "is the goal complete?" indicator and for
     * deciding whether to skip past the goal automatically.
     */
    public function assertCurrentGoalState($asserted, $benchmark, $funnelSubscriber)
    {
        if (!$funnelSubscriber || !$funnelSubscriber->subscriber) {
            return $asserted;
        }

        // Replace this with the actual "does the contact already meet the
        // criteria?" check for your plugin's domain.
        $userId   = (int) ($funnelSubscriber->subscriber->user_id ?? 0);
        $thingIds = (array) Arr::get($benchmark->settings, 'thing_ids', []);

        if (empty($thingIds)) {
            return false; // nothing configured = nothing to assert
        }

        return my_plugin_user_has_any_thing($userId, $thingIds);
    }
}

Step 3 — When to use a custom-named benchmark

Same rule as triggers: if a real WP action already exists with the right shape, set triggerName to that action name and you're done. Otherwise pick a unique name and dispatch from a bridge:

add_action('my_real_plugin_event', function ($subscriberId, $thingId) {
    // Skip if no published funnel uses this benchmark.
    $hasActive = \FluentCrm\App\Models\FunnelSequence::where('action_name', 'my_plugin_thing_happened')
        ->whereHas('funnel', function ($q) { return $q->where('status', 'published'); })
        ->exists();
    if (!$hasActive) {
        return;
    }
    $subscriber = \FluentCrm\App\Models\Subscriber::find($subscriberId);
    if (!$subscriber) {
        return;
    }
    do_action('my_plugin_thing_happened', $thingId, $subscriber);
}, 20, 2);

Note the existence check uses FunnelSequence (not Funnel) and matches action_name — that's how resetFunnelIndexes() discovers benchmarks.

Step 4 — How the registration plumbs through

  1. getBlock() return is added to fluentcrm_funnel_blocks with type === 'benchmark' (set by BaseBenchMark::addBenchmark at BaseBenchMark.php:53-62) — that's how the editor's "Goal" section sees your block.
  2. getBlockFields($funnel) shapes the editor settings panel (returned via fluentcrm_funnel_block_fields).
  3. Admin saves the funnel with your benchmark inside → FunnelController calls resetFunnelIndexes() which writes your triggerName into the fluentcrm_funnel_settings option.
  4. When do_action($triggerName, ...) fires at runtime, FunnelHandler::mapTriggers() looks up benchmark FunnelSequence rows with action_name === $triggerName (published funnels only) and dispatches do_action('fluentcrm_funnel_benchmark_start_'.$triggerName, $benchMark, $originalArgs) for each.
  5. BaseBenchMark::register() listens on that hook (BaseBenchMark.php:24) → invokes your handle($benchMark, $originalArgs).
  6. Your handler matches criteria → startFunnelFromSequencePoint($benchMark, $subscriber) resumes the funnel.

The assertCurrentGoalState filter is dispatched separately when the admin loads a contact's funnel detail view, or when the funnel processor checks "is the goal already met" before deciding what to do.

Critical rules

Common mistakes

Cross-references

What this skill does NOT cover

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.