Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php
namespace App\Http\Controllers\Api\V1\Certificates;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Certificates\CertificateTemplate;
use App\Models\Certificates\CertificateBatch;
use App\Models\Certificates\SchoolCryptoKey;
use App\Services\Certificates\CertificateGeneratorService;

class CertificateBatchController extends Controller
{
public function generate(Request $request, CertificateGeneratorService $service)
{
$request->validate([
'template_name' => 'required|string',
'background_image' => 'required|image',
'font_file' => 'nullable|file',
'fields_config' => 'required|json',
'students_data' => 'required|json',
'whatsapp_column' => 'nullable|string'
]);

$bgPath = $request->file('background_image')->store('certificates/templates', 'public');
$fontPath = $request->hasFile('font_file') ? $request->file('font_file')->store('certificates/fonts', 'public') : null;

$template = CertificateTemplate::create([
'school_id' => $request->user()->school_id,
'name' => $request->template_name,
'background_image_path' => $bgPath,
'font_file_path' => $fontPath,
'fields_config' => json_decode($request->fields_config, true),
]);

if (!$template->school->cryptoKey) {
$res = openssl_pkey_new(["digest_alg" => "sha256", "private_key_bits" => 2048, "private_key_type" => OPENSSL_KEYTYPE_RSA]);
openssl_pkey_export($res, $privKey);
$pubKey = openssl_pkey_get_details($res)["key"];
SchoolCryptoKey::create(['school_id' => $template->school_id, 'public_key' => $pubKey, 'private_key' => $privKey]);
}

$studentsData = json_decode($request->students_data, true);
$batch = CertificateBatch::create([
'school_id' => $template->school_id,
'certificate_template_id' => $template->id,
'status' => 'processing',
'total_count' => count($studentsData)
]);

foreach ($studentsData as $row) {
$cert = $service->generate($template, $row, $request->whatsapp_column);
$cert->update([
'certificate_batch_id' => $batch->id,
'file_path_pdf' => 'certificates/generated/' . $cert->uuid . '.pdf'
]);
}

$batch->update(['status' => 'completed', 'processed_count' => count($studentsData)]);
return response()->json(['message' => 'Batch processing started', 'batch_id' => $batch->id]);
}

public function show($batchId)
{
$batch = CertificateBatch::with('certificates')->findOrFail($batchId);
return response()->json($batch);
}
}
32 changes: 32 additions & 0 deletions app/Http/Controllers/Public/CertificateVerificationController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php
namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Models\Certificates\Certificate;
use Inertia\Inertia;

class CertificateVerificationController extends Controller
{
public function show($uuid)
{
$certificate = Certificate::with('school.cryptoKey')->where('uuid', $uuid)->first();

if (!$certificate) {
return Inertia::render('Certificates/Verify', ['valid' => false]);
}

$payload = $certificate->uuid . '|' . $certificate->recipient_name;
$pubKey = $certificate->school->cryptoKey->public_key ?? null;

$isValid = false;
if ($pubKey && $certificate->digital_signature) {
$isValid = openssl_verify($payload, base64_decode($certificate->digital_signature), $pubKey, OPENSSL_ALGO_SHA256) === 1;
}

return Inertia::render('Certificates/Verify', [
'valid' => $isValid,
'certificate' => $certificate->only(['uuid', 'recipient_name', 'created_at']),
'school_name' => $certificate->school->name ?? 'Unknown'
]);
}
}
19 changes: 19 additions & 0 deletions app/Models/Certificates/Certificate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php
namespace App\Models\Certificates;
use Illuminate\Database\Eloquent\Model;
use App\Models\School;
use App\Models\Auth\User;

class Certificate extends Model
{
protected $fillable = [
'uuid', 'school_id', 'certificate_template_id', 'student_id',
'recipient_name', 'recipient_phone', 'recipient_whatsapp',
'data_payload', 'file_path_pdf', 'file_path_jpg', 'digital_signature'
];
protected $casts = ['data_payload' => 'array'];

public function school() { return $this->belongsTo(School::class); }
public function template() { return $this->belongsTo(CertificateTemplate::class, 'certificate_template_id'); }
public function student() { return $this->belongsTo(User::class, 'student_id'); }
}
13 changes: 13 additions & 0 deletions app/Models/Certificates/CertificateBatch.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php
namespace App\Models\Certificates;
use Illuminate\Database\Eloquent\Model;
use App\Models\School;

class CertificateBatch extends Model
{
protected $fillable = ['school_id', 'certificate_template_id', 'status', 'total_count', 'processed_count'];

public function school() { return $this->belongsTo(School::class); }
public function template() { return $this->belongsTo(CertificateTemplate::class, 'certificate_template_id'); }
public function certificates() { return $this->hasMany(Certificate::class); }
}
13 changes: 13 additions & 0 deletions app/Models/Certificates/CertificateTemplate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php
namespace App\Models\Certificates;
use Illuminate\Database\Eloquent\Model;
use App\Models\School;

class CertificateTemplate extends Model
{
protected $fillable = ['school_id', 'name', 'background_image_path', 'font_file_path', 'fields_config'];
protected $casts = ['fields_config' => 'array'];

public function school() { return $this->belongsTo(School::class); }
public function certificates() { return $this->hasMany(Certificate::class); }
}
10 changes: 10 additions & 0 deletions app/Models/Certificates/SchoolCryptoKey.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php
namespace App\Models\Certificates;
use Illuminate\Database\Eloquent\Model;
use App\Models\School;

class SchoolCryptoKey extends Model
{
protected $fillable = ['school_id', 'public_key', 'private_key'];
public function school() { return $this->belongsTo(School::class); }
}
39 changes: 39 additions & 0 deletions app/Services/Certificates/CertificateGeneratorService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php
namespace App\Services\Certificates;

use App\Models\Certificates\Certificate;
use App\Models\Certificates\CertificateTemplate;
use Illuminate\Support\Str;

class CertificateGeneratorService
{
/**
* Generates a certificate record and applies digital signature.
* Actual image/PDF generation should be handled by a queue job using Intervention Image / TCPDF.
*/
public function generate(CertificateTemplate $template, array $dataRow, string $whatsappColumn = null)
{
$uuid = Str::uuid()->toString();
$recipientName = $dataRow['name'] ?? 'Unknown';

// Retrieve school crypto key
$cryptoKey = $template->school->cryptoKey;
$signature = null;
if ($cryptoKey) {
// Sign the UUID and recipient name
$payload = $uuid . '|' . $recipientName;
openssl_sign($payload, $signature, $cryptoKey->private_key, OPENSSL_ALGO_SHA256);
$signature = base64_encode($signature);
}

return Certificate::create([
'uuid' => $uuid,
'school_id' => $template->school_id,
'certificate_template_id' => $template->id,
'recipient_name' => $recipientName,
'recipient_whatsapp' => $whatsappColumn ? ($dataRow[$whatsappColumn] ?? null) : null,
'data_payload' => $dataRow,
'digital_signature' => $signature,
]);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
public function up(): void
{
// 1. Keys for Digital Signature per School
Schema::create('school_crypto_keys', function (Blueprint $table) {
$table->id();
$table->foreignId('school_id')->constrained()->onDelete('cascade');
$table->text('public_key');
$table->text('private_key'); // Should be encrypted at rest in a real app
$table->timestamps();
});

// 2. Certificate Templates
Schema::create('certificate_templates', function (Blueprint $table) {
$table->id();
$table->foreignId('school_id')->constrained()->onDelete('cascade');
$table->string('name');
$table->string('background_image_path');
$table->string('font_file_path')->nullable();
$table->json('fields_config')->nullable(); // { "name": {"x": 100, "y": 200, "size": 24, "color": "#000"} }
$table->timestamps();
});

// 3. Generated Certificates
Schema::create('certificates', function (Blueprint $table) {
$table->id();
$table->uuid('uuid')->unique();
$table->foreignId('school_id')->constrained()->onDelete('cascade');
$table->foreignId('certificate_template_id')->constrained()->onDelete('cascade');
$table->foreignId('student_id')->nullable()->constrained('users')->onDelete('set null');
$table->string('recipient_name');
$table->string('recipient_phone')->nullable();
$table->string('recipient_whatsapp')->nullable();
$table->json('data_payload')->nullable(); // Full excel row data
$table->string('file_path_pdf')->nullable();
$table->string('file_path_jpg')->nullable();
$table->text('digital_signature')->nullable();
$table->timestamps();
});
}

public function down(): void
{
Schema::dropIfExists('certificates');
Schema::dropIfExists('certificate_templates');
Schema::dropIfExists('school_crypto_keys');
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
public function up(): void
{
Schema::create('certificate_batches', function (Blueprint $table) {
$table->id();
$table->foreignId('school_id')->constrained()->onDelete('cascade');
$table->foreignId('certificate_template_id')->constrained()->onDelete('cascade');
$table->enum('status', ['pending', 'processing', 'completed', 'failed'])->default('pending');
$table->integer('total_count')->default(0);
$table->integer('processed_count')->default(0);
$table->timestamps();
});

Schema::table('certificates', function (Blueprint $table) {
$table->foreignId('certificate_batch_id')->nullable()->constrained()->onDelete('cascade');
});
}

public function down(): void
{
Schema::table('certificates', function (Blueprint $table) {
$table->dropForeign(['certificate_batch_id']);
$table->dropColumn('certificate_batch_id');
});
Schema::dropIfExists('certificate_batches');
}
};
2 changes: 2 additions & 0 deletions database/seeders/RolesAndPermissionsSeeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ public function run(): void
['code' => 'manage_pages', 'label' => 'إدارة الصفحات'],
['code' => 'manage_articles', 'label' => 'إدارة المقالات والتحرير'],
['code' => 'write_articles', 'label' => 'كتابة المقالات المسندة'],
['code' => 'view_teachers', 'label' => 'عرض بيانات المعلمين'],
['code' => 'view_halaqas', 'label' => 'عرض بيانات الحلقات'],
];

foreach ($permissions as $permission) {
Expand Down
66 changes: 66 additions & 0 deletions resources/js/Pages/Certificates/Studio.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import React, { useState } from 'react';
import { Head } from '@inertiajs/react';

export default function CertificateStudio() {
const [templateImage, setTemplateImage] = useState<string | null>(null);
const [fields, setFields] = useState<any[]>([]);

// Mock logic for drag and drop fields over image
const addField = () => {
setFields([...fields, { id: Date.now(), name: 'New Field', x: 50, y: 50, size: 24, color: '#000000' }]);
};

return (
<div className="p-6">
<Head title="استوديو الشهادات" />
<h1 className="text-2xl font-bold mb-4">استوديو تصميم الشهادات</h1>

<div className="flex gap-4">
{/* Sidebar Controls */}
<div className="w-1/4 bg-white p-4 rounded shadow">
<h3 className="font-semibold mb-2">1. رفع القالب والخط</h3>
<input type="file" className="mb-4 w-full" accept="image/*" onChange={(e) => {
if (e.target.files?.[0]) {
setTemplateImage(URL.createObjectURL(e.target.files[0]));
}
}} />

<h3 className="font-semibold mb-2">2. استيراد البيانات (Excel)</h3>
<input type="file" className="mb-4 w-full" accept=".xlsx,.csv" />

<h3 className="font-semibold mb-2">3. الحقول الديناميكية</h3>
<button onClick={addField} className="bg-blue-600 text-white px-4 py-2 rounded w-full mb-2">
+ إضافة حقل جديد
</button>

<h3 className="font-semibold mb-2 mt-4">4. التصدير</h3>
<button className="bg-green-600 text-white px-4 py-2 rounded w-full">
توليد الشهادات
</button>
</div>

{/* Canvas Area */}
<div className="w-3/4 bg-gray-100 rounded shadow p-4 min-h-[600px] relative overflow-hidden">
{templateImage ? (
<div className="relative inline-block border border-dashed border-gray-400">
<img src={templateImage} alt="Template" className="max-w-full" />
{fields.map(field => (
<div
key={field.id}
className="absolute border-2 border-blue-500 bg-white/50 px-2 py-1 cursor-move"
style={{ left: `${field.x}px`, top: `${field.y}px`, color: field.color, fontSize: `${field.size}px` }}
>
{field.name}
</div>
))}
</div>
) : (
<div className="flex items-center justify-center h-full text-gray-500">
يرجى رفع صورة قالب الشهادة للبدء
</div>
)}
</div>
</div>
</div>
);
}
Loading
Loading