Skip to content
Merged

Dev #2904

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
60 changes: 60 additions & 0 deletions app/Console/Commands/ImportResourcesFromExcel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

namespace App\Console\Commands;

use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ResourcesImport;

class ImportResourcesFromExcel extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'resources:import {file : Path to the Excel file}';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Import resources from an Excel file with accompanying images folder.';

/**
* Execute the console command.
*/
public function handle()
{
$filePath = $this->argument('file');
$excelPath = realpath($filePath);

if (!$excelPath || !file_exists($excelPath)) {
$this->error("Excel file does not exist: $filePath");
return 1;
}

$excelDir = dirname($excelPath);
$imagesDir = $excelDir . DIRECTORY_SEPARATOR . 'images';

if (!is_dir($imagesDir)) {
$this->warn("Warning: Images folder not found at $imagesDir. Continuing without images.");
}

try {
Excel::import(new ResourcesImport($imagesDir), $filePath);

$this->info('Import completed successfully.');
return 0;
} catch (Exception $e) {
Log::error('[ImportResourcesFromExcel] Error: ' . $e->getMessage(), [
'trace' => $e->getTraceAsString(),
]);
$this->error('Import failed: ' . $e->getMessage());
return 2;
}
}
}
11 changes: 4 additions & 7 deletions app/Http/Controllers/SearchResourcesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ public function search(ResourceFilters $filters, Request $request)
$items = $this->getItems($filters);

$items->load(['types', 'levels', 'programmingLanguages', 'subjects', 'categories', 'languages']);
//$items = \App\ResourceItem::all();

return $items;

Expand All @@ -23,14 +22,12 @@ public function search(ResourceFilters $filters, Request $request)
protected function getItems(ResourceFilters $filters)
{

$items = ResourceItem::filter($filters)->whereActive(true)
$items = ResourceItem::filter($filters)
->whereActive(true)
->orderBy('weight', 'desc')
->orderBy('created_at', 'desc')
->orderBy('name', 'asc');

//return($items->get()->distinct());

//dd($items->distinct()->paginate(10)->items);

return $items->get()->unique()->paginate(30);
return $items->distinct()->paginate(30);
}
}
152 changes: 152 additions & 0 deletions app/Imports/ResourcesImport.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
<?php

namespace App\Imports;

use App\ResourceItem;
use App\ResourceType;
use App\ResourceLevel;
use App\ResourceProgrammingLanguage;
use App\ResourceSubject;
use App\ResourceCategory;
use App\ResourceLanguage;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder;
use Illuminate\Support\Str;

class ResourcesImport extends DefaultValueBinder implements ToModel, WithCustomValueBinder, WithHeadingRow
{
protected $imagesDir;

// public
private $disk = 'resources';

public function __construct($imagesDir = null)
{
$this->imagesDir = $imagesDir;
}

protected function parseArray($value)
{
if (is_array($value)) return $value;
if (is_string($value)) return array_filter(array_map('trim', preg_split('/[,;|]/', $value)));
return [];
}

public function model(array $row): ?Model
{
if (empty($row['name_of_the_resource'])) {
Log::warning('[ResourcesImport] Missing name_of_the_resource', $row);
return null;
}

$thumbnail = null;
if (!empty($row['image']) && $this->imagesDir) {
$localPath = $this->imagesDir . DIRECTORY_SEPARATOR . $row['image'];
if (file_exists($localPath)) {
$ext = pathinfo($row['image'], PATHINFO_EXTENSION) ?: 'jpg';
$basename = Str::slug($row['name_of_the_resource']) . '-' . time() . '.' . $ext;
Storage::disk($this->disk)->put($basename, file_get_contents($localPath));
$thumbnail = Storage::disk($this->disk)->url($basename);
} else {
Log::warning("[ResourcesImport] Image not found: $localPath");
}
}

$item = new ResourceItem([
'name' => trim($row['name_of_the_resource']),
'source' => trim($row['link'] ?? ''),
'description' => trim($row['description'] ?? ''),
'thumbnail' => $thumbnail,
'learn' => true,
'teach' => true,
'active' => true,
'weight' => \Carbon\Carbon::now()->format('Y')
]);
$item->save();

// Attach relations
// TYPE (ResourceType)
$types = $this->parseArray($row['filters_type'] ?? []);
foreach ($types as $type) {
$model = ResourceType::whereRaw('LOWER(name) = ?', [mb_strtolower(trim($type))])->first();
if ($model) {
$item->types()->attach($model->id);
} else {
Log::warning("[ResourcesImport] ResourceType not found: $type");
}
}

// TARGET AUDIENCE (ResourceLevel)
$audiences = $this->parseArray($row['filters_target_audience'] ?? []);
foreach ($audiences as $aud) {
$model = ResourceLevel::whereRaw('LOWER(name) = ?', [mb_strtolower(trim($aud))])->first();
if ($model) {
$item->levels()->attach($model->id);
} else {
Log::warning("[ResourcesImport] ResourceLevel (target_audience) not found: $aud");
}
}

// LEVEL OF DIFFICULTY (ResourceLevel)
$levels = $this->parseArray($row['filters_level_of_difficulty'] ?? []);
foreach ($levels as $level) {
$model = ResourceLevel::whereRaw('LOWER(name) = ?', [mb_strtolower(trim($level))])->first();
if ($model) {
$item->levels()->attach($model->id);
} else {
Log::warning("[ResourcesImport] ResourceLevel (level_of_difficulty) not found: $level");
}
}

// PROGRAMMING LANGUAGE (ResourceProgrammingLanguage)
$languages = $this->parseArray($row['filters_programming_language'] ?? []);
foreach ($languages as $lang) {
$model = ResourceProgrammingLanguage::whereRaw('LOWER(name) = ?', [mb_strtolower(trim($lang))])->first();
if ($model) {
$item->programmingLanguages()->attach($model->id);
} else {
Log::warning("[ResourcesImport] ResourceProgrammingLanguage not found: $lang");
}
}

// SUBJECT (ResourceSubject)
$subjects = $this->parseArray($row['filters_subject'] ?? []);
foreach ($subjects as $subject) {
$model = ResourceSubject::whereRaw('LOWER(name) = ?', [mb_strtolower(trim($subject))])->first();
if ($model) {
$item->subjects()->attach($model->id);
} else {
Log::warning("[ResourcesImport] ResourceSubject not found: $subject");
}
}

// TOPICS (ResourceCategory)
$topics = $this->parseArray($row['filters_topics'] ?? []);
foreach ($topics as $topic) {
$model = ResourceCategory::whereRaw('LOWER(name) = ?', [mb_strtolower(trim($topic))])->first();
if ($model) {
$item->categories()->attach($model->id);
} else {
Log::warning("[ResourcesImport] ResourceCategory (topic) not found: $topic");
}
}

// LANGUAGE (ResourceLanguage)
$langs = $this->parseArray($row['filters_language'] ?? []);
foreach ($langs as $lang) {
$model = ResourceLanguage::whereRaw('LOWER(name) = ?', [mb_strtolower(trim($lang))])->first();
if ($model) {
$item->languages()->attach($model->id);
} else {
Log::warning("[ResourcesImport] ResourceLanguage not found: $lang");
}
}

return $item;
}
}
14 changes: 9 additions & 5 deletions app/ResourceItem.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,20 +67,24 @@ class ResourceItem extends Model
'teach' => false,
];

protected $appends = ['thumbnail'];

public function scopeFilter($query, ResourceFilters $filters)
{
return $filters->apply($query);
}

public function getThumbnailAttribute($value)
{

if (strncmp($value, 'http', 4) !== 0) {
return config('codeweek.resources_url') . $value;
if (empty($value)) {
$value = $this->attributes['thumbnail'] ?? null;
}

if (stripos($value, 'http://') === 0 || stripos($value, 'https://') === 0) {
return $value;
}

return $value;

return config('codeweek.resources_url') . ltrim($value, '/');
}

public function levels(): BelongsToMany
Expand Down
Loading
Loading