HEX
Server: LiteSpeed
System: Linux s1049.use1.mysecurecloudhost.com 4.18.0-477.27.2.lve.el8.x86_64 #1 SMP Wed Oct 11 12:32:56 UTC 2023 x86_64
User: xedaptot (3356)
PHP: 8.3.31
Disabled: NONE
Upload Files
File: /home/xedaptot/ai.naniguide.com/database/seeders/Demo/Stage04_SubscriptionsSeeder.php
<?php

namespace Database\Seeders\Demo;

use App\Model\Subscription;
use App\Services\Subscription\SubscriptionManagementService;
use Database\Seeders\DatabaseInit;
use Illuminate\Support\Carbon;

/**
 * Creates one Subscription per demo customer linking them to the configured plan.
 *
 * Status mapping:
 *   - "active" → Subscription::STATUS_ACTIVE, period ends in 1 year
 *   - "new"    → STATUS_NEW (trial), period ends in 14 days
 *   - "ended"  → STATUS_ENDED, ends_at = 7 days ago
 */
class Stage04_SubscriptionsSeeder extends AbstractDemoSeeder
{
    protected int $fakerOffset = 4;

    /** customer_key → Subscription */
    public static array $created = [];

    public function run(): void
    {
        $customers = Stage03_CustomersSeeder::$created;
        $plans     = DatabaseInit::$createdPlans;
        $service   = app(SubscriptionManagementService::class);

        foreach (DemoConfig::customers() as $cfg) {
            $customer = $customers[$cfg['key']] ?? null;
            $plan     = $plans[$cfg['plan_key']] ?? null;
            if (!$customer || !$plan) {
                $this->log("skip {$cfg['key']}: missing customer or plan");
                continue;
            }

            [$status, $endsAt, $cancelledAt] = match ($cfg['sub_status']) {
                'new'    => [Subscription::STATUS_NEW,    Carbon::now()->addDays(14), null],
                'ended'  => [Subscription::STATUS_ENDED,  Carbon::now()->subDays(7),  Carbon::now()->subDays(7)],
                default  => [Subscription::STATUS_ACTIVE, Carbon::now()->addYear(),   null],
            };

            $sub = $service->createAtState($customer, $plan, $status, $endsAt, $cancelledAt);
            self::$created[$cfg['key']] = $sub;

            // Mirror production assignPlan(): SubscriptionLifecycle::onSubscribe
            // primes both the cold-state subscription_credit_state row and the
            // hot tracker file (path declared on CreditKey). Trial / ended subs
            // skip — they shouldn't be able to send/verify.
            if ($sub->isActive()) {
                app(\App\Services\Plans\Lifecycle\SubscriptionLifecycle::class)
                    ->onSubscribe($sub);
            }

            $this->log("subscription {$cfg['key']} → plan={$cfg['plan_key']} status={$sub->status}");
        }

        $this->log('seeded ' . count(self::$created) . ' subscriptions');
    }
}