ultimatepos/Modules/Crm/Services/CompanyProfileService.php

103 lines
3.0 KiB
PHP

<?php
namespace Modules\Crm\Services;
use Modules\Crm\Entities\CrmCompany;
use Modules\Crm\Entities\CrmPhoneFollowUp;
class CompanyProfileService
{
protected $profileFields = [
'legal_name', 'brand_name', 'company_type', 'industry_category_id',
'employee_count_range', 'website', 'email', 'main_phone',
'registration_number', 'address', 'city', 'province', 'description',
];
public function calculateCompletion(CrmCompany $company): int
{
$filled = 0;
$total = count($this->profileFields);
foreach ($this->profileFields as $field) {
if (! empty($company->{$field})) {
$filled++;
}
}
$relations = ['contacts', 'branches', 'phones', 'requirements'];
$total += count($relations);
foreach ($relations as $rel) {
if ($company->{$rel}()->exists()) {
$filled++;
}
}
$completion = (int) round(($filled / max($total, 1)) * 100);
$company->update(['profile_completion' => $completion]);
$this->syncPhoneFollowUps($company);
return $completion;
}
public function getEmptyFields(CrmCompany $company): array
{
$empty = [];
foreach ($this->profileFields as $field) {
if (empty($company->{$field})) {
$empty[] = $field;
}
}
if (! $company->contacts()->exists()) {
$empty[] = 'contacts';
}
if (! $company->branches()->exists()) {
$empty[] = 'branches';
}
if (! $company->phones()->exists()) {
$empty[] = 'phones';
}
if (! $company->requirements()->exists()) {
$empty[] = 'requirements';
}
return $empty;
}
public function getSuggestedFieldsForCall(CrmCompany $company, int $limit = 3): array
{
return array_slice($this->getEmptyFields($company), 0, $limit);
}
public function findOrCreateForPhone(CrmPhoneFollowUp $phone, int $user_id): CrmCompany
{
if (! empty($phone->company_id)) {
return CrmCompany::findOrFail($phone->company_id);
}
$company = CrmCompany::create([
'business_id' => $phone->business_id,
'brand_name' => $phone->company_name ?? $phone->contact_name,
'main_phone' => $phone->mobile_number,
'city' => $phone->city,
'province' => $phone->province,
'industry_category_id' => $phone->industry_category_id,
'created_by' => $user_id,
]);
$phone->update(['company_id' => $company->id]);
$this->calculateCompletion($company);
return $company;
}
protected function syncPhoneFollowUps(CrmCompany $company): void
{
CrmPhoneFollowUp::where('company_id', $company->id)->update([
'profile_completion' => $company->profile_completion,
'company_name' => $company->brand_name ?? $company->legal_name,
]);
}
}