Marketing Automation – Campaign Generation and Sending

This section covers the MarketingCampaigns console command, which automates the creation and dispatch of marketing campaigns for Prep Network events. It selects events based on configured timelines, generates campaign records, and sends transactional emails or texts in production environments.

Key Components

File / Class Responsibility
app/Console/Commands/MarketingCampaigns.php Generates and sends campaigns via CLI command
app/Models/MarketingAutomation.php Defines automation rules (timeline, event type, recipients, templates)
app/Models/MarketingCampaign.php Represents a campaign instance tied to a specific event and automation
app/Jobs/SendTransactionalEmail.php Queues jobs to dispatch emails/texts for campaigns
app/Console/Kernel.php (Scheduler) Schedules the marketing:campaigns command to run every minute without overlapping

Command Lifecycle

  • Scheduling: Runs every minute via Laravel scheduler
  • Execution: php artisan marketing:campaigns {date?}
  • Workflow:
    1. Generate campaigns
    2. Send due campaigns

The scheduler configuration ensures high-frequency execution while preventing overlaps .

1. Generating Campaigns

Creates or updates campaign entries for events matching active automations.

public function generateCampaigns()
{
    // Count campaigns created today
    $campaigns = MarketingCampaign::whereDate('created_at', Carbon::today())->count();

    // Fetch active automations
    $automations = $campaigns
        ? MarketingAutomation::where('status', 'Active')
            ->where('updated_at', '>', Carbon::now()->subMinutes(10))
            ->get()
        : MarketingAutomation::where('status', 'Active')->get();

    $date = Carbon::parse($this->argument('date'));

    foreach ($automations as $automation) {
        // Map timeline to event date field
        $timeline = [
            'Pre-Event'   => 'start_date',
            'Post-Event'  => 'end_date',
            'Day(s) Of'   => 'days_of',
        ][$automation->send_timeline];

        // Query matching events
        $events = Event::where('website_id', $automation->website_id)
            ->where('type', $automation->event_type)
            ->where('internal_status', '!=', 'Cancelled')
            ->when($timeline != 'days_of', fn($q) =>
                $q->whereDate($timeline, $automation->sendDate($date))
            )
            ->when($timeline == 'days_of', fn($q) =>
                $q->whereDate('start_date', '<=', $date)
                  ->whereDate('end_date', '>=', $date)
            )
            ->when($automation->showcase_type, fn($q) =>
                $q->where('title', 'LIKE', '%'.$automation->showcase_type.'%')
            )
            ->get();

        // Filter by categories
        if ($automation->event_categories) {
            foreach ($automation->event_categories as $category) {
                $events = $events->where($category, 1);
            }
        }

        // Create or update campaigns
        foreach ($events as $event) {
            $campaign = MarketingCampaign::firstOrNew([
                'automation_id' => $automation->id,
                'event_id'      => $event->id,
            ]);

            if (! $campaign->exists || ! $campaign->sent) {
                $campaign->send_date = $automation->campaignSendDate();
                $campaign->save();
            }
        }
    }
}

This process ensures each active automation produces campaigns for relevant events exactly once per send cycle .

2. Sending Campaigns

Dispatches the SendTransactionalEmail job for campaigns whose send date matches the current date.

public function sendCampaigns()
{
    $date = $this->argument('date')
        ? Carbon::parse($this->argument('date'))->endOfDay()
        : Carbon::now();

    if ($date->isFuture()) {
        $this->info('Cannot send campaigns for future date');
        return;
    }

    $campaigns = MarketingCampaign::shouldSend()
        ->whereDate('send_date', $date)
        ->orderByDesc('send_date')
        ->get();

    foreach ($campaigns as $campaign) {
        $this->info('Sending campaign for '.$campaign->event->title);

        // Only send if email/text enabled and running in production/testing
        if (
            ($campaign->automation->send_email && $campaign->automation->template_id) ||
            $campaign->automation->send_text
        ) {
            if (in_array(config('app.env'), ['production', 'testing'])) {
                SendTransactionalEmail::dispatch($campaign);
            } else {
                $this->info('Unable to send when not on production');
            }
        }

        // Mark as sent
        $campaign->update(['sent' => 1]);
    }
}
  • Safety check prevents dispatch on future dates
  • Environment guard ensures jobs only enqueue in production or testing environments

Flowchart of the Command

flowchart TD
  A[Scheduler trigger] --> B[MarketingCampaigns::handle()]
  B --> C[generateCampaigns()]
  C --> D[Fetch active automations]
  D --> E[Query matching events]
  E --> F[Create/Update campaigns]
  B --> G[sendCampaigns()]
  G --> H[Query due campaigns]
  H --> I[Dispatch SendTransactionalEmail]
  I --> J[Mark campaign.sent = 1]

Dependencies & Relationships

  • Models: Event, MarketingAutomation, MarketingCampaign
  • Job: SendTransactionalEmail (handles email/text templating and transport)
  • Schedule: configured in app/Console/Kernel.php via everyMinute()->withoutOverlapping(10)
  • Factories & Tests:
    • MarketingAutomationFactory and MarketingCampaignFactory define default state and scopes
    • Feature tests verify audience selection and variable interpolation
{
  "title": "📌 Important",
  "content": "Campaigns only dispatch in production or testing environments."
}

This automated pipeline ensures timely, targeted outreach around each event’s lifecycle, enabling Prep Network to maintain consistent communication with participants, parents, coaches, and other stakeholders.