Component Details

Deep dive into the configuration and assets associated with this component.

Basic Information
Name cron-generator
Display Name Cron Generator
Version 1.0.0
Status Active
Downloads 76
Description Component: Cron Generator
Created 2025-11-11 20:42:10
Last Updated 2025-11-12 13:32:29
Controller Code
<?php

namespace App\Http\Controllers\Components\CronGenerator;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;

class ComponentCronGeneratorController extends Controller
{
    /**
     * Display the cron generator interface.
     */
    public function index()
    {
        return view('components.cron-generator.index');
    }

    /**
     * Generate cron jobs using OpenAI
     * POST /dashboard/generate-cron-jobs
     */
    public function generateCronJobs(Request $request)
    {
        // Force JSON response - this is an API endpoint
        if (!$request->wantsJson() && !$request->expectsJson()) {
            $request->headers->set('Accept', 'application/json');
        }

        // Always return JSON for API endpoints
        try {
            $validated = $request->validate([
                'requirements' => 'required|string|max:10000',
                'matomo_path' => 'nullable|string|max:255',
                'cron_user' => 'nullable|string|max:100',
                'context' => 'nullable|string|max:5000',
            ]);
        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'error' => 'Validation failed: ' . implode(', ', $e->validator->errors()->all()),
                'errors' => $e->errors(),
            ], 422);
        }

        $requirements = $validated['requirements'];
        $matomoPath = $validated['matomo_path'] ?? '/var/www/matomo';
        $cronUser = $validated['cron_user'] ?? 'www-data';
        $context = $validated['context'] ?? '';

        // Build prompt for OpenAI
        $prompt = "Generate cron job configuration for Matomo analytics archiving based on these requirements:\n\n";
        $prompt .= "Requirements:\n{$requirements}\n\n";
        if ($context) {
            $prompt .= "Additional context:\n{$context}\n\n";
        }
        $prompt .= "Matomo path: {$matomoPath}\n";
        $prompt .= "Cron user: {$cronUser}\n\n";
        $prompt .= "Provide a properly formatted crontab entry with explanation.";

        // Call OpenAI API directly (controller runs on license server)
        $user = auth()->user();

        if (!$user || !$user->license_key) {
            return response()->json([
                'success' => false,
                'error' => 'License key not found. Please configure your license in settings.',
            ], 403);
        }

        try {
            // Get OpenAI API key from database
            $apiKey = Setting::get('openai_api_key');
            if (!$apiKey) {
                return response()->json([
                    'success' => false,
                    'error' => 'OpenAI API key not configured on license server',
                ], 500);
            }

            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $apiKey,
                'Content-Type' => 'application/json',
            ])->timeout(90)->post('https://api.openai.com/v1/chat/completions', [
                'model' => Setting::get('openai_model', 'gpt-4'),
                'messages' => [
                    [
                        'role' => 'user',
                        'content' => $prompt
                    ]
                ],
                'max_tokens' => (int) Setting::get('openai_max_tokens', 2000),
                'temperature' => (float) Setting::get('openai_temperature', 0.1),
            ]);

            if (!$response->successful()) {
                Log::error('OpenAI API error', [
                    'status' => $response->status(),
                    'body' => $response->body(),
                ]);
                return response()->json([
                    'success' => false,
                    'error' => 'OpenAI API request failed: ' . $response->body()
                ], $response->status());
            }

            $data = $response->json();
            
            if (!isset($data['choices'][0]['message']['content'])) {
                return response()->json([
                    'success' => false,
                    'error' => 'Invalid response from OpenAI API'
                ], 500);
            }

            return response()->json([
                'success' => true,
                'data' => $data['choices'][0]['message']['content'],
            ]);

        } catch (\Exception $e) {
            Log::error('Cron generation exception', [
                'error' => $e->getMessage(),
            ]);

            return response()->json([
                'success' => false,
                'error' => 'Generation failed: ' . $e->getMessage(),
            ], 500);
        }
    }
}

Routes Code
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Components\CronGenerator\ComponentCronGeneratorController;

Route::middleware(['auth', 'component.visible'])->group(function () {
    Route::get('/cron-generator', [ComponentCronGeneratorController::class, 'index'])->name('dashboard.cron-generator');
    // API route - always returns JSON
    Route::post('/generate-cron-jobs', [ComponentCronGeneratorController::class, 'generateCronJobs'])
        ->name('dashboard.generate-cron-jobs')
        ->middleware('api'); // Ensure JSON response
});

Views (1)
  • index.blade.php Length: 36932 chars