ultimatepos/database/seeders/GlobalProductTaxonomySeeder.php

82 lines
2.3 KiB
PHP

<?php
namespace Database\Seeders;
use App\Business;
use App\Category;
use App\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
class GlobalProductTaxonomySeeder extends Seeder
{
/**
* دسته‌بندی و زیردسته‌بندی جامع محصولات جهان.
*/
public function run(): void
{
$taxonomy = require database_path('seeders/data/global_product_taxonomy.php');
$now = now();
Business::query()->pluck('id')->each(function (int $businessId) use ($taxonomy, $now) {
$createdBy = User::where('business_id', $businessId)->value('id') ?? 1;
foreach ($taxonomy as $parentName => $parentData) {
$parent = $this->firstOrCreateCategory(
$parentName,
0,
$parentData['code'] ?? null,
$businessId,
$createdBy,
$now
);
foreach ($parentData['children'] as $childName => $childCode) {
$this->firstOrCreateCategory(
$childName,
$parent->id,
$childCode,
$businessId,
$createdBy,
$now
);
}
}
});
}
private function firstOrCreateCategory(
string $name,
int $parentId,
?string $shortCode,
int $businessId,
int $createdBy,
$timestamp
): Category {
$existing = Category::where('business_id', $businessId)
->where('category_type', 'product')
->where('name', $name)
->first();
if ($existing) {
if ($shortCode && empty($existing->short_code)) {
$existing->update(['short_code' => $shortCode]);
}
return $existing;
}
return Category::create([
'name' => $name,
'short_code' => $shortCode,
'slug' => $shortCode ? Str::slug($shortCode) : null,
'business_id' => $businessId,
'parent_id' => $parentId,
'created_by' => $createdBy,
'category_type' => 'product',
'created_at' => $timestamp,
'updated_at' => $timestamp,
]);
}
}