83 lines
2.5 KiB
PHP
83 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Holding;
|
|
|
|
use App\BusinessLocation;
|
|
use App\HoldingEntity;
|
|
use App\Utils\BusinessUtil;
|
|
use Spatie\Permission\Models\Permission;
|
|
|
|
class HoldingEntityLocationSyncService
|
|
{
|
|
public function __construct(protected BusinessUtil $businessUtil)
|
|
{
|
|
}
|
|
|
|
public function createEntityWithLocation(int $businessId, array $entityData): HoldingEntity
|
|
{
|
|
$entity = HoldingEntity::create($entityData);
|
|
$this->syncLocationForEntity($entity);
|
|
|
|
return $entity->fresh();
|
|
}
|
|
|
|
public function syncLocationForEntity(HoldingEntity $entity): ?BusinessLocation
|
|
{
|
|
$existingLocationId = data_get($entity->meta, 'business_location_id');
|
|
if (! empty($existingLocationId)) {
|
|
return BusinessLocation::find($existingLocationId);
|
|
}
|
|
|
|
$location = $this->businessUtil->addLocation(
|
|
(int) $entity->business_id,
|
|
$this->buildLocationDetails($entity)
|
|
);
|
|
|
|
$this->ensureLocationPermission($location->id);
|
|
|
|
$meta = $entity->meta ?? [];
|
|
$meta['business_location_id'] = $location->id;
|
|
$entity->update(['meta' => $meta]);
|
|
|
|
return $location;
|
|
}
|
|
|
|
public function syncLocationName(HoldingEntity $entity): void
|
|
{
|
|
$locationId = data_get($entity->meta, 'business_location_id');
|
|
if (empty($locationId)) {
|
|
return;
|
|
}
|
|
|
|
BusinessLocation::where('id', $locationId)
|
|
->where('business_id', $entity->business_id)
|
|
->update(['name' => $entity->name]);
|
|
}
|
|
|
|
protected function buildLocationDetails(HoldingEntity $entity): array
|
|
{
|
|
$template = BusinessLocation::where('business_id', $entity->business_id)->first();
|
|
|
|
return [
|
|
'name' => $entity->name,
|
|
'landmark' => $template->landmark ?? '',
|
|
'city' => $template->city ?? '-',
|
|
'state' => $template->state ?? '-',
|
|
'country' => $template->country ?? '-',
|
|
'zip_code' => $template->zip_code ?? '00000',
|
|
'mobile' => $template->mobile ?? '',
|
|
'alternate_number' => $template->alternate_number ?? '',
|
|
'website' => $template->website ?? '',
|
|
];
|
|
}
|
|
|
|
protected function ensureLocationPermission(int $locationId): void
|
|
{
|
|
$permissionName = 'location.'.$locationId;
|
|
|
|
if (! Permission::where('name', $permissionName)->exists()) {
|
|
Permission::create(['name' => $permissionName]);
|
|
}
|
|
}
|
|
}
|