|
45405
|
1625
|
46
|
2026-05-14T14:35:03.611087+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769303611_m1.jpg...
|
PhpStorm
|
faVsco.js – Salesforce/Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
11
130
3
21
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Salesforce;
use Carbon\Carbon;
use Exception;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Events\Dispatcher;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Jiminny\Component\Country\CountriesMap;
use Jiminny\Contracts\Acl\PermissionEnum;
use Jiminny\Contracts\Repositories\TeamRepository;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\ImportsBusinessProcessesInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\SalesforceBatchSyncInterface;
use Jiminny\Contracts\Services\Crm\Provider\SalesforceInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\RemoteNoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SearchTaskInterface;
use Jiminny\Contracts\Services\Crm\SendSummaryToCrmInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SupportsObjectTypeParseInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmProfileRecordTypesInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Enums\CrmObject;
use Jiminny\Events\Activities\Crm\LeadConverted;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpBadRequestException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\NoResultsException;
use Jiminny\Exceptions\ServiceUnavailableException;
use Jiminny\Jobs\Crm\NoteObject;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Calendar\CalendarEvent;
use Jiminny\Models\Contact;
use Jiminny\Models\Contracts\ActivityContract;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\ContactRole;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Crm\RecordType;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\TeamSettings;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\ContactRoleRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\Crm\RecordTypeFieldValuesRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\Helpers\ArrayIterator;
use Jiminny\Services\Crm\MatchDomainByEmailInterface;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Services\Crm\ResolveCompanyNameByEmailTrait;
use Jiminny\Services\Crm\Salesforce\Fields\FieldHelper;
use Jiminny\Services\Crm\Salesforce\Fields\FieldTypeConverter;
use Jiminny\Services\Crm\Salesforce\Fields\ValueNormalizer;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\FollowupActivityTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\LogActivityTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\RecordManipulationsTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\SyncFieldsTrait;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
use Ramsey\Uuid\Uuid;
use Sentry\Laravel\Facade as Sentry;
class Service extends BaseService implements
SalesforceInterface,
SalesforceBatchSyncInterface,
SyncCrmEntitiesInterface,
SyncCrmProfileRecordTypesInterface,
ImportsBusinessProcessesInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
SendSummaryToCrmInterface,
MatchDomainByEmailInterface,
SearchTaskInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
SupportsObjectTypeParseInterface,
RemoteNoteEntityManipulationInterface,
VerifyTaskExistsInterface
{
use ResolveCompanyNameByEmailTrait;
use SyncFieldsTrait;
use DeleteObjectsTrait;
use RecordManipulationsTrait;
use ServiceTraits\BatchSyncTrait;
use FollowupActivityTrait;
use LogActivityTrait;
/**
* Note Body Limit for the Old Note-Taking Tool
*
* @var int
*/
private const int CLASSIC_NOTE_MAX_LENGTH = 32000;
/**
* Note Content Limit for the New Notes
*
* @var int
*/
private const int ENHANCED_NOTE_MAX_LENGTH = 50000000;
private const string INSTALLED_PACKAGE_ID = '033Tw0000007bKbIAI';
private const int CACHE_TTL = 600;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day - 86400
/**
* @var Client
*/
protected $client;
protected PayloadBuilder $payloadBuilder;
protected QueryHandler $queryHandler;
private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
public function __construct(
Client $client,
PayloadBuilder $payloadBuilder,
protected Dispatcher $eventDispatcher,
private readonly CountriesMap $countriesMap,
private readonly ProspectPhotoPathService $prospectPhotoPathService,
) {
parent::__construct();
$this->client = $client;
$this->payloadBuilder = $payloadBuilder;
$this->queryHandler = app(QueryHandler::class, [
'client' => $this->client,
'logger' => $this->logger,
]);
$this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
}
public function getDisplayName(): string
{
return 'Salesforce';
}
public function getJobDelay(): int
{
return 1;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
return $user->getSocialAccount(SocialAccount::PROVIDER_SALESFORCE);
}
public function verifyTaskExists(Activity $activity): bool
{
$crmProviderId = $activity->getCrmProviderId();
$cacheKey = "crm_task_exists:{$this->config->getId()}:$crmProviderId";
return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($activity, $crmProviderId) {
$playbook = $this->getPlaybookFromActivity($activity);
if ($playbook === null) {
$this->logger->warning('[Salesforce] Cannot verify task - no playbook found', [
'activity' => $activity->getId(),
'crm_provider_id' => $crmProviderId,
]);
return false;
}
$objectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_EVENT ? 'Event' : 'Task';
try {
$record = $this->getRecord($objectType, $crmProviderId, ['Id', 'IsDeleted']);
return ! empty($record) && ($record['IsDeleted'] ?? false) === false;
} catch (HttpNotFoundException|HttpBadRequestException) {
$this->logger->info('[Salesforce] Activity record not found during verification', [
'activity' => $activity->getId(),
'object_type' => $objectType,
'crm_provider_id' => $crmProviderId,
'config_id' => $this->config->getId(),
]);
return false;
}
});
}
public function query(string $queryToRun, array $parameters = []): QueryIterator
{
// Due to poorly designed external calls, this method cannot be entirely removed
return $this->queryHandler->query($queryToRun, $parameters);
}
/*=========== Organization Information ===============*/
/**
* Get a list of all the API Versions for the instance.
*
* @throws CrmException
*
* @return mixed
*
*/
public function getApiVersions()
{
$url = $this->config->crm_base_url . '/services/data';
$response = $this->client->get($url);
return json_decode($response->getBody(), true);
}
/**
* Gets the valid recordTypes for a given Salesforce Object via the describe API.
*/
private function getRecordTypes(string $crmObject): array
{
$url = $this->client->getObjectsUrl() . $crmObject . '/describe';
$response = $this->client->get($url);
$jsonResponse = json_decode($response->getBody(), true);
$fields = [];
foreach ($jsonResponse['recordTypeInfos'] as $row) {
$fields[] = ['recordTypeId' => $row['recordTypeId'], 'default' => $row['defaultRecordTypeMapping']];
}
return $fields;
}
/**
* Convert raw field data into a format compatible with CRM APIs.
*/
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return ValueNormalizer::normalize($fieldType, $fieldValue, $internal);
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
$defaultFields = ($activityType === Playbook::ACTIVITY_TYPE_TASK)
? FieldDefinitions::defaultTaskFields()
: FieldDefinitions::defaultEventFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'Type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK, Playbook::ACTIVITY_TYPE_EVENT];
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldFilter = ($activityType === Playbook::ACTIVITY_TYPE_TASK)
? FieldDefinitions::taskFollowupFieldsFilter()
: FieldDefinitions::eventFollowupFieldsFilter();
foreach ($fieldFilter as $eachFilter) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $eachFilter);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
/**
* This one is now called only when ImportActivityTypes is triggered or SyncFieldMetadata executed manually
* Regular sync now uses SharedSyncFieldsTrait -> syncSingleObjectType
* Needs to be replaced later on
*/
public function syncField(Field $field): void
{
try {
if (FieldHelper::isCustomField($field)) {
$query = '
SELECT
Id, Metadata, TableEnumOrId
FROM
CustomField
WHERE
DeveloperName = :fieldName
AND
TableEnumOrId = :fieldType
AND
NamespacePrefix = :namespacePrefix';
// We need to constrain the field lookup to the object, in case it's used in multiple places.
$objectType = \in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true)
? 'activity'
: $field->object_type;
$sfFields = $this->queryHandler->metadata($query, [
'fieldName' => substr($field->crm_provider_id, 0, -\strlen('__c')),
'fieldType' => ucfirst($objectType),
// This is used to ensure we only consider the field within the org, not installed packages.
'namespacePrefix' => 'null',
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
// Sync field metadata.
$metadata = $sfField['Metadata'];
$field->description = mb_strimwidth($metadata['description'] ?? '', 0, 191);
$field->label = mb_strimwidth($metadata['label'] ?? '', 0, Field::LABEL_MAX_LENGTH);
$field->type = $this->convertFieldType($metadata['type'], $field->getEntityName());
$field->is_mandatory = ($metadata['required'] === true);
$field->length = $metadata['length'];
$field->default_value = mb_strimwidth(trim($metadata['defaultValue'] ?? '', '"'), 0, 191);
$field->save();
} else {
$query = '
SELECT
Id, DataType, DeveloperName, Label, Length, Description
FROM
FieldDefinition
WHERE
DurableId = :entityName';
$entityName = $field->getEntityName();
$sfFields = $this->queryHandler->metadata($query, [
'entityName' => $entityName,
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
$convertedType = $this->convertFieldType($sfField['DataType'], $entityName);
$label = mb_strimwidth($sfField['Label'], 0, Field::LABEL_MAX_LENGTH);
if ($field->isBusinessType()) {
$label = 'Opportunity Type';
}
$field->description = mb_strimwidth($sfField['Description'], 0, Field::DESCRIPTION_MAX_LENGTH);
$field->label = $label;
$field->type = $convertedType;
$field->length = $sfField['Length'];
$field->save();
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
private function convertFieldType(string $from, ?string $entityName = null): string
{
$converter = new FieldTypeConverter();
return $converter->convert($from, $entityName);
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$values = [];
$fieldValues = [];
try {
if (FieldHelper::isCustomField($field)) {
$query = '
SELECT
Id, Metadata, TableEnumOrId
FROM
CustomField
WHERE
DeveloperName = :fieldName
AND
TableEnumOrId = :fieldType
AND
NamespacePrefix = :namespacePrefix';
// We need to constrain the field lookup to the object, in case it's used in multiple places.
$objectType = \in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true) ?
'activity' : $field->object_type;
$sfFields = $this->queryHandler->metadata($query, [
'fieldName' => substr($field->crm_provider_id, 0, -\strlen('__c')),
'fieldType' => ucfirst($objectType),
// This is used to ensure we only consider the field within the org, not installed packages.
'namespacePrefix' => 'null',
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
$valueSet = $sfField['Metadata']['valueSet'];
if ($valueSet['valueSetName'] === null) {
// Local picklist values can be obtained easily.
$picklistValues = $valueSet['valueSetDefinition']['value'];
} else {
// But for some fields, we just get the Global Value Picklist pointer so need to do more work.
$picklistValues = $this->importGlobalValuePicklistValues($valueSet['valueSetName']);
}
// Import all active values.
foreach ($picklistValues as $i => $sfFieldValue) {
// Setup default value.
if ($sfFieldValue['default']) {
$field->update(['default_value' => $sfFieldValue['valueName']]);
}
// This comes through as null if active (lol).
if ($sfFieldValue['isActive'] !== false) {
$values[] = [
'value' => $sfFieldValue['valueName'],
'label' => $sfFieldValue['valueName'],
'sequence' => $i,
'is_default' => $sfFieldValue['default'],
];
}
}
} else {
$objectFields = $this->getObjectFields($field->object_type);
$fieldId = $field->crm_provider_id;
// Only work with our field of interest.
$objectField = array_filter($objectFields, function ($item) use ($fieldId) {
return $item['name'] === $fieldId;
});
$objectField = array_shift($objectField);
if (empty($objectField['picklistValues']) === false) {
foreach ($objectField['picklistValues'] as $i => $sfFieldValue) {
// Skip inactive values.
if ($sfFieldValue['active'] === false) {
continue;
}
// Setup default value.
if ($sfFieldValue['defaultValue']) {
$field->update(['default_value' => $sfFieldValue['value']]);
}
$values[] = [
'value' => $sfFieldValue['value'],
'label' => $sfFieldValue['label'],
'sequence' => $i,
'is_default' => $sfFieldValue['defaultValue'],
];
}
}
}
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
if (($key = array_search($value['value'], $fieldsToPurge, true)) !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
// Get IDs of the values to be deleted
$valuesToDelete = $field->values()->whereIn('value', $fieldsToPurge);
$valuesToDeleteIds = $valuesToDelete->pluck('id');
if (! $valuesToDeleteIds->isEmpty()) {
$recordTypeFieldValuesRepository = app(RecordTypeFieldValuesRepository::class);
$recordTypeFieldValuesRepository->deleteForCrmFieldValueIds($valuesToDeleteIds->toArray());
// Now safely delete from crm_field_values
$valuesToDelete->delete();
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
return $fieldValues;
}
/**
* Gets values from Global Value Picklists.
*/
private function importGlobalValuePicklistValues(string $picklistName): array
{
$query = '
SELECT
Metadata
FROM
GlobalValueSet
WHERE
DeveloperName = :picklistName
LIMIT 1';
try {
$sfValues = $this->queryHandler->metadata($query, [
'picklistName' => $picklistName,
]);
// There is always 1 result at this point.
$sfValue = $sfValues->current();
return $sfValue['Metadata']['customValue'];
} catch (NoResultsException $noResultsException) {
// Nothing returned.
return [];
}
}
/**
* @inheritdoc
*/
public function syncProfileRecordTypes(): void
{
$objectTypes = [
'lead',
'account',
'contact',
'opportunity',
'task',
'event',
];
foreach ($objectTypes as $objectType) {
try {
$crmRecordTypes = $this->getRecordTypes(ucfirst($objectType));
foreach ($crmRecordTypes as $crmRecordType) {
// If the record type is default and not the Master type, set this.
if ($crmRecordType['default'] && $crmRecordType['recordTypeId'] !== '012000000000000AAA') {
$recordType = $this->config->recordTypes()
->where('crm_provider_id', $crmRecordType['recordTypeId'])
->first();
if ($recordType) {
$this->profile->{$objectType . '_record_type_id'} = $recordType->id;
}
}
}
} catch (HttpNotFoundException $exception) {
Log::error('No access to ' . $objectType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
if ($this->profile->isDirty()) {
$this->profile->save();
}
}
/**
* Gets business processes.
*/
public function importBusinessProcesses(): void
{
$query = '
SELECT
Id, IsActive, Name, TableEnumOrId
FROM
BusinessProcess
WHERE
TableEnumOrId IN (\'Lead\',\'Opportunity\')';
try {
$sfProcesses = $this->queryHandler->query($query);
// Upsert all processes for the team.
foreach ($sfProcesses as $sfProcess) {
/** @var BusinessProcess $businessProcess */
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => $sfProcess['Id'],
], [
'team_id' => $this->team->id,
'name' => $sfProcess['Name'],
'type' => $sfProcess['TableEnumOrId'] === 'Lead' ? 'lead' : 'opportunity',
'is_selectable' => $sfProcess['IsActive'],
]);
$this->importBusinessProcessStages($businessProcess);
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* Gets business process stages.
*/
private function importBusinessProcessStages(BusinessProcess $businessProcess): void
{
$query = '
SELECT
Metadata
FROM
BusinessProcess
WHERE
Id = :processId';
try {
$stages = [];
$sfProcessStages = $this->queryHandler->metadata($query, [
'processId' => $businessProcess->crm_provider_id,
]);
// There is always 1 result at this point.
$sfProcessStage = $sfProcessStages->current();
// Upsert all processes for the team.
foreach ($sfProcessStage['Metadata']['values'] as $sfProcessStage) {
$sanitizedName = urldecode($sfProcessStage['valueName']); // Must decode: "%2C" becomes "," etc.
$stage = $businessProcess->crm->stages()
// This MUST match on label because this API doesn't use API Name.
->where('label', $sanitizedName)
->where('type', $businessProcess->type)
->where('is_selectable', 1)
->first();
if ($stage) {
$stages[] = $stage->id;
}
}
$businessProcess->stages()->sync($stages);
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* Gets record types.
*/
public function importRecordTypes(): void
{
$query = '
SELECT
Id, IsActive, Name, BusinessProcessId, SobjectType
FROM
RecordType';
try {
$sfRecordTypes = $this->queryHandler->query($query);
// Upsert all record types for the process.
foreach ($sfRecordTypes as $sfRecordType) {
$businessProcess = null;
if ($sfRecordType['BusinessProcessId']) {
$businessProcess = $this->config->businessProcesses()
->where('crm_provider_id', $sfRecordType['BusinessProcessId'])
->first();
}
/** @var RecordType $recordType */
$recordType = $this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => $sfRecordType['Id'],
], [
'team_id' => $this->team->id,
'type' => mb_strtolower($sfRecordType['SobjectType']),
'name' => $sfRecordType['Name'],
'is_selectable' => $sfRecordType['IsActive'],
'business_process_id' => $businessProcess->id ?? null,
]);
$this->importRecordTypeFieldValues($recordType);
}
} catch (NoResultsException $noResultsException) {
// Do nothing.
}
}
/**
* Import record type - field value mappings. This only works for standard fields.
*/
private function importRecordTypeFieldValues(RecordType $recordType): void
{
try {
$query = '
SELECT
Metadata
FROM
RecordType
WHERE
Id = :recordTypeId';
$sfFields = $this->queryHandler->metadata($query, [
'recordTypeId' => $recordType->crm_provider_id,
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
// Sync field metadata.
$picklists = $sfField['Metadata']['picklistValues'];
foreach ($picklists as $picklist) {
$field = $this->config->fields()->where([
'type' => Field::TYPE_PICKLIST,
'object_type' => $recordType->type,
'crm_provider_id' => $picklist['picklist'],
])->first();
if ($field) {
$fieldValues = [];
foreach ($picklist['values'] as $value) {
// Must decode: "%2C" becomes "," etc.
$fieldValue = $field->values()
->where('value', urldecode($value['valueName']))
->first();
if ($fieldValue) {
$fieldValues[] = $fieldValue->id;
}
}
$recordType->fieldValues()->sync($fieldValues);
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* @inheritdoc
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$params = [];
$missingStage = null;
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
foreach ($types as $type) {
if ($type === Stage::TYPE_LEAD) {
$query = '
SELECT
Id, ApiName, MasterLabel, SortOrder
FROM
LeadStatus';
} else {
$query = '
SELECT
Id, ApiName, MasterLabel, IsActive, SortOrder, DefaultProbability
FROM
OpportunityStage';
}
if ($missingStageName) {
$escapedStageName = ValueNormalizer::replaceQueryWithStringLiterals($missingStageName);
$query .= ' WHERE ApiName = :stageName';
$params = [
'stageName' => $escapedStageName,
];
}
try {
$sfStages = $this->queryHandler->query($query, $params);
} catch (NoResultsException $exception) {
$sfStages = [];
}
$missingStage = null;
// Upsert all stages for the team.
foreach ($sfStages as $sfStage) {
$selectable = true;
if (array_key_exists('IsActive', $sfStage)) {
$selectable = $sfStage['IsActive'];
}
$this->restoreAnyTrashedEntity($this->config->stages(), $sfStage['Id']);
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $sfStage['Id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($sfStage['ApiName'], 0, 50),
'label' => mb_strimwidth($sfStage['MasterLabel'], 0, 191),
'type' => $type,
'sequence' => $sfStage['SortOrder'] ?? 0,
'is_selectable' => $selectable,
'probability' => $sfStage['DefaultProbability'] ?? null,
]);
if ($missingStageName && $missingStageName === $sfStage['ApiName']) {
$missingStage = $stage;
}
}
if ($missingStageName && $missingStage === null) {
// If they requested a stage that still doesn't exist, it must be inactive so lazy create it.
$missingStage = $this->config->stages()->create([
'crm_provider_id' => Uuid::uuid4(),
'team_id' => $this->team->id,
'name' => mb_strimwidth($missingStageName, 0, 50),
'label' => mb_strimwidth($missingStageName, 0, 191),
'type' => $type,
'sequence' => 0,
'is_selectable' => 0,
]);
}
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$fields = $this->getAllFieldsAsArray('lead');
if (\in_array('Id', $fields, true) === false) {
return $syncCount;
}
$query = '
SELECT ' . rtrim(implode(',', $fields), ',') . '
FROM Lead
WHERE LastModifiedDate > :since
ORDER BY LastModifiedDate ASC';
try {
$sfLeads = $this->queryHandler->query($query, [
'since' => $since->format('Y-m-d\TH:i:s\Z'),
]);
foreach ($sfLeads as $sfLead) {
// Only sync if previously imported.
if ($this->hasLead($sfLead['Id'])) {
$this->importLead($sfLead);
$syncCount++;
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::LEAD);
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
$fields = $this->getAllFieldsAsArray('lead');
$sfLead = $this->getRecord('Lead', $crmId, $fields);
return $this->importLead($sfLead);
}
private function importLead($crmData): ?Lead
{
/** @var ?Stage $stage */
$stage = null;
if (isset($crmData['Status'])) {
// Get the current stage.
$stage = $this->config
->stages()
->where('name', $crmData['Status'])
->where('type', Stage::TYPE_LEAD)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['Status']);
}
}
// If we have no way of importing this, just return null :(
if ($stage === null) {
return null;
}
$countryCode = $crmData['CountryCode'] ?? null;
// Salesforce allows custom "countries" to be created. Disregard these.
if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {
$countryCode = null;
}
// If we have no country code, try to parse it from the country name.
if ($countryCode === null && empty($crmData['Country']) !== false) {
$countryCode = $this->convertCountryNameToCode($crmData['Country']);
}
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['Phone'] ?? '', 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
$mobilePhone = null;
if (empty($crmData['MobilePhone']) === false) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['MobilePhone'], 0, 25);
$mobilePhone = phone_e164($countryCode, $number);
}
$convertedDate = null;
$convertedAccount = null;
$convertedOpportunity = null;
$convertedContact = null;
if ($crmData['IsConverted'] == 'true') {
$convertedDate = $crmData['ConvertedDate'];
if (empty($crmData['ConvertedAccountId']) === false) {
$convertedAccount = $this->config
->accounts()
->where('crm_provider_id', $crmData['ConvertedAccountId'])
->first();
if ($convertedAccount === null) {
try {
$convertedAccount = $this->syncAccount($crmData['ConvertedAccountId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
if (empty($crmData['ConvertedOpportunityId']) === false) {
$convertedOpportunity = $this->config
->opportunities()
->where('crm_provider_id', $crmData['ConvertedOpportunityId'])
->first();
if ($convertedOpportunity === null) {
try {
$convertedOpportunity = $this->syncOpportunity($crmData['ConvertedOpportunityId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
if (empty($crmData['ConvertedContactId']) === false) {
$convertedContact = $this->team
->crm
->contacts()
->where('crm_provider_id', $crmData['ConvertedContactId'])
->first();
if ($convertedContact === null) {
try {
$convertedContact = $this->syncContact($crmData['ConvertedContactId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
}
if (empty($crmData['Company'])) {
$company = 'Unknown';
} else {
$company = mb_strimwidth($crmData['Company'], 0, 191);
}
$domain = null;
if (empty($crmData['Website']) === false) {
$domain = mb_strimwidth($crmData['Website'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$createdDate = null;
if (empty($crmData['CreatedDate']) === false) {
$createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$data = [
'team_id' => $this->team->id,
'user_id' => $profile?->user_id,
'owner_id' => $crmData['OwnerId'] ?? '',
'company' => $company,
'domain' => $domain,
'name' => $crmData['Name'] ? mb_strimwidth($crmData['Name'], 0, 191) : '',
'title' => $crmData['Title'] ? mb_strimwidth($crmData['Title'], 0, 128) : null,
'email' => $crmData['Email'] ? mb_strimwidth($crmData['Email'], 0, 80) : null,
'phone' => $parsedNumber['phone'],
'ext' => $parsedNumber['ext'] ?? null,
'mobile_phone' => $mobilePhone,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['Id'],
modelType: Lead::class,
fileName: $crmData['Id'],
avatarText: $crmData['Name']
),
'stage_id' => $stage->id,
'record_type_id' => null,
'converted_at' => $convertedDate,
'converted_account_id' => $convertedAccount->id ?? null,
'converted_opportunity_id' => $convertedOpportunity->id ?? null,
'converted_contact_id' => $convertedContact->id ?? null,
'country_code' => $countryCode,
'remotely_created_at' => $createdDate,
];
$this->restoreAnyTrashedEntity($this->config->leads(), $crmData['Id']);
/** @var Lead $lead */
$lead = $this->config->leads()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);
if ($lead->wasChanged('converted_at') && $lead->getConvertedAt() !== null) {
$this->eventDispatcher->dispatch(new LeadConverted($lead));
}
$this->handleObjectDeletion($lead, $crmData);
return $lead;
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$fields = $this->getAllFieldsAsArray('account');
if (\in_array('Id', $fields, true) === false) {
return $syncCount;
}
$query = '
SELECT ' . rtrim(implode(',', $fields), ',') . '
FROM Account
WHERE LastModifiedDate > :since
ORDER BY LastModifiedDate ASC';
try {
$sfAccounts = $this->queryHandler->query($query, [
'since' => $since->format('Y-m-d\TH:i:s\Z'),
]);
foreach ($sfAccounts as $sfAccount) {
// Only sync if previously imported.
if ($this->hasAccount($sfAccount['Id'])) {
$this->importAccount($sfAccount);
$syncCount++;
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::ACCOUNT);
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
$fields = $this->getAllFieldsAsArray('account');
if (! in_array('Id', $fields, true)) {
$this->logger->info('[Salesforce] Sync account cancelled. Fields are not available.', [
'crmId' => $crmId,
'userId' => $this->profile->getUserId(),
]);
return null;
}
$sfAccount = $this->getRecord('Account', $crmId, $fields);
return $this->importAccount($sfAccount);
}
private function importAccount($crmData): Account
{
$countryCode = $crmData['BillingCountryCode'] ?? $crmData['ShippingCountryCode'] ?? null;
// Salesforce allows custom "countries" to be created. Disregard these.
if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {
$countryCode = null;
}
// If we have no country code, try to parse it from the country names.
if ($countryCode === null && empty($crmData['BillingCountry']) === false) {
$countryCode = $this->convertCountryNameToCode($crmData['BillingCountry']);
}
if ($countryCode === null && empty($crmData['ShippingCountry']) === false) {
$countryCode = $this->convertCountryNameToCode($crmData['ShippingCountry']);
}
if (empty($crmData['Phone']) === false) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['Phone'], 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
$industry = null;
if (empty($crmData['Industry']) === false) {
$industry = mb_strimwidth($crmData['Industry'], 0, 40);
}
$domain = null;
if (empty($crmData['Website']) === false) {
$domain = mb_strimwidth($crmData['Website'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$createdDate = null;
if (empty($crmData['CreatedDate']) === false) {
$createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$data = [
'team_id' => $this->team->id,
'user_id' => $profile?->user_id,
'owner_id' => $crmData['OwnerId'],
'name' => mb_strimwidth($crmData['Name'], 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['Id'],
modelType: Account::class,
fileName: $crmData['Id'],
avatarText: $crmData['Name']
),
'industry' => $industry,
'domain' => $domain,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'country_code' => $countryCode,
'remotely_created_at' => $createdDate,
];
$this->restoreAnyTrashedEntity($this->config->accounts(), $crmData['Id']);
/** @var Account $account */
$account = $this->config->accounts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);
$this->handleObjectDeletion($account, $crmData);
return $account;
}
/**
* @inheritdoc
*/
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
$logParams = $parameters;
$parameters['profile'] = $this->profile;
$logParams['user'] = $this->profile->getUserId();
if (count($strategies) > 1) {
$this->logger->warning('[' . $this->getDisplayName() . '] Multiple sync strategies used', [
'teamId' => $this->team->getUuid(),
'params' => $logParams,
'strategies_count' => count($strategies),
]);
}
foreach ($strategies as $syncStrategy) {
$name = $syncStrategy->getStrategyName();
try {
$sfOpportunities = $syncStrategy->fetchOpportunities($parameters);
$totalRecords = $sfOpportunities->count();
foreach ($sfOpportunities as $sfOpportunity) {
$this->importOpportunity($sfOpportunity);
$syncCount++;
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
$this->logger->warning('[' . $this->getDisplayName() . '] No opportunities found', [
'teamId' => $this->team->getUuid(),
'name' => $name,
'params' => $logParams,
'reason' => $noResultsException->getMessage(),
]);
} catch (CrmException $crmException) {
// Nothing to sync.
$this->logger->warning('[' . $this->getDisplayName() . '] Opportunity sync failed', [
'teamId' => $this->team->getUuid(),
'name' => $name,
'params' => $logParams,
'reason' => $crmException->getMessage(),
]);
}
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::OPPORTUNITY, ['params' => $logParams]);
// debug to see how if count of opportunities reaches 1000
if ($syncCount >= 1000) {
$this->logger->info(
'[' . $this->getDisplayName() . '] Sync Opportunities - count warning',
[
'team_id' => $this->team->getId(),
'params' => $logParams,
'count' => $syncCount,
'strategies_count' => count($strategies),
'total_records' => $totalRecords ?? null,
]
);
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
$parameters = [
'profile' => $this->profile,
'crm_id' => $crmId,
];
try {
$sfOpportunity = $strategy->fetchOpportunities($parameters);
} catch (HttpNotFoundException $e) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [
'teamId' => $this->team->id_string,
'crmId' => $crmId,
]);
return null;
} catch (CrmException $crmException) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity sync failed', [
'teamId' => $this->team->id_string,
'crmId' => $crmId,
'exception' => $crmException->getMessage(),
]);
return null;
}
if ($sfOpportunity instanceof ArrayIterator) {
return $this->importOpportunity($sfOpportunity->getItems());
}
return $this->importOpportunity($sfOpportunity);
}
private function importOpportunity($crmData): ?Opportunity
{
/** @var ?Stage $stage */
$stage = null;
if (isset($crmData['StageName'])) {
$stage = $this->config
->stages()
->where('name', $crmData['StageName'])
->where('type', Stage::TYPE_OPPORTUNITY)
->orderBy('is_selectable', 'DESC')
->orderBy('id')
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['StageName']);
}
}
$recordType = null;
if (empty($crmData['RecordTypeId']) === false) {
/** @var ?RecordType $recordType */
$recordType = $this->config->recordTypes()
->where('crm_provider_id', $crmData['RecordTypeId'])
->first();
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$account = null;
if (empty($crmData['AccountId']) === false) {
/** @var ?Account $account */
$account = $this->config->accounts()
->whe...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.6645833,"top":0.027777778,"width":0.15902779,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.82361114,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.8472222,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.87083334,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.9291667,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9527778,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9763889,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"11","depth":4,"bounds":{"left":0.725,"top":0.3122222,"width":0.01875,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"130","depth":4,"bounds":{"left":0.74791664,"top":0.3122222,"width":0.025,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.77708334,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"21","depth":4,"bounds":{"left":0.79791665,"top":0.3122222,"width":0.02013889,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.8215278,"top":0.31,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.8368056,"top":0.31,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Salesforce;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Illuminate\\Database\\Eloquent\\Relations\\HasMany;\nuse Illuminate\\Events\\Dispatcher;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Illuminate\\Support\\Facades\\Log;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\Country\\CountriesMap;\nuse Jiminny\\Contracts\\Acl\\PermissionEnum;\nuse Jiminny\\Contracts\\Repositories\\TeamRepository;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\ImportsBusinessProcessesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\SalesforceBatchSyncInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\SalesforceInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteNoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SearchTaskInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SendSummaryToCrmInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SupportsObjectTypeParseInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmProfileRecordTypesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Enums\\CrmObject;\nuse Jiminny\\Events\\Activities\\Crm\\LeadConverted;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpBadRequestException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\NoResultsException;\nuse Jiminny\\Exceptions\\ServiceUnavailableException;\nuse Jiminny\\Jobs\\Crm\\NoteObject;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Calendar\\CalendarEvent;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Contracts\\ActivityContract;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\ContactRole;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Crm\\RecordType;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\TeamSettings;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\ContactRoleRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\Crm\\RecordTypeFieldValuesRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\Helpers\\ArrayIterator;\nuse Jiminny\\Services\\Crm\\MatchDomainByEmailInterface;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Services\\Crm\\ResolveCompanyNameByEmailTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\FieldHelper;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\FieldTypeConverter;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\ValueNormalizer;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\FollowupActivityTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\LogActivityTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\RecordManipulationsTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\SyncFieldsTrait;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\nuse Ramsey\\Uuid\\Uuid;\nuse Sentry\\Laravel\\Facade as Sentry;\n\nclass Service extends BaseService implements\n SalesforceInterface,\n SalesforceBatchSyncInterface,\n SyncCrmEntitiesInterface,\n SyncCrmProfileRecordTypesInterface,\n ImportsBusinessProcessesInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n SendSummaryToCrmInterface,\n MatchDomainByEmailInterface,\n SearchTaskInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n SupportsObjectTypeParseInterface,\n RemoteNoteEntityManipulationInterface,\n VerifyTaskExistsInterface\n{\n use ResolveCompanyNameByEmailTrait;\n use SyncFieldsTrait;\n use DeleteObjectsTrait;\n use RecordManipulationsTrait;\n use ServiceTraits\\BatchSyncTrait;\n use FollowupActivityTrait;\n use LogActivityTrait;\n\n /**\n * Note Body Limit for the Old Note-Taking Tool\n *\n * @var int\n */\n private const int CLASSIC_NOTE_MAX_LENGTH = 32000;\n\n /**\n * Note Content Limit for the New Notes\n *\n * @var int\n */\n private const int ENHANCED_NOTE_MAX_LENGTH = 50000000;\n\n private const string INSTALLED_PACKAGE_ID = '033Tw0000007bKbIAI';\n\n private const int CACHE_TTL = 600;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day - 86400\n\n /**\n * @var Client\n */\n protected $client;\n\n protected PayloadBuilder $payloadBuilder;\n protected QueryHandler $queryHandler;\n\n private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n\n public function __construct(\n Client $client,\n PayloadBuilder $payloadBuilder,\n protected Dispatcher $eventDispatcher,\n private readonly CountriesMap $countriesMap,\n private readonly ProspectPhotoPathService $prospectPhotoPathService,\n ) {\n parent::__construct();\n\n $this->client = $client;\n $this->payloadBuilder = $payloadBuilder;\n $this->queryHandler = app(QueryHandler::class, [\n 'client' => $this->client,\n 'logger' => $this->logger,\n ]);\n $this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n }\n\n public function getDisplayName(): string\n {\n return 'Salesforce';\n }\n\n public function getJobDelay(): int\n {\n return 1;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n return $user->getSocialAccount(SocialAccount::PROVIDER_SALESFORCE);\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($activity, $crmProviderId) {\n $playbook = $this->getPlaybookFromActivity($activity);\n\n if ($playbook === null) {\n $this->logger->warning('[Salesforce] Cannot verify task - no playbook found', [\n 'activity' => $activity->getId(),\n 'crm_provider_id' => $crmProviderId,\n ]);\n\n return false;\n }\n\n $objectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_EVENT ? 'Event' : 'Task';\n\n try {\n $record = $this->getRecord($objectType, $crmProviderId, ['Id', 'IsDeleted']);\n\n return ! empty($record) && ($record['IsDeleted'] ?? false) === false;\n } catch (HttpNotFoundException|HttpBadRequestException) {\n $this->logger->info('[Salesforce] Activity record not found during verification', [\n 'activity' => $activity->getId(),\n 'object_type' => $objectType,\n 'crm_provider_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n });\n }\n\n public function query(string $queryToRun, array $parameters = []): QueryIterator\n {\n // Due to poorly designed external calls, this method cannot be entirely removed\n return $this->queryHandler->query($queryToRun, $parameters);\n }\n\n /*=========== Organization Information ===============*/\n\n /**\n * Get a list of all the API Versions for the instance.\n *\n * @throws CrmException\n *\n * @return mixed\n *\n */\n public function getApiVersions()\n {\n $url = $this->config->crm_base_url . '/services/data';\n\n $response = $this->client->get($url);\n\n return json_decode($response->getBody(), true);\n }\n\n /**\n * Gets the valid recordTypes for a given Salesforce Object via the describe API.\n */\n private function getRecordTypes(string $crmObject): array\n {\n $url = $this->client->getObjectsUrl() . $crmObject . '/describe';\n\n $response = $this->client->get($url);\n $jsonResponse = json_decode($response->getBody(), true);\n\n $fields = [];\n foreach ($jsonResponse['recordTypeInfos'] as $row) {\n $fields[] = ['recordTypeId' => $row['recordTypeId'], 'default' => $row['defaultRecordTypeMapping']];\n }\n\n return $fields;\n }\n\n /**\n * Convert raw field data into a format compatible with CRM APIs.\n */\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return ValueNormalizer::normalize($fieldType, $fieldValue, $internal);\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n $defaultFields = ($activityType === Playbook::ACTIVITY_TYPE_TASK)\n ? FieldDefinitions::defaultTaskFields()\n : FieldDefinitions::defaultEventFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'Type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK, Playbook::ACTIVITY_TYPE_EVENT];\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n\n $fieldFilter = ($activityType === Playbook::ACTIVITY_TYPE_TASK)\n ? FieldDefinitions::taskFollowupFieldsFilter()\n : FieldDefinitions::eventFollowupFieldsFilter();\n\n foreach ($fieldFilter as $eachFilter) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $eachFilter);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n /**\n * This one is now called only when ImportActivityTypes is triggered or SyncFieldMetadata executed manually\n * Regular sync now uses SharedSyncFieldsTrait -> syncSingleObjectType\n * Needs to be replaced later on\n */\n public function syncField(Field $field): void\n {\n try {\n if (FieldHelper::isCustomField($field)) {\n $query = '\n SELECT\n Id, Metadata, TableEnumOrId\n FROM\n CustomField\n WHERE\n DeveloperName = :fieldName\n AND\n TableEnumOrId = :fieldType\n AND\n NamespacePrefix = :namespacePrefix';\n\n // We need to constrain the field lookup to the object, in case it's used in multiple places.\n $objectType = \\in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true)\n ? 'activity'\n : $field->object_type;\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'fieldName' => substr($field->crm_provider_id, 0, -\\strlen('__c')),\n 'fieldType' => ucfirst($objectType),\n\n // This is used to ensure we only consider the field within the org, not installed packages.\n 'namespacePrefix' => 'null',\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Sync field metadata.\n $metadata = $sfField['Metadata'];\n\n $field->description = mb_strimwidth($metadata['description'] ?? '', 0, 191);\n $field->label = mb_strimwidth($metadata['label'] ?? '', 0, Field::LABEL_MAX_LENGTH);\n $field->type = $this->convertFieldType($metadata['type'], $field->getEntityName());\n $field->is_mandatory = ($metadata['required'] === true);\n $field->length = $metadata['length'];\n $field->default_value = mb_strimwidth(trim($metadata['defaultValue'] ?? '', '\"'), 0, 191);\n $field->save();\n } else {\n $query = '\n SELECT\n Id, DataType, DeveloperName, Label, Length, Description\n FROM\n FieldDefinition\n WHERE\n DurableId = :entityName';\n\n $entityName = $field->getEntityName();\n $sfFields = $this->queryHandler->metadata($query, [\n 'entityName' => $entityName,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n $convertedType = $this->convertFieldType($sfField['DataType'], $entityName);\n $label = mb_strimwidth($sfField['Label'], 0, Field::LABEL_MAX_LENGTH);\n\n if ($field->isBusinessType()) {\n $label = 'Opportunity Type';\n }\n\n $field->description = mb_strimwidth($sfField['Description'], 0, Field::DESCRIPTION_MAX_LENGTH);\n $field->label = $label;\n $field->type = $convertedType;\n $field->length = $sfField['Length'];\n $field->save();\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n private function convertFieldType(string $from, ?string $entityName = null): string\n {\n $converter = new FieldTypeConverter();\n\n return $converter->convert($from, $entityName);\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $values = [];\n $fieldValues = [];\n\n try {\n if (FieldHelper::isCustomField($field)) {\n $query = '\n SELECT\n Id, Metadata, TableEnumOrId\n FROM\n CustomField\n WHERE\n DeveloperName = :fieldName\n AND\n TableEnumOrId = :fieldType\n AND\n NamespacePrefix = :namespacePrefix';\n\n // We need to constrain the field lookup to the object, in case it's used in multiple places.\n $objectType = \\in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true) ?\n 'activity' : $field->object_type;\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'fieldName' => substr($field->crm_provider_id, 0, -\\strlen('__c')),\n 'fieldType' => ucfirst($objectType),\n // This is used to ensure we only consider the field within the org, not installed packages.\n 'namespacePrefix' => 'null',\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n $valueSet = $sfField['Metadata']['valueSet'];\n\n if ($valueSet['valueSetName'] === null) {\n // Local picklist values can be obtained easily.\n $picklistValues = $valueSet['valueSetDefinition']['value'];\n } else {\n // But for some fields, we just get the Global Value Picklist pointer so need to do more work.\n $picklistValues = $this->importGlobalValuePicklistValues($valueSet['valueSetName']);\n }\n\n // Import all active values.\n foreach ($picklistValues as $i => $sfFieldValue) {\n // Setup default value.\n if ($sfFieldValue['default']) {\n $field->update(['default_value' => $sfFieldValue['valueName']]);\n }\n\n // This comes through as null if active (lol).\n if ($sfFieldValue['isActive'] !== false) {\n $values[] = [\n 'value' => $sfFieldValue['valueName'],\n 'label' => $sfFieldValue['valueName'],\n 'sequence' => $i,\n 'is_default' => $sfFieldValue['default'],\n ];\n }\n }\n } else {\n $objectFields = $this->getObjectFields($field->object_type);\n $fieldId = $field->crm_provider_id;\n\n // Only work with our field of interest.\n $objectField = array_filter($objectFields, function ($item) use ($fieldId) {\n return $item['name'] === $fieldId;\n });\n\n $objectField = array_shift($objectField);\n if (empty($objectField['picklistValues']) === false) {\n foreach ($objectField['picklistValues'] as $i => $sfFieldValue) {\n // Skip inactive values.\n if ($sfFieldValue['active'] === false) {\n continue;\n }\n\n // Setup default value.\n if ($sfFieldValue['defaultValue']) {\n $field->update(['default_value' => $sfFieldValue['value']]);\n }\n\n $values[] = [\n 'value' => $sfFieldValue['value'],\n 'label' => $sfFieldValue['label'],\n 'sequence' => $i,\n 'is_default' => $sfFieldValue['defaultValue'],\n ];\n }\n }\n }\n\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n if (($key = array_search($value['value'], $fieldsToPurge, true)) !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n // Get IDs of the values to be deleted\n $valuesToDelete = $field->values()->whereIn('value', $fieldsToPurge);\n $valuesToDeleteIds = $valuesToDelete->pluck('id');\n if (! $valuesToDeleteIds->isEmpty()) {\n $recordTypeFieldValuesRepository = app(RecordTypeFieldValuesRepository::class);\n $recordTypeFieldValuesRepository->deleteForCrmFieldValueIds($valuesToDeleteIds->toArray());\n\n // Now safely delete from crm_field_values\n $valuesToDelete->delete();\n }\n\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n return $fieldValues;\n }\n\n /**\n * Gets values from Global Value Picklists.\n */\n private function importGlobalValuePicklistValues(string $picklistName): array\n {\n $query = '\n SELECT\n Metadata\n FROM\n GlobalValueSet\n WHERE\n DeveloperName = :picklistName\n LIMIT 1';\n\n try {\n $sfValues = $this->queryHandler->metadata($query, [\n 'picklistName' => $picklistName,\n ]);\n\n // There is always 1 result at this point.\n $sfValue = $sfValues->current();\n\n return $sfValue['Metadata']['customValue'];\n } catch (NoResultsException $noResultsException) {\n // Nothing returned.\n\n return [];\n }\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileRecordTypes(): void\n {\n $objectTypes = [\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n 'task',\n 'event',\n ];\n\n foreach ($objectTypes as $objectType) {\n try {\n $crmRecordTypes = $this->getRecordTypes(ucfirst($objectType));\n\n foreach ($crmRecordTypes as $crmRecordType) {\n // If the record type is default and not the Master type, set this.\n if ($crmRecordType['default'] && $crmRecordType['recordTypeId'] !== '012000000000000AAA') {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $crmRecordType['recordTypeId'])\n ->first();\n\n if ($recordType) {\n $this->profile->{$objectType . '_record_type_id'} = $recordType->id;\n }\n }\n }\n } catch (HttpNotFoundException $exception) {\n Log::error('No access to ' . $objectType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n if ($this->profile->isDirty()) {\n $this->profile->save();\n }\n }\n\n /**\n * Gets business processes.\n */\n public function importBusinessProcesses(): void\n {\n $query = '\n SELECT\n Id, IsActive, Name, TableEnumOrId\n FROM\n BusinessProcess\n WHERE\n TableEnumOrId IN (\\'Lead\\',\\'Opportunity\\')';\n\n try {\n $sfProcesses = $this->queryHandler->query($query);\n\n // Upsert all processes for the team.\n foreach ($sfProcesses as $sfProcess) {\n /** @var BusinessProcess $businessProcess */\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $sfProcess['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => $sfProcess['Name'],\n 'type' => $sfProcess['TableEnumOrId'] === 'Lead' ? 'lead' : 'opportunity',\n 'is_selectable' => $sfProcess['IsActive'],\n ]);\n\n $this->importBusinessProcessStages($businessProcess);\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * Gets business process stages.\n */\n private function importBusinessProcessStages(BusinessProcess $businessProcess): void\n {\n $query = '\n SELECT\n Metadata\n FROM\n BusinessProcess\n WHERE\n Id = :processId';\n\n try {\n $stages = [];\n $sfProcessStages = $this->queryHandler->metadata($query, [\n 'processId' => $businessProcess->crm_provider_id,\n ]);\n\n // There is always 1 result at this point.\n $sfProcessStage = $sfProcessStages->current();\n\n // Upsert all processes for the team.\n foreach ($sfProcessStage['Metadata']['values'] as $sfProcessStage) {\n $sanitizedName = urldecode($sfProcessStage['valueName']); // Must decode: \"%2C\" becomes \",\" etc.\n\n $stage = $businessProcess->crm->stages()\n // This MUST match on label because this API doesn't use API Name.\n ->where('label', $sanitizedName)\n ->where('type', $businessProcess->type)\n ->where('is_selectable', 1)\n ->first();\n\n if ($stage) {\n $stages[] = $stage->id;\n }\n }\n\n $businessProcess->stages()->sync($stages);\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * Gets record types.\n */\n public function importRecordTypes(): void\n {\n $query = '\n SELECT\n Id, IsActive, Name, BusinessProcessId, SobjectType\n FROM\n RecordType';\n\n try {\n $sfRecordTypes = $this->queryHandler->query($query);\n\n // Upsert all record types for the process.\n foreach ($sfRecordTypes as $sfRecordType) {\n $businessProcess = null;\n if ($sfRecordType['BusinessProcessId']) {\n $businessProcess = $this->config->businessProcesses()\n ->where('crm_provider_id', $sfRecordType['BusinessProcessId'])\n ->first();\n }\n\n /** @var RecordType $recordType */\n $recordType = $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $sfRecordType['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'type' => mb_strtolower($sfRecordType['SobjectType']),\n 'name' => $sfRecordType['Name'],\n 'is_selectable' => $sfRecordType['IsActive'],\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $this->importRecordTypeFieldValues($recordType);\n }\n } catch (NoResultsException $noResultsException) {\n // Do nothing.\n }\n }\n\n /**\n * Import record type - field value mappings. This only works for standard fields.\n */\n private function importRecordTypeFieldValues(RecordType $recordType): void\n {\n try {\n $query = '\n SELECT\n Metadata\n FROM\n RecordType\n WHERE\n Id = :recordTypeId';\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'recordTypeId' => $recordType->crm_provider_id,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Sync field metadata.\n $picklists = $sfField['Metadata']['picklistValues'];\n\n foreach ($picklists as $picklist) {\n $field = $this->config->fields()->where([\n 'type' => Field::TYPE_PICKLIST,\n 'object_type' => $recordType->type,\n 'crm_provider_id' => $picklist['picklist'],\n ])->first();\n\n if ($field) {\n $fieldValues = [];\n\n foreach ($picklist['values'] as $value) {\n // Must decode: \"%2C\" becomes \",\" etc.\n $fieldValue = $field->values()\n ->where('value', urldecode($value['valueName']))\n ->first();\n\n if ($fieldValue) {\n $fieldValues[] = $fieldValue->id;\n }\n }\n\n $recordType->fieldValues()->sync($fieldValues);\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * @inheritdoc\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $params = [];\n $missingStage = null;\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n\n foreach ($types as $type) {\n if ($type === Stage::TYPE_LEAD) {\n $query = '\n SELECT\n Id, ApiName, MasterLabel, SortOrder\n FROM\n LeadStatus';\n } else {\n $query = '\n SELECT\n Id, ApiName, MasterLabel, IsActive, SortOrder, DefaultProbability\n FROM\n OpportunityStage';\n }\n\n if ($missingStageName) {\n $escapedStageName = ValueNormalizer::replaceQueryWithStringLiterals($missingStageName);\n\n $query .= ' WHERE ApiName = :stageName';\n\n $params = [\n 'stageName' => $escapedStageName,\n ];\n }\n\n try {\n $sfStages = $this->queryHandler->query($query, $params);\n } catch (NoResultsException $exception) {\n $sfStages = [];\n }\n\n $missingStage = null;\n\n // Upsert all stages for the team.\n foreach ($sfStages as $sfStage) {\n $selectable = true;\n if (array_key_exists('IsActive', $sfStage)) {\n $selectable = $sfStage['IsActive'];\n }\n\n $this->restoreAnyTrashedEntity($this->config->stages(), $sfStage['Id']);\n\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $sfStage['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($sfStage['ApiName'], 0, 50),\n 'label' => mb_strimwidth($sfStage['MasterLabel'], 0, 191),\n 'type' => $type,\n 'sequence' => $sfStage['SortOrder'] ?? 0,\n 'is_selectable' => $selectable,\n 'probability' => $sfStage['DefaultProbability'] ?? null,\n ]);\n\n if ($missingStageName && $missingStageName === $sfStage['ApiName']) {\n $missingStage = $stage;\n }\n }\n\n if ($missingStageName && $missingStage === null) {\n // If they requested a stage that still doesn't exist, it must be inactive so lazy create it.\n $missingStage = $this->config->stages()->create([\n 'crm_provider_id' => Uuid::uuid4(),\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($missingStageName, 0, 50),\n 'label' => mb_strimwidth($missingStageName, 0, 191),\n 'type' => $type,\n 'sequence' => 0,\n 'is_selectable' => 0,\n ]);\n }\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('lead');\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Lead\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfLeads = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfLeads as $sfLead) {\n // Only sync if previously imported.\n if ($this->hasLead($sfLead['Id'])) {\n $this->importLead($sfLead);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::LEAD);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n $fields = $this->getAllFieldsAsArray('lead');\n\n $sfLead = $this->getRecord('Lead', $crmId, $fields);\n\n return $this->importLead($sfLead);\n }\n\n private function importLead($crmData): ?Lead\n {\n /** @var ?Stage $stage */\n $stage = null;\n if (isset($crmData['Status'])) {\n // Get the current stage.\n $stage = $this->config\n ->stages()\n ->where('name', $crmData['Status'])\n ->where('type', Stage::TYPE_LEAD)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['Status']);\n }\n }\n\n // If we have no way of importing this, just return null :(\n if ($stage === null) {\n return null;\n }\n\n $countryCode = $crmData['CountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country name.\n if ($countryCode === null && empty($crmData['Country']) !== false) {\n $countryCode = $this->convertCountryNameToCode($crmData['Country']);\n }\n\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['Phone'] ?? '', 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n\n $mobilePhone = null;\n if (empty($crmData['MobilePhone']) === false) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['MobilePhone'], 0, 25);\n $mobilePhone = phone_e164($countryCode, $number);\n }\n\n $convertedDate = null;\n $convertedAccount = null;\n $convertedOpportunity = null;\n $convertedContact = null;\n\n if ($crmData['IsConverted'] == 'true') {\n $convertedDate = $crmData['ConvertedDate'];\n\n if (empty($crmData['ConvertedAccountId']) === false) {\n $convertedAccount = $this->config\n ->accounts()\n ->where('crm_provider_id', $crmData['ConvertedAccountId'])\n ->first();\n\n if ($convertedAccount === null) {\n try {\n $convertedAccount = $this->syncAccount($crmData['ConvertedAccountId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n\n if (empty($crmData['ConvertedOpportunityId']) === false) {\n $convertedOpportunity = $this->config\n ->opportunities()\n ->where('crm_provider_id', $crmData['ConvertedOpportunityId'])\n ->first();\n\n if ($convertedOpportunity === null) {\n try {\n $convertedOpportunity = $this->syncOpportunity($crmData['ConvertedOpportunityId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n\n if (empty($crmData['ConvertedContactId']) === false) {\n $convertedContact = $this->team\n ->crm\n ->contacts()\n ->where('crm_provider_id', $crmData['ConvertedContactId'])\n ->first();\n\n if ($convertedContact === null) {\n try {\n $convertedContact = $this->syncContact($crmData['ConvertedContactId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n }\n\n if (empty($crmData['Company'])) {\n $company = 'Unknown';\n } else {\n $company = mb_strimwidth($crmData['Company'], 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['Website']) === false) {\n $domain = mb_strimwidth($crmData['Website'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'] ?? '',\n 'company' => $company,\n 'domain' => $domain,\n 'name' => $crmData['Name'] ? mb_strimwidth($crmData['Name'], 0, 191) : '',\n 'title' => $crmData['Title'] ? mb_strimwidth($crmData['Title'], 0, 128) : null,\n 'email' => $crmData['Email'] ? mb_strimwidth($crmData['Email'], 0, 80) : null,\n 'phone' => $parsedNumber['phone'],\n 'ext' => $parsedNumber['ext'] ?? null,\n 'mobile_phone' => $mobilePhone,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Lead::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'stage_id' => $stage->id,\n 'record_type_id' => null,\n 'converted_at' => $convertedDate,\n 'converted_account_id' => $convertedAccount->id ?? null,\n 'converted_opportunity_id' => $convertedOpportunity->id ?? null,\n 'converted_contact_id' => $convertedContact->id ?? null,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->leads(), $crmData['Id']);\n\n /** @var Lead $lead */\n $lead = $this->config->leads()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n if ($lead->wasChanged('converted_at') && $lead->getConvertedAt() !== null) {\n $this->eventDispatcher->dispatch(new LeadConverted($lead));\n }\n\n $this->handleObjectDeletion($lead, $crmData);\n\n return $lead;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('account');\n\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Account\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfAccounts = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfAccounts as $sfAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($sfAccount['Id'])) {\n $this->importAccount($sfAccount);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::ACCOUNT);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n $fields = $this->getAllFieldsAsArray('account');\n if (! in_array('Id', $fields, true)) {\n $this->logger->info('[Salesforce] Sync account cancelled. Fields are not available.', [\n 'crmId' => $crmId,\n 'userId' => $this->profile->getUserId(),\n ]);\n\n return null;\n }\n\n $sfAccount = $this->getRecord('Account', $crmId, $fields);\n\n return $this->importAccount($sfAccount);\n }\n\n private function importAccount($crmData): Account\n {\n $countryCode = $crmData['BillingCountryCode'] ?? $crmData['ShippingCountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country names.\n if ($countryCode === null && empty($crmData['BillingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['BillingCountry']);\n }\n\n if ($countryCode === null && empty($crmData['ShippingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['ShippingCountry']);\n }\n\n if (empty($crmData['Phone']) === false) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['Phone'], 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n $industry = null;\n if (empty($crmData['Industry']) === false) {\n $industry = mb_strimwidth($crmData['Industry'], 0, 40);\n }\n\n $domain = null;\n if (empty($crmData['Website']) === false) {\n $domain = mb_strimwidth($crmData['Website'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'],\n 'name' => mb_strimwidth($crmData['Name'], 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Account::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'industry' => $industry,\n 'domain' => $domain,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->accounts(), $crmData['Id']);\n\n /** @var Account $account */\n $account = $this->config->accounts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n $this->handleObjectDeletion($account, $crmData);\n\n return $account;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n $logParams = $parameters;\n $parameters['profile'] = $this->profile;\n $logParams['user'] = $this->profile->getUserId();\n\n if (count($strategies) > 1) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Multiple sync strategies used', [\n 'teamId' => $this->team->getUuid(),\n 'params' => $logParams,\n 'strategies_count' => count($strategies),\n ]);\n }\n\n foreach ($strategies as $syncStrategy) {\n $name = $syncStrategy->getStrategyName();\n\n try {\n $sfOpportunities = $syncStrategy->fetchOpportunities($parameters);\n $totalRecords = $sfOpportunities->count();\n\n foreach ($sfOpportunities as $sfOpportunity) {\n $this->importOpportunity($sfOpportunity);\n $syncCount++;\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n $this->logger->warning('[' . $this->getDisplayName() . '] No opportunities found', [\n 'teamId' => $this->team->getUuid(),\n 'name' => $name,\n 'params' => $logParams,\n 'reason' => $noResultsException->getMessage(),\n ]);\n } catch (CrmException $crmException) {\n // Nothing to sync.\n $this->logger->warning('[' . $this->getDisplayName() . '] Opportunity sync failed', [\n 'teamId' => $this->team->getUuid(),\n 'name' => $name,\n 'params' => $logParams,\n 'reason' => $crmException->getMessage(),\n ]);\n }\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::OPPORTUNITY, ['params' => $logParams]);\n\n // debug to see how if count of opportunities reaches 1000\n if ($syncCount >= 1000) {\n $this->logger->info(\n '[' . $this->getDisplayName() . '] Sync Opportunities - count warning',\n [\n 'team_id' => $this->team->getId(),\n 'params' => $logParams,\n 'count' => $syncCount,\n 'strategies_count' => count($strategies),\n 'total_records' => $totalRecords ?? null,\n ]\n );\n }\n\n return $syncCount;\n }\n\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n $parameters = [\n 'profile' => $this->profile,\n 'crm_id' => $crmId,\n ];\n\n try {\n $sfOpportunity = $strategy->fetchOpportunities($parameters);\n } catch (HttpNotFoundException $e) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [\n 'teamId' => $this->team->id_string,\n 'crmId' => $crmId,\n ]);\n\n return null;\n } catch (CrmException $crmException) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity sync failed', [\n 'teamId' => $this->team->id_string,\n 'crmId' => $crmId,\n 'exception' => $crmException->getMessage(),\n ]);\n\n return null;\n }\n\n if ($sfOpportunity instanceof ArrayIterator) {\n return $this->importOpportunity($sfOpportunity->getItems());\n }\n\n return $this->importOpportunity($sfOpportunity);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n /** @var ?Stage $stage */\n $stage = null;\n if (isset($crmData['StageName'])) {\n $stage = $this->config\n ->stages()\n ->where('name', $crmData['StageName'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->orderBy('is_selectable', 'DESC')\n ->orderBy('id')\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['StageName']);\n }\n }\n\n $recordType = null;\n if (empty($crmData['RecordTypeId']) === false) {\n /** @var ?RecordType $recordType */\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $crmData['RecordTypeId'])\n ->first();\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $account = null;\n if (empty($crmData['AccountId']) === false) {\n /** @var ?Account $account */\n $account = $this->config->accounts()\n ->where('crm_provider_id', (string) $crmData['AccountId'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['AccountId']);\n }\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $closeDate = null;\n if (empty($crmData['CloseDate']) === false) {\n $closeDate = Carbon::parse($crmData['CloseDate'])->format('Y-m-d');\n }\n\n $valueFieldName = 'Amount';\n if ($this->config->opportunity_value_field_id) {\n $valueFieldName = $this->config->opportunityValueField->crm_provider_id;\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile?->user_id ?? null,\n 'owner_id' => $crmData['OwnerId'] ?? null,\n 'name' => mb_strimwidth($crmData['Name'] ?? '', 0, 128),\n 'value' => $crmData[$valueFieldName],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['CurrencyIsoCode'] ?? null),\n 'close_date' => $closeDate,\n 'is_closed' => $crmData['IsClosed'],\n 'is_won' => $crmData['IsWon'],\n 'stage_id' => $stage?->id ?? null,\n 'record_type_id' => $recordType->id ?? null,\n 'remotely_created_at' => $createdDate,\n 'probability' => $crmData['Probability'] ?? null,\n 'forecast_category' => $crmData['ForecastCategoryName'] ?? null,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->opportunities(), $crmData['Id']);\n\n // Do not allow locked DB tables & other errors\n // to interrupt the process of reverting the trashed opportunities\n try {\n /** @var Opportunity $opportunity */\n $opportunity = $this->config->opportunities()\n ->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n // import external fields into crm_field_data if present\n $crmFields = $this->getOpportunitySyncableFields();\n\n $this->importOpportunityCrmFieldData($crmData, $crmFields, $opportunity->id);\n\n $this->handleObjectDeletion($opportunity, $crmData);\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n } catch (Exception $exception) {\n Sentry::captureException($exception);\n\n $this->logger->error('[Salesforce] importOpportunity failure.', [\n 'crm_provider_id' => $crmData['Id'],\n 'team_id' => $this->team->id,\n 'exception' => $exception->getMessage(),\n ]);\n\n $this->handleEntityDeletionByProviderId($this->config->opportunities(), $crmData);\n }\n\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('contact');\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Contact\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfContacts = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfContacts as $sfContact) {\n // Only sync if previously imported.\n if ($this->hasContact($sfContact['Id'])) {\n $this->importContact($sfContact);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::CONTACT);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n $fields = $this->getAllFieldsAsArray('contact');\n if (! in_array('Id', $fields, true)) {\n $this->logger->info('[Salesforce] Sync contact cancelled. Fields are not available.', [\n 'crmId' => $crmId,\n 'userId' => $this->profile->getUserId(),\n ]);\n\n return null;\n }\n\n $sfContact = $this->getRecord('Contact', $crmId, $fields);\n\n return $this->importContact($sfContact);\n }\n\n private function importContact($crmData): Contact\n {\n $account = null;\n // Contacts may not have accounts...\n if (isset($crmData['AccountId'])) {\n $account = $this->config->accounts()\n ->where('crm_provider_id', (string) $crmData['AccountId'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['AccountId']);\n }\n }\n\n $countryCode = $crmData['MailingCountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country name.\n if ($countryCode === null && empty($crmData['MailingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['MailingCountry']);\n\n if ($countryCode === null && $account) {\n $countryCode = $account->country_code;\n }\n }\n\n $ext = null;\n $parsedNumber = [];\n if (empty($crmData['Phone']) === false) {\n $number = Str::limit($crmData['Phone'], 25, '');\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n\n if (empty($parsedNumber['ext']) === false) {\n $ext = Str::limit($parsedNumber['ext'], 10, '');\n }\n }\n\n $mobileNumber = null;\n if (empty($crmData['MobilePhone']) === false) {\n $mobileNumber = Str::limit(phone_e164($countryCode, $crmData['MobilePhone']), 25, '');\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'] ?? null,\n 'name' => ($crmData['Name'] ?? null) !== null ? mb_strimwidth($crmData['Name'], 0, 100) : '',\n 'title' => ($crmData['Title'] ?? null) !== null ? mb_strimwidth($crmData['Title'], 0, 128) : null,\n 'email' => ($crmData['Email'] ?? null) !== null ? mb_strimwidth($crmData['Email'], 0, 191) : null,\n 'country_code' => $countryCode,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $ext,\n 'mobile_phone' => $mobileNumber,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Contact::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->contacts(), $crmData['Id']);\n\n /** @var Contact $contact */\n $contact = $this->config->contacts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n $this->handleObjectDeletion($contact, $crmData);\n\n return $contact;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n $fields = [\n 'InstanceName',\n 'OrganizationType',\n 'IsSandbox',\n ];\n\n $orgValues = $this->getRecord('Organization', $this->config->crm_provider_id, $fields);\n\n $edition = null;\n switch ($orgValues['OrganizationType']) {\n case 'Developer Edition':\n $edition = Configuration::EDITION_DEVELOPER;\n\n break;\n\n case 'Professional Edition':\n $edition = Configuration::EDITION_PROFESSIONAL;\n\n break;\n\n case 'Enterprise Edition':\n $edition = Configuration::EDITION_ENTERPRISE;\n\n break;\n }\n\n $this->config->edition = $edition;\n $this->config->instance = $orgValues['InstanceName'];\n\n // XXX: How can this state be possible?\n if ($this->config->version === null) {\n $this->config->version = Client::MIN_API_VERSION;\n }\n\n $installedVersion = $this->getInstalledAppVersion();\n if ($installedVersion !== null) {\n $installedVersion = (string) $this->getInstalledAppVersion();\n }\n\n $this->config->installed_app_version = $installedVersion;\n\n $this->config->save();\n }\n\n public function getInstalledAppVersion(): ?string\n {\n try {\n $query = '\n SELECT\n SubscriberPackageVersion.MajorVersion,\n SubscriberPackageVersion.MinorVersion,\n SubscriberPackageVersion.PatchVersion,\n SubscriberPackageVersion.BuildNumber\n FROM\n InstalledSubscriberPackage\n WHERE\n SubscriberPackageId = :packageId\n ';\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'packageId' => self::INSTALLED_PACKAGE_ID,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Grab version number.\n $version = $sfField['SubscriberPackageVersion']['MajorVersion'] .\n $sfField['SubscriberPackageVersion']['MinorVersion'] .\n $sfField['SubscriberPackageVersion']['PatchVersion'] .\n $sfField['SubscriberPackageVersion']['BuildNumber'];\n } catch (\\Exception) {\n $version = null;\n }\n\n return $version;\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws \\Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // For SF we also check if Log Notes is enabled.\n if ($this->profile->log_notes === Profile::LOG_NOTE_NONE) {\n return;\n }\n\n if ($activity->opportunity_id && $activity->prospect === null) {\n return;\n }\n\n try {\n $transcriptionData = $this->generateTranscription($activity);\n\n $noteMaxLength = $this->profile->log_notes === Profile::LOG_NOTE_ENHANCED\n ? self::ENHANCED_NOTE_MAX_LENGTH\n : self::CLASSIC_NOTE_MAX_LENGTH;\n\n $title = 'Transcript for ';\n $title .= $activity->title ?? $activity->activity_title;\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $body = mb_strimwidth($transcriptionData, 0, $noteMaxLength);\n\n if ($activity->opportunity_id) {\n $objectId = $activity->opportunity->crm_provider_id;\n } else {\n $objectId = $activity->prospect->crm_provider_id;\n }\n\n $noteId = $this->saveNote($title, $body, $objectId);\n\n // Store crm logged id in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $noteId;\n $transcription->save();\n } catch (\\Exception $e) {\n \\Sentry::captureException($e);\n }\n }\n\n public function saveNote(string $title, string $body, string $objectId, ?NoteObject $noteObject = null): ?string\n {\n $noteId = null;\n\n try {\n if ($this->profile->log_notes === Profile::LOG_NOTE_ENHANCED) {\n $noteId = $this->buildEnhancedNote($title, $body, $objectId);\n } else {\n $noteId = $this->buildClassicNote($title, $body, $objectId);\n }\n } catch (HttpNotFoundException $exception) {\n // The profile not having access to create Enhanced Notes. Set their preference to Classic.\n if ($this->profile->log_notes === Profile::LOG_NOTE_ENHANCED) {\n $this->profile->update([\n 'log_notes' => Profile::LOG_NOTE_CLASSIC,\n ]);\n }\n }\n\n return $noteId;\n }\n\n /**\n * This is using the \"Enhanced\" Notes feature, NOT the \"Notes & Attachments\" feature being deprecated.\n *\n * @url https://salesforce.stackexchange.com/questions/104408/how-can-i-create-an-account-note-or-contact-note-via-api-that-is-visible-in-sale\n */\n private function buildEnhancedNote(string $title, string $body, string $objectId): string\n {\n // Decode stored entities, escape HTML (without quoting), then convert line breaks for Salesforce formatting\n $decodedBody = html_entity_decode($body, ENT_QUOTES | ENT_HTML5);\n $sanitizedBody = htmlspecialchars($decodedBody, ENT_NOQUOTES, 'UTF-8', false);\n $content = nl2br($sanitizedBody, false);\n $note = [\n 'OwnerId' => $this->profile->crm_provider_id,\n 'Title' => $title,\n 'Content' => base64_encode($content),\n ];\n\n $noteId = $this->createRecord('ContentNote', $note);\n\n $link = [\n 'ContentDocumentId' => $noteId,\n 'LinkedEntityId' => $objectId,\n 'ShareType' => 'I',\n ];\n\n $this->createRecord('ContentDocumentLink', $link);\n\n return $noteId;\n }\n\n private function buildClassicNote(string $title, string $body, string $objectId): string\n {\n if (in_array($this->parseObjectType($objectId), [Field::OBJECT_TASK, Field::OBJECT_EVENT])) {\n $this->logger->info('[Salesforce] Summary not sent', [\n 'profile_id' => $this->profile->id,\n 'objectId' => $objectId,\n 'reason' => 'Classical Note does not support Task/Event relation',\n ]);\n\n return '';\n }\n\n $titleTrimmed = null;\n\n if (mb_strlen($title) > 80) {\n $titleTrimmed = substr($title, 0, 77) . '...';\n }\n $payload = [\n 'OwnerId' => $this->profile->crm_provider_id,\n 'IsPrivate' => false,\n 'Title' => $titleTrimmed ?? $title,\n 'Body' => $titleTrimmed ? $title . PHP_EOL . $body : $body,\n 'ParentId' => $objectId,\n ];\n\n return $this->createRecord('Note', $payload);\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n if ($this->profile === null) {\n return [];\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $limitValues = ['limit' => $this->limit, 'offset' => $this->offset];\n $sosl = $queryBuilder->buildFindQuery($name, $scopes, $limitValues);\n\n $this->logger->info('[Salesforce] Find prospects', [\n 'profile_id' => $this->profile->id,\n 'sosl_query' => $sosl,\n 'search_string' => $name,\n 'scopes' => $scopes,\n ]);\n\n $data = Cache::remember($this->profile->id . $sosl, self::CACHE_TTL, function () use ($sosl) {\n $data = [];\n\n try {\n // Hit remote API.\n $objects = $this->queryHandler->search($sosl);\n\n // Build mapped list.\n foreach ($objects as $object) {\n $type = strtolower($object['attributes']['type']);\n\n $record = [\n 'crmId' => $object['Id'],\n 'name' => $object['Name'],\n 'prospectType' => $type,\n 'phoneNumbers' => [],\n 'crmUrl' => $this->generateProviderUrl($object['Id'], $type),\n ];\n\n switch ($type) {\n case 'lead':\n if (empty($object['Company']) === false) {\n $record['organization'] = $object['Company'];\n }\n\n if (empty($object['Title']) === false) {\n $record['title'] = $object['Title'];\n }\n\n $stage = $this->config->stages()\n ->where('type', Stage::TYPE_LEAD)\n ->where('name', $object['Status'])\n ->first();\n\n // Lazy create the stage.\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_LEAD], $object['Status']);\n }\n\n if ($stage) {\n $record += [\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n ];\n }\n\n if (empty($object['RecordTypeId']) === false) {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $object['RecordTypeId'])\n ->first();\n\n if ($recordType) {\n $record += [\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n }\n }\n\n break;\n\n case 'account':\n if (empty($object['Industry']) === false) {\n $record['industry'] = $object['Industry'];\n $record['detailsLine'] = $object['Industry'];\n }\n if (! empty($object['PersonEmail'])) {\n $record['detailsLine'] = $object['PersonEmail'];\n }\n\n break;\n\n case 'contact':\n // For contacts, we should try and fetch their account name too.\n if ($object['AccountId']) {\n // Cheaper to get this locally.\n $account = $this->config->accounts()\n ->where('crm_provider_id', $object['AccountId'])\n ->first(['name']);\n\n if ($account) {\n $record['organization'] = $account->name;\n }\n }\n\n if (! empty($object['IsPersonAccount']) && $object['Email']) {\n $record['detailsLine'] = $object['Email'];\n } else {\n if (empty($object['Title']) === false) {\n $record['title'] = $object['Title'];\n }\n }\n\n break;\n }\n\n // Add phone numbers to record.\n if (empty($object['Phone']) === false && $object['Phone']) {\n $record['phoneNumbers'][] = [\n 'number' => $object['Phone'],\n 'nationalFormat' => phone_national($this->profile->user->country_code, $object['Phone']),\n 'type' => 'phone',\n ];\n }\n\n if (empty($object['MobilePhone']) === false && $object['MobilePhone']) {\n $record['phoneNumbers'][] = [\n 'number' => $object['MobilePhone'],\n 'nationalFormat' => phone_national(\n $this->profile->user->country_code,\n $object['MobilePhone']\n ),\n 'type' => 'mobile',\n ];\n }\n\n $data[] = $record;\n }\n } catch (NoResultsException $e) {\n $data = [];\n }\n\n return $data;\n });\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n\n if ($crmAccountId === null) {\n return $data;\n }\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n try {\n // Perhaps their profile has no opportunity permissions.\n if ($this->profile === null || $this->profile->opportunity_fields === null) {\n return $data;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildFindOpportunitiesQuery();\n\n $objects = $this->queryHandler->query($query, ['accountId' => $crmAccountId]);\n\n foreach ($objects as $object) {\n $record = [\n 'crmId' => $object['Id'],\n 'name' => $object['Name'],\n 'won' => $object['IsWon'],\n 'closed' => $object['IsClosed'],\n ];\n\n $valueFieldName = 'Amount';\n if ($this->config->opportunity_value_field_id) {\n $valueFieldName = $this->config->opportunityValueField->crm_provider_id;\n }\n\n if (empty($object[$valueFieldName]) === false) {\n $currency = $object['CurrencyIsoCode'] ?? $this->config->default_currency;\n $value = formatCurrency($object[$valueFieldName], $currency);\n\n $record += [\n 'value' => $value,\n ];\n }\n\n $stage = $this->config->stages()\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->where('name', $object['StageName'])\n ->first();\n\n // Lazy create the stage.\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $object['StageName']);\n }\n\n $record += [\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n ];\n\n if (empty($object['RecordTypeId']) === false) {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $object['RecordTypeId'])\n ->first();\n\n if ($recordType) {\n $record += [\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n }\n }\n\n if ($ownerId && isset($object['OwnerId']) && $object['OwnerId'] === $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n } catch (NoResultsException $e) {\n return $data;\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n public function getContactRolesFromCrm(?Carbon $since = null): array\n {\n $roles = [];\n\n if ($this->profile === null) {\n return $roles;\n }\n\n $queryBuilder = app(QueryBuilder::class, ['profile' => $this->profile]);\n\n $query = $queryBuilder->buildGetContactRolesQuery($since);\n\n try {\n $objects = $this->queryHandler->query($query);\n\n foreach ($objects as $object) {\n $roles[] = [\n 'id' => $object['Id'],\n 'contactId' => $object['ContactId'],\n 'opportunityId' => $object['OpportunityId'],\n 'ownerId' => $object['Opportunity']['OwnerId'] ?? null,\n 'isPrimary' => $object['IsPrimary'],\n 'role' => $object['Role'],\n ];\n }\n } catch (NoResultsException) {\n // Just return an empty array.\n $this->logger->info('[Salesforce] No contact roles found', [\n 'since' => $since?->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n }\n\n return $roles;\n }\n\n public function syncContactRoles(Carbon $since): int\n {\n $contactRoleRepository = app(ContactRoleRepository::class);\n\n $crmContactRoles = $this->getContactRolesFromCrm(since: $since);\n $syncCount = 0;\n $contactRoles = [];\n\n foreach ($crmContactRoles as $crmContactRole) {\n $contactRoles[] = $this->importContactRole($crmContactRole);\n $syncCount++;\n }\n\n $contactRoleRepository->saveContactRoles($contactRoles);\n\n $this->syncRemotelyDeletedContactRoles();\n\n return $syncCount;\n }\n\n private function importContactRole(array $contactRole): array\n {\n $contact = $this->config->contacts()\n ->where('crm_provider_id', $contactRole['contactId'])\n ->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($contactRole['contactId']);\n }\n\n $opportunity = $this->config->opportunities()\n ->where('crm_provider_id', $contactRole['opportunityId'])\n ->first();\n\n if ($opportunity === null) {\n $opportunity = $this->syncOpportunity($contactRole['opportunityId']);\n }\n\n $role = null;\n if (! empty($contactRole['role'])) {\n $role = mb_strimwidth($contactRole['role'], 0, 191);\n }\n\n return [\n 'crm_configuration_id' => $this->config->getId(),\n 'contact_id' => $contact->getId(),\n 'crm_provider_id' => $contactRole['id'],\n 'subject_type' => ContactRole::SUBJECT_TYPE_OPPORTUNITY,\n 'subject_id' => $opportunity->getId(),\n 'is_primary' => $contactRole['isPrimary'],\n 'role' => $role,\n ];\n }\n\n protected function syncRemotelyDeletedContactRoles(): bool\n {\n try {\n $deletedRemotely = $this->queryHandler->queryDeleted('OpportunityContactRole');\n } catch (NoResultsException $e) {\n return false;\n }\n\n $deletedOpportunities = $deletedRemotely->getResults();\n $deletedIds = array_column($deletedOpportunities, 'id');\n\n $contactRoleRepository = app(ContactRoleRepository::class);\n\n foreach (array_chunk($deletedIds, self::HARD_DELETE_CHUNK) as $chunk) {\n $contactRoleRepository->deleteContactRoles($chunk);\n\n $this->logger->info('[' . $this->getDisplayName() . '] Remotely deleted opportunities synced', [\n 'teamId' => $this->team->id_string,\n 'remotelyDeletedOpportunities' => $chunk,\n 'count' => count($chunk),\n ]);\n }\n\n return true;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $objects = [];\n\n $hasWho = \\in_array($objectType, ['lead', 'contact']);\n $playbook = $this->getPlaybook($this->profile->user);\n $fields = array_merge(\n $this->profile->getFieldsAsArray(parent::OBJECT_TASK),\n $playbook && $playbook->activityField ? [$playbook->activityField->crm_provider_id] : []\n );\n\n // Query should default to any open call for that user.\n $query = '\n SELECT ' . implode(',', array_unique($fields)) . '\n FROM Task\n WHERE OwnerId = :ownerId\n AND IsArchived = false\n AND IsDeleted = false\n AND IsClosed = false\n AND (';\n\n if ($objectType === 'account') {\n // This covers tasks tied to a related contact or opportunity too.\n $query .= '\n AccountId = :accountId';\n }\n\n if ($hasWho) {\n $query .= '\n WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($opportunityId) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ' ) ORDER BY LastModifiedDate DESC';\n\n try {\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $this->profile->crm_provider_id,\n 'whoId' => $objectId,\n 'whatId' => $opportunityId,\n 'accountId' => $objectId,\n ]);\n } catch (NoResultsException $e) {\n return $data;\n } finally {\n $this->logger->debug(sprintf('[Salesforce] Found %s tasks for query \"%s\"', count($objects), $query));\n }\n\n foreach ($objects as $object) {\n $dueDate = $object['ActivityDate'] ? Carbon::parse($object['ActivityDate'])->toIso8601String() : null;\n $data[] = [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'due' => $dueDate,\n 'type' => $object[$playbook->activityField->crm_provider_id],\n ];\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getEvents(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $objects = [];\n $user = $this->profile?->user;\n if ($this->profile === null || $user === null) {\n return $data;\n }\n\n $hasWho = \\in_array($objectType, ['lead', 'contact']);\n $playbook = $this->getPlaybook($user);\n $fields = array_merge(\n $this->profile->getFieldsAsArray(parent::OBJECT_EVENT),\n $playbook && $playbook->activityField ? [$playbook->activityField->crm_provider_id] : []\n );\n\n // Query should default to any event starting in the last week and ending up until today owned by the user.\n $query = '\n SELECT ' . implode(',', array_unique($fields)) . '\n FROM Event\n WHERE OwnerId = :ownerId\n AND IsArchived = false\n AND IsAllDayEvent = false\n AND StartDateTime >= LAST_N_DAYS:7\n AND EndDateTime <= TODAY\n AND (';\n\n if ($objectType === 'account') {\n // This covers events tied to a related contact or opportunity too.\n $query .= '\n AccountId = :accountId';\n }\n\n if ($hasWho) {\n $query .= '\n WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($opportunityId) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ' ) ORDER BY LastModifiedDate DESC';\n\n try {\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $this->profile->crm_provider_id,\n 'whoId' => $objectId,\n 'whatId' => $opportunityId,\n 'accountId' => $objectId,\n ]);\n } catch (NoResultsException $e) {\n return $data;\n } finally {\n $this->logger->debug(sprintf('[Salesforce] Found %s tasks for query \"%s\"', count($objects), $query));\n }\n\n foreach ($objects as $object) {\n $dueDate = $object['StartDateTime'] ? Carbon::parse($object['StartDateTime'])->toIso8601String() : null;\n\n $data[] = [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'due' => $dueDate,\n 'type' => $object[$playbook->activityField->crm_provider_id],\n ];\n }\n\n return $data;\n }\n\n /**\n * Try to find CRM Objects using email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByQuery($email, Field::TYPE_EMAIL);\n if ($sosl === null) {\n return null;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $email,\n QueryHandler::PRIORITISE_EMAIL\n );\n\n $data = $this->convertCrmData($objects, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n } catch (NoResultsException $e) {\n // Try the account next.\n if ($this->profile->account_fields === null) {\n return null;\n }\n }\n\n return null;\n }\n\n public function getDomain(string $email): ?string\n {\n // SF improved search - strip the domain extension, min domain name length 4\n return $this->getCompanyNameFromEmail(email: $email, minNameLength: 4);\n }\n\n /**\n * Try to find CRM objects using domain name of the email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByDomain(string $domain, ?int $userId = null): ?array\n {\n $companyName = $domain;\n\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByDomainQuery($companyName);\n\n try {\n $objects = $this->queryHandler->search($sosl);\n\n $data = $this->convertCrmData($objects, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n } catch (NoResultsException) {\n return null;\n }\n }\n\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Don't bother looking up numbers that are masked.\n if (str_contains($phone, '**')) {\n return null;\n }\n\n if ($this->isPhoneNumberOfTeamMember($phone)) {\n return null;\n }\n\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $phoneNational = phone_national(null, $phone) ?? '';\n $possiblePhoneFormats = collect([\n preg_replace('/\\D/', '', ltrim($phone, '0+')),\n preg_replace('/\\D/', '', $phoneNational),\n formatDashPhoneNumber($phone),\n $phoneNational,\n ])\n ->filter() // Removes null and empty strings\n ->unique()\n ->values();\n\n foreach ($possiblePhoneFormats as $phone) {\n $sosl = $queryBuilder->buildMatchByQuery($phone, Field::TYPE_PHONE);\n if ($sosl === null) {\n continue;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $phone,\n QueryHandler::PRIORITISE_PHONE\n );\n\n return $this->convertCrmData($objects, $userId);\n } catch (NoResultsException) {\n continue;\n }\n }\n\n return null;\n }\n\n private function isPhoneNumberOfTeamMember(string $phone): bool\n {\n $teamRepository = app(TeamRepository::class);\n $user = $teamRepository->findTeamMemberByPhone($this->team, $phone);\n\n if ($user instanceof User) {\n return true;\n }\n\n return false;\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->profile->id . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n /** Determine the CRM Objects which represent the call activity. */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n if ($this->profile === null) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByQuery($name, 'name');\n if ($sosl === null) {\n return false;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n } catch (NoResultsException $e) {\n return false;\n }\n\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $name,\n QueryHandler::PRIORITISE_NAME\n );\n\n $data = $this->convertCrmData($objects, $userId);\n\n return (! empty(array_filter($data))) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n /**\n * @return array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n protected function convertCrmData(QueryIterator $objects, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n if ($objects->count() > 0) {\n $object = $objects->current();\n\n if ($object['attributes']['type'] === 'Lead') {\n $lead = $this->importLead($object);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } else {\n if ($object['attributes']['type'] === 'Contact') {\n $contact = $this->importContact($object);\n $account = $contact->account;\n } else {\n $account = $this->importAccount($object);\n }\n\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $sfOpportunities = $this->findOpportunities(\n $account?->getCrmProviderId(),\n $contact?->getCrmProviderId(),\n $userId\n );\n\n // Take the first opportunity, which will be ordered as priority based on their settings.\n if (! empty($sfOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($sfOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n } catch (Exception) {\n // Nothing to see here.\n }\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n if ($stage->type === Stage::TYPE_LEAD) {\n $objectType = 'Lead';\n $objectId = $crmObject->crm_provider_id;\n $objectStageType = 'Status';\n } else {\n $objectType = 'Opportunity';\n $objectId = $crmObject->crm_provider_id;\n $objectStageType = 'StageName';\n }\n\n $headers = [];\n if ($this->config->trigger_assignment_rules === false) {\n // @see: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers_autoassign.htm\n $headers = [\n 'Sforce-Auto-Assign' => 'false',\n ];\n }\n\n $this->updateRecord($objectType, $objectId, [$objectStageType => $stage->name], $headers);\n }\n\n public function parseObjectType(string $objectId): string\n {\n if (Str::startsWith($objectId, '001')) {\n return 'account';\n }\n\n if (Str::startsWith($objectId, '003')) {\n return 'contact';\n }\n\n if (Str::startsWith($objectId, '00Q')) {\n return 'lead';\n }\n\n if (Str::startsWith($objectId, '006')) {\n return 'opportunity';\n }\n\n if (Str::startsWith($objectId, '00U')) {\n return 'event';\n }\n\n if (Str::startsWith($objectId, '00T')) {\n return 'task';\n }\n\n throw new \\InvalidArgumentException('Unsupported Object Type');\n }\n\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, ['profile' => $this->profile]);\n $query = $queryBuilder->buildGetUsersQuery($userToSearch);\n\n try {\n $salesforceUsers = $this->queryHandler->query($query, [\n 'active' => true,\n ]);\n } catch (NoResultsException $e) {\n $this->logger->info('[Salesforce] Sync Profiles. No users found', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n $teamRepository = app(TeamRepository::class);\n $customRules = $this->getCustomProfileRules($teamRepository);\n\n foreach ($salesforceUsers as $crmUser) {\n if ($crmUser['Email'] === null) {\n continue;\n }\n\n if (! $this->customProfileValidation($crmUser, $customRules)) {\n continue;\n }\n\n $user = $teamRepository->findActiveTeamMemberByEmail($this->team, $crmUser['Email']);\n\n if (! $user instanceof User) {\n continue;\n }\n\n $edition = $crmUser['UserPreferencesLightningExperiencePreferred']\n ? Profile::EDITION_LIGHTNING\n : Profile::EDITION_CLASSIC;\n\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->updateOrCreateProfile(\n $user,\n [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmUser['Id'],\n ],\n [\n 'user_id' => $user->getId(),\n 'edition' => $edition,\n 'has_external_cti' => ! empty($crmUser['CallCenterId']),\n 'crm_profile_id' => $crmUser['ProfileId'],\n ]\n );\n\n if ($userToSearch instanceof User && $userToSearch->getId() === $user->getId()) {\n return $profile;\n }\n }\n\n // Clean up inactive profiles\n try {\n $this->archiveInactiveProfiles();\n } catch (\\Exception $e) {\n $this->logger->warning('[Salesforce] Profile archiving failed', [\n 'teamId' => $this->team->getUuid(),\n 'reason' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $url = null;\n\n // For Salesforce it's easy, we just point every object to the apex domain and they handle it.\n switch ($objectType) {\n case 'lead':\n case 'account':\n case 'contact':\n case 'opportunity':\n case 'task':\n case 'event':\n case 'activity':\n\n $url = $this->config->crm_base_url . '/' . $providerId;\n\n break;\n }\n\n return $url;\n }\n\n public function buildTaskSearchFields(): array\n {\n return ['Id', 'WhoId', 'WhatId', 'AccountId'];\n }\n\n public function getTaskByFilterConditions(\n array $fields,\n array $filters,\n bool $bulkSearch = false,\n bool $strictFilters = true\n ): ?array {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildSearchTaskQuery($fields, $filters, $bulkSearch, $strictFilters);\n\n try {\n if (! $bulkSearch) {\n $objects = $this->queryHandler->query($query, $filters);\n if ($objects->count() === 1) {\n return $objects->current();\n }\n }\n\n if ($bulkSearch) {\n $objects = $this->queryHandler->query($query);\n $records = [];\n foreach ($objects as $record) {\n $key = $record[end($fields)];\n $records[$key] = $record;\n }\n\n return $records;\n }\n } catch (\\Exception $e) {\n $this->logger->info('[Salesforce] Failed to execute query', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n public function mapCrmObjects(array $task): array\n {\n $activityData = [];\n\n if (! empty($task['WhoId'])) {\n $type = $this->parseObjectType($task['WhoId']);\n $activityData[$type] = $task['WhoId'];\n }\n if (! empty($task['AccountId'])) {\n $activityData['account'] = $task['AccountId'];\n }\n if (! empty($task['WhatId'])) {\n $activityData['opportunity'] = $task['WhatId'];\n }\n\n return $activityData;\n }\n\n /**\n * Get SF task by Outreach call id.\n */\n public function getTaskByFilter(\n string $activityFieldType,\n array $filters,\n string $operator = '=',\n array $additionalFields = []\n ): ?array {\n $data = [];\n\n try {\n // Default (base) fields.\n $fields = ['Id', 'Subject', 'Description', 'ActivityDate', 'WhoId', 'WhatId', $activityFieldType];\n\n foreach ($additionalFields as $additionalField) {\n $fields[] = $additionalField->crm_provider_id;\n }\n\n $fields = array_unique($fields);\n\n // Find task with the same Outreach id as the call id.\n $query = 'SELECT ' . implode(',', $fields) . '\n FROM Task\n WHERE IsArchived = false AND IsDeleted = false';\n\n foreach ($filters as $key => $value) {\n $key = preg_quote($key, '/');\n $key = str_replace(['\\'', '\"'], '', $key);\n // Prepare the substitution.\n $strKey = \":$key\";\n\n $query .= \" AND $key $operator $strKey\";\n }\n\n $query .= ' ORDER BY LastModifiedDate DESC LIMIT 1';\n\n $objects = $this->queryHandler->query($query, $filters);\n\n // There should be only one task related to this call if any.\n if ($objects->count() === 1) {\n $object = $objects->current();\n\n $dueDate = $object['ActivityDate'] ? Carbon::parse($object['ActivityDate'])->toIso8601String() : null;\n\n $data = array_merge($object, [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'summary' => $object['Description'],\n 'due' => $dueDate,\n 'Type' => $object[$activityFieldType],\n ]);\n }\n } catch (NoResultsException $e) {\n // Filters don't match any records.\n } catch (ServiceUnavailableException $serviceUnavailableException) {\n // Service cannot be queried. We should probably log this.\n }\n\n return $data;\n }\n\n /**\n * Get Salesforce fields including datetime fields\n *\n * @param $objectType\n */\n private function getAllFieldsAsArray($objectType): array\n {\n $basicFields = [];\n // Not all users have access to all object fields.\n if ($this->profile->{$objectType . '_fields'}) {\n $basicFields = explode(',', $this->profile->{$objectType . '_fields'});\n }\n\n $extraFields = [\n 'CreatedDate',\n 'LastModifiedDate',\n 'IsDeleted',\n ];\n\n if ($objectType === self::OBJECT_OPPORTUNITY\n && $this->config->opportunity_value_field_id\n && ! in_array($this->config->opportunityValueField->crm_provider_id, $basicFields)\n ) {\n $extraFields[] = $this->config->opportunityValueField->crm_provider_id;\n }\n\n return array_unique(array_merge($basicFields, $extraFields));\n }\n\n /**\n * Generate transcription for activity description.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! ($this->config->store_transcript)) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n return $this->transcriptionService\n ->findTranscriptionByActivity($activity)\n ->map(static function (array $transcriptionSegment): string {\n return $transcriptionSegment['formattedStartsAt'] . ' | ' . $transcriptionSegment['transcript'];\n })\n ->implode(PHP_EOL);\n }\n\n /**\n * Find related Salesforce event based on activity data\n *\n * @return array<string>\n */\n public function fetchRelatedActivity(Activity $activity): array\n {\n $this->logger->info('[Salesforce] Searching for related activity', [\n 'activityId' => $activity->getUuid(),\n 'ownerId' => $this->profile?->crm_provider_id,\n ]);\n\n $sfEvent = $this->fetchRelatedEvent($activity);\n if (empty($sfEvent)) {\n $this->logger->info('[Salesforce] No related activity found', [\n 'activityId' => $activity->getUuid(),\n 'ownerId' => $this->profile?->crm_provider_id,\n 'account' => $activity->hasAccount()\n ? $activity->getAccount()->getCrmProviderId()\n : null,\n ]);\n\n return [];\n }\n\n return $sfEvent;\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n if ($activity->isTypeConference() === false) {\n return null;\n }\n\n if ($activity->hasActualStartTime() === false && $activity->hasScheduledStartTime() === false) {\n return null;\n }\n\n if (! $activity->hasProspect()) {\n $this->logger->info('[Salesforce] Skip look up, Activity not linked to Lead, Contact or Account', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $playbook = $this->getPlaybook($activity->getUser());\n if ($playbook !== null && $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK) {\n $this->logger->info('[Salesforce] Skip auto-sync for task-based playbook', [\n 'activityUuid' => $activity->getUuid(),\n 'playbookId' => $playbook->getId(),\n 'playbookType' => $playbook->getActivityType(),\n ]);\n\n return null;\n }\n\n try {\n $sfEvent = $this->fetchRelatedActivity($activity);\n if (empty($sfEvent)) {\n return null;\n }\n\n [$activityField, $activityType] = $this->resolveActivityTypeFromEvent($activity, $sfEvent);\n\n $this->logger->info('[Salesforce] Found related activity', [\n 'activityId' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n 'activityFieldName' => $activityField,\n 'crmActivityType' => ($activityField !== null && isset($sfEvent[$activityField]))\n ? $sfEvent[$activityField]\n : null,\n 'activityType' => $activityType,\n ]);\n\n $userId = $this->findRelatedActivityUserId($activity, $sfEvent);\n\n if ($activity->getUserId() !== $userId) {\n $this->logger->info('[Salesforce] Updating meeting owner', [\n 'activityId' => $activity->getUuid(),\n 'oldUserId' => $activity->getUserId(),\n 'newUserId' => $userId,\n ]);\n }\n\n $this->updateSfEventDescription($activity, $sfEvent);\n\n $activity->update([\n 'user_id' => $userId,\n 'crm_provider_id' => $sfEvent['Id'],\n 'playbook_category_id' => $activityType->id ?? $activity->getCategory()?->getId(),\n ]);\n\n $this->logger->info('[Salesforce] Activity updated', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return $activity;\n } catch (\\Exception $exception) {\n \\Sentry::captureException($exception);\n\n throw $exception;\n }\n }\n\n /**\n * @param array<string, mixed> $sfEvent\n *\n * @return array{0: string|null, 1: mixed}\n */\n private function resolveActivityTypeFromEvent(Activity $activity, array $sfEvent): array\n {\n $activityField = $this->getActivityFieldName($activity);\n $activityType = null;\n\n if ($activityField !== null && ! empty($sfEvent[$activityField])) {\n $playbook = $this->getPlaybook($activity->getUser());\n $activityType = $this->getPlaybookCategory($playbook, strval($sfEvent[$activityField]));\n }\n\n return [$activityField, $activityType];\n }\n\n /**\n * @param array<string> $sfEvent\n */\n private function findRelatedActivityUserId(Activity $activity, array $sfEvent): int\n {\n $userId = $activity->getUserId();\n\n if (empty($sfEvent['OwnerId']) === false) {\n $profile = $this\n ->config\n ->profiles()\n ->where('crm_provider_id', $sfEvent['OwnerId'])\n ->get()\n ->filter(static function (Profile $profile) use ($activity): bool {\n if (! $activity->isTypeConference()) {\n return ! empty($profile->user) ? $profile->user->isStatusActive() : false;\n }\n\n $participants = $activity->getParticipants();\n\n return ! empty($profile->user)\n ? $profile->user->isStatusActive()\n && $profile->user->hasPermission(PermissionEnum::RECORD_MEETING)\n && $participants->contains('user_id', $profile->user_id)\n : false;\n })\n ->first();\n\n if ($profile) {\n $userId = $profile->user_id;\n }\n }\n\n return $userId;\n }\n\n /**\n * @param array<string, mixed> $sfEvent\n */\n private function updateSfEventDescription(Activity $activity, array $sfEvent): void\n {\n try {\n if (str_contains($sfEvent['Description'], $activity->id_string)) {\n return;\n }\n\n $payload = [\n 'Description' => $sfEvent['Description']\n . PHP_EOL\n . PHP_EOL\n . (new DecorateActivity())->generateDescription($activity),\n ];\n\n $this->logger->info('[Salesforce] Update record', [\n 'activityId' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n 'payload' => $payload,\n ]);\n\n $payload = array_merge(\n $payload,\n $this->payloadBuilder->fetchCustomFieldData($activity, Field::OBJECT_EVENT)\n );\n\n $this->updateRecord('Event', $sfEvent['Id'], $payload);\n } catch (\\Exception) {\n $this->logger->error('[Salesforce] Failed to update record', [\n 'activityUuid' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n ]);\n }\n }\n\n /**\n * Returns the most recently modified Event within time range (if any).\n *\n * @return array|null An Event record from Salesforce.\n */\n private function fetchRelatedEvent(Activity $activity): ?array\n {\n $ownerId = $this->profile?->crm_provider_id;\n if ($ownerId === null) {\n return [];\n }\n\n /** @var ?Carbon $from */\n /** @var ?Carbon $to */\n [$from, $to] = $this->getFromToDates($activity);\n\n try {\n $whoId = null;\n $hasWho = $activity->lead_id || $activity->contact_id;\n if ($hasWho) {\n $whoId = $activity->hasLead()\n ? $activity->getLead()->crm_provider_id\n : $activity->getContact()->crm_provider_id;\n }\n\n if ($hasWho === false && $activity->account_id === null) {\n return null;\n }\n\n $query = $this->buildFetchRelatedEventQuery($activity);\n\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $ownerId,\n 'whoId' => $whoId,\n 'whatId' => $activity->hasOpportunity() ? $activity->getOpportunity()->crm_provider_id : null,\n 'accountId' => $activity->hasAccount() ? $activity->getAccount()->crm_provider_id : null,\n 'from' => $from?->format('Y-m-d\\TH:i:s\\Z'),\n 'to' => $to?->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($objects as $object) {\n return $object;\n }\n } catch (NoResultsException $e) {\n return [];\n }\n\n return [];\n }\n\n private function getFromToDates(Activity $activity): array\n {\n $from = null;\n $to = null;\n\n /** @var ?CalendarEvent $calendarEvent */\n $calendarEvent = $activity->calendarEvent()->first();\n if ($calendarEvent !== null) {\n $from = $calendarEvent->getStartTime();\n $to = $calendarEvent->getEndTime();\n }\n\n // For non-calendar imported activities\n // Also double check if calendar event dates could be null?\n // If null use what we've got so far\n if ($from === null || $to === null) {\n $from = $activity->hasScheduledStartTime()\n ? $activity->getScheduledStartTime()\n : $activity->getActualStartTime();\n $to = $activity->hasScheduledEndTime()\n ? $activity->getScheduledEndTime()->addMinutes(15)\n : $activity->getActualEndTime();\n }\n\n return [$from, $to];\n }\n\n /**\n * Determines the appropriate activity field name for querying Salesforce events.\n *\n * This method follows a hierarchy to determine the field name:\n * 1. Uses the playbook's activity field if it exists and is in the profile's accessible fields\n * 2. Falls back to the default activity field if the profile has no event fields configured\n * 3. Returns null if no suitable field is found\n *\n * @param Activity $activity The activity to determine the field for\n *\n * @return string|null The field name to use in queries, or null if none is available\n */\n private function getActivityFieldName(Activity $activity): ?string\n {\n if ($this->profile === null) {\n $this->logger->warning('[Salesforce] Cannot determine activity field - profile not found', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $profileEventFields = $this->profile->getFieldsAsArray('event');\n\n if (empty($profileEventFields)) {\n $defaultActivityField = $this->getDefaultActivityField(Field::OBJECT_EVENT);\n $defaultFieldName = $defaultActivityField?->getAttribute('crm_provider_id');\n // Profile not yet synced — fall back to the default activity field.\n // There is a small chance that the profile won't have Default Activity Type field access\n // in which case the query will fail.\n // This is however an edge case and should be reviewed for profile sync issues.\n Sentry::withScope(function (\\Sentry\\State\\Scope $scope) use ($defaultFieldName): void {\n $scope->setContext('details', [\n 'profileId' => $this->profile->id,\n 'defaultField' => $defaultFieldName,\n ]);\n Sentry::captureMessage(\n '[Salesforce] Profile event fields empty, falling back to default activity field.',\n \\Sentry\\Severity::warning()\n );\n });\n\n return $defaultFieldName;\n }\n\n $playbook = $this->getPlaybook($activity->getUser());\n\n if (! is_null($playbook) && ! is_null($playbook->getActivityField())) {\n $playbookFieldName = $playbook->getActivityField()->getAttribute('crm_provider_id');\n\n if (in_array($playbookFieldName, $profileEventFields, true)) {\n return $playbookFieldName;\n }\n\n $this->logger->warning('[Salesforce] Playbook activity field not found in profile fields', [\n 'activityId' => $activity->getUuid(),\n 'playbookField' => $playbookFieldName,\n 'profileId' => $this->profile->id,\n ]);\n }\n\n return null;\n }\n\n private function buildFetchRelatedEventQuery(Activity $activity): string\n {\n $hasWho = $activity->lead_id || $activity->contact_id;\n\n $activityFieldName = $this->getActivityFieldName($activity);\n $fields = array_filter(['Id', 'Description', 'OwnerId', $activityFieldName]);\n\n $ownerCondition = '(OwnerId = :ownerId OR CreatedById = :ownerId)';\n\n $query = '\n SELECT ' . implode(',', $fields) . '\n FROM Event\n WHERE ' . $ownerCondition . '\n AND IsArchived = false\n AND IsAllDayEvent = false\n AND StartDateTime >= :from\n AND EndDateTime <= :to\n AND (';\n\n $operator = '';\n if ($activity->account_id) {\n // This covers events tied to a related contact or opportunity too.\n $query .= 'AccountId = :accountId';\n\n $operator = ' OR ';\n }\n\n if ($hasWho) {\n $query .= $operator . 'WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($activity->opportunity_id) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ') ORDER BY LastModifiedDate DESC';\n\n return $query;\n }\n\n public function fetchProspect(array $task): array\n {\n $lead = $account = $opportunity = $contact = $stage = $countryCode = null;\n $externalId = $task['WhoId'] ?? null;\n\n // Lead or Contact\n if ($externalId) {\n try {\n [$lead, $account, $opportunity, $contact, $stage, $countryCode] = $this->parseRecords($externalId);\n } catch (\\InvalidArgumentException $exception) {\n // Invalid object type.\n }\n }\n\n // If we happen to know the opportunity or account from the Task, figure that out.\n if (empty($task['WhatId']) === false) {\n // WhatId could be either Account ID or Opportunity ID.\n // If WhatId is Opportunity ID, get the opportunity and stage from the CRM.\n try {\n [, $account, $opportunity, , $stage, ] = $this->parseRecords($task['WhatId']);\n } catch (\\InvalidArgumentException $exception) {\n // Invalid object type.\n }\n }\n\n return [$lead, $account, $opportunity, $contact, $stage, $countryCode];\n }\n\n /**\n * Save activity transcription summary as note\n */\n public function saveTranscriptionSummaryAsNote(\n ActivityContract $activity,\n string $title,\n string $body,\n ?string $objectId,\n ?NoteObject $noteObject = null,\n ): ?string {\n return $this->saveNote($title, $body, (string) $objectId);\n }\n\n public function getObjectByFilterConditions(string $objectType, array $fields, array $filters): ?array\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildObjectSearchQuery($objectType, $fields, $filters);\n\n try {\n $objects = $this->queryHandler->query($query, $filters);\n if ($objects->count() === 1) {\n return $objects->current();\n }\n } catch (\\Exception $e) {\n $this->logger->info('[Salesforce] Failed to execute query', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n private function getCustomProfileRules(TeamRepository $teamRepository): array\n {\n $teamSettings = $teamRepository->getTeamSetting($this->team, 'custom_profile_validation');\n\n if ($teamSettings instanceof TeamSettings && $teamSettings->getValueType() === 'array') {\n $customRules = json_decode($teamSettings->getValue(), true);\n if (is_array($customRules)) {\n return $customRules;\n }\n }\n\n return [];\n }\n\n private function customProfileValidation(array $crmUser, array $customRules): bool\n {\n foreach ($customRules as $customRule) {\n if ($crmUser[$customRule['field']] !== $customRule['value']) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * When syncing Contact / Lead / Account / Opportunity / Stage crm entities,\n * validate and restore locally trashed objects,\n * before updating them. Objects are identified by CrmProviderId\n */\n private function restoreAnyTrashedEntity(HasMany $targetEntity, string $crmProviderId): void\n {\n $recordExists = $targetEntity->withTrashed()->where(['crm_provider_id' => $crmProviderId])->first();\n if ($recordExists && $recordExists->trashed()) {\n $recordExists->restore();\n }\n }\n\n #[\\Override] public function supportsNotes(): bool\n {\n return true;\n }\n\n private function getOwnerProfile(?string $ownerId): ?Profile\n {\n if ($ownerId === null) {\n return null;\n }\n\n return $this->config->profiles()\n ->where('crm_provider_id', $ownerId)\n ->first();\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Salesforce;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Illuminate\\Database\\Eloquent\\Relations\\HasMany;\nuse Illuminate\\Events\\Dispatcher;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Illuminate\\Support\\Facades\\Log;\nuse Illuminate\\Support\\Str;\nuse Jiminny\\Component\\Country\\CountriesMap;\nuse Jiminny\\Contracts\\Acl\\PermissionEnum;\nuse Jiminny\\Contracts\\Repositories\\TeamRepository;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\ImportsBusinessProcessesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\SalesforceBatchSyncInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\SalesforceInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteNoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SearchTaskInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SendSummaryToCrmInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SupportsObjectTypeParseInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmProfileRecordTypesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Enums\\CrmObject;\nuse Jiminny\\Events\\Activities\\Crm\\LeadConverted;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpBadRequestException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\NoResultsException;\nuse Jiminny\\Exceptions\\ServiceUnavailableException;\nuse Jiminny\\Jobs\\Crm\\NoteObject;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Calendar\\CalendarEvent;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Contracts\\ActivityContract;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\ContactRole;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Crm\\RecordType;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\TeamSettings;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\ContactRoleRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\Crm\\RecordTypeFieldValuesRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\Helpers\\ArrayIterator;\nuse Jiminny\\Services\\Crm\\MatchDomainByEmailInterface;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Services\\Crm\\ResolveCompanyNameByEmailTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\FieldHelper;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\FieldTypeConverter;\nuse Jiminny\\Services\\Crm\\Salesforce\\Fields\\ValueNormalizer;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\FollowupActivityTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\LogActivityTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\RecordManipulationsTrait;\nuse Jiminny\\Services\\Crm\\Salesforce\\ServiceTraits\\SyncFieldsTrait;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\nuse Ramsey\\Uuid\\Uuid;\nuse Sentry\\Laravel\\Facade as Sentry;\n\nclass Service extends BaseService implements\n SalesforceInterface,\n SalesforceBatchSyncInterface,\n SyncCrmEntitiesInterface,\n SyncCrmProfileRecordTypesInterface,\n ImportsBusinessProcessesInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n SendSummaryToCrmInterface,\n MatchDomainByEmailInterface,\n SearchTaskInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n SupportsObjectTypeParseInterface,\n RemoteNoteEntityManipulationInterface,\n VerifyTaskExistsInterface\n{\n use ResolveCompanyNameByEmailTrait;\n use SyncFieldsTrait;\n use DeleteObjectsTrait;\n use RecordManipulationsTrait;\n use ServiceTraits\\BatchSyncTrait;\n use FollowupActivityTrait;\n use LogActivityTrait;\n\n /**\n * Note Body Limit for the Old Note-Taking Tool\n *\n * @var int\n */\n private const int CLASSIC_NOTE_MAX_LENGTH = 32000;\n\n /**\n * Note Content Limit for the New Notes\n *\n * @var int\n */\n private const int ENHANCED_NOTE_MAX_LENGTH = 50000000;\n\n private const string INSTALLED_PACKAGE_ID = '033Tw0000007bKbIAI';\n\n private const int CACHE_TTL = 600;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day - 86400\n\n /**\n * @var Client\n */\n protected $client;\n\n protected PayloadBuilder $payloadBuilder;\n protected QueryHandler $queryHandler;\n\n private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n\n public function __construct(\n Client $client,\n PayloadBuilder $payloadBuilder,\n protected Dispatcher $eventDispatcher,\n private readonly CountriesMap $countriesMap,\n private readonly ProspectPhotoPathService $prospectPhotoPathService,\n ) {\n parent::__construct();\n\n $this->client = $client;\n $this->payloadBuilder = $payloadBuilder;\n $this->queryHandler = app(QueryHandler::class, [\n 'client' => $this->client,\n 'logger' => $this->logger,\n ]);\n $this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n }\n\n public function getDisplayName(): string\n {\n return 'Salesforce';\n }\n\n public function getJobDelay(): int\n {\n return 1;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n return $user->getSocialAccount(SocialAccount::PROVIDER_SALESFORCE);\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($activity, $crmProviderId) {\n $playbook = $this->getPlaybookFromActivity($activity);\n\n if ($playbook === null) {\n $this->logger->warning('[Salesforce] Cannot verify task - no playbook found', [\n 'activity' => $activity->getId(),\n 'crm_provider_id' => $crmProviderId,\n ]);\n\n return false;\n }\n\n $objectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_EVENT ? 'Event' : 'Task';\n\n try {\n $record = $this->getRecord($objectType, $crmProviderId, ['Id', 'IsDeleted']);\n\n return ! empty($record) && ($record['IsDeleted'] ?? false) === false;\n } catch (HttpNotFoundException|HttpBadRequestException) {\n $this->logger->info('[Salesforce] Activity record not found during verification', [\n 'activity' => $activity->getId(),\n 'object_type' => $objectType,\n 'crm_provider_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n });\n }\n\n public function query(string $queryToRun, array $parameters = []): QueryIterator\n {\n // Due to poorly designed external calls, this method cannot be entirely removed\n return $this->queryHandler->query($queryToRun, $parameters);\n }\n\n /*=========== Organization Information ===============*/\n\n /**\n * Get a list of all the API Versions for the instance.\n *\n * @throws CrmException\n *\n * @return mixed\n *\n */\n public function getApiVersions()\n {\n $url = $this->config->crm_base_url . '/services/data';\n\n $response = $this->client->get($url);\n\n return json_decode($response->getBody(), true);\n }\n\n /**\n * Gets the valid recordTypes for a given Salesforce Object via the describe API.\n */\n private function getRecordTypes(string $crmObject): array\n {\n $url = $this->client->getObjectsUrl() . $crmObject . '/describe';\n\n $response = $this->client->get($url);\n $jsonResponse = json_decode($response->getBody(), true);\n\n $fields = [];\n foreach ($jsonResponse['recordTypeInfos'] as $row) {\n $fields[] = ['recordTypeId' => $row['recordTypeId'], 'default' => $row['defaultRecordTypeMapping']];\n }\n\n return $fields;\n }\n\n /**\n * Convert raw field data into a format compatible with CRM APIs.\n */\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return ValueNormalizer::normalize($fieldType, $fieldValue, $internal);\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n $defaultFields = ($activityType === Playbook::ACTIVITY_TYPE_TASK)\n ? FieldDefinitions::defaultTaskFields()\n : FieldDefinitions::defaultEventFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'Type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK, Playbook::ACTIVITY_TYPE_EVENT];\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n\n $fieldFilter = ($activityType === Playbook::ACTIVITY_TYPE_TASK)\n ? FieldDefinitions::taskFollowupFieldsFilter()\n : FieldDefinitions::eventFollowupFieldsFilter();\n\n foreach ($fieldFilter as $eachFilter) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $eachFilter);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n /**\n * This one is now called only when ImportActivityTypes is triggered or SyncFieldMetadata executed manually\n * Regular sync now uses SharedSyncFieldsTrait -> syncSingleObjectType\n * Needs to be replaced later on\n */\n public function syncField(Field $field): void\n {\n try {\n if (FieldHelper::isCustomField($field)) {\n $query = '\n SELECT\n Id, Metadata, TableEnumOrId\n FROM\n CustomField\n WHERE\n DeveloperName = :fieldName\n AND\n TableEnumOrId = :fieldType\n AND\n NamespacePrefix = :namespacePrefix';\n\n // We need to constrain the field lookup to the object, in case it's used in multiple places.\n $objectType = \\in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true)\n ? 'activity'\n : $field->object_type;\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'fieldName' => substr($field->crm_provider_id, 0, -\\strlen('__c')),\n 'fieldType' => ucfirst($objectType),\n\n // This is used to ensure we only consider the field within the org, not installed packages.\n 'namespacePrefix' => 'null',\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Sync field metadata.\n $metadata = $sfField['Metadata'];\n\n $field->description = mb_strimwidth($metadata['description'] ?? '', 0, 191);\n $field->label = mb_strimwidth($metadata['label'] ?? '', 0, Field::LABEL_MAX_LENGTH);\n $field->type = $this->convertFieldType($metadata['type'], $field->getEntityName());\n $field->is_mandatory = ($metadata['required'] === true);\n $field->length = $metadata['length'];\n $field->default_value = mb_strimwidth(trim($metadata['defaultValue'] ?? '', '\"'), 0, 191);\n $field->save();\n } else {\n $query = '\n SELECT\n Id, DataType, DeveloperName, Label, Length, Description\n FROM\n FieldDefinition\n WHERE\n DurableId = :entityName';\n\n $entityName = $field->getEntityName();\n $sfFields = $this->queryHandler->metadata($query, [\n 'entityName' => $entityName,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n $convertedType = $this->convertFieldType($sfField['DataType'], $entityName);\n $label = mb_strimwidth($sfField['Label'], 0, Field::LABEL_MAX_LENGTH);\n\n if ($field->isBusinessType()) {\n $label = 'Opportunity Type';\n }\n\n $field->description = mb_strimwidth($sfField['Description'], 0, Field::DESCRIPTION_MAX_LENGTH);\n $field->label = $label;\n $field->type = $convertedType;\n $field->length = $sfField['Length'];\n $field->save();\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n private function convertFieldType(string $from, ?string $entityName = null): string\n {\n $converter = new FieldTypeConverter();\n\n return $converter->convert($from, $entityName);\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $values = [];\n $fieldValues = [];\n\n try {\n if (FieldHelper::isCustomField($field)) {\n $query = '\n SELECT\n Id, Metadata, TableEnumOrId\n FROM\n CustomField\n WHERE\n DeveloperName = :fieldName\n AND\n TableEnumOrId = :fieldType\n AND\n NamespacePrefix = :namespacePrefix';\n\n // We need to constrain the field lookup to the object, in case it's used in multiple places.\n $objectType = \\in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true) ?\n 'activity' : $field->object_type;\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'fieldName' => substr($field->crm_provider_id, 0, -\\strlen('__c')),\n 'fieldType' => ucfirst($objectType),\n // This is used to ensure we only consider the field within the org, not installed packages.\n 'namespacePrefix' => 'null',\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n $valueSet = $sfField['Metadata']['valueSet'];\n\n if ($valueSet['valueSetName'] === null) {\n // Local picklist values can be obtained easily.\n $picklistValues = $valueSet['valueSetDefinition']['value'];\n } else {\n // But for some fields, we just get the Global Value Picklist pointer so need to do more work.\n $picklistValues = $this->importGlobalValuePicklistValues($valueSet['valueSetName']);\n }\n\n // Import all active values.\n foreach ($picklistValues as $i => $sfFieldValue) {\n // Setup default value.\n if ($sfFieldValue['default']) {\n $field->update(['default_value' => $sfFieldValue['valueName']]);\n }\n\n // This comes through as null if active (lol).\n if ($sfFieldValue['isActive'] !== false) {\n $values[] = [\n 'value' => $sfFieldValue['valueName'],\n 'label' => $sfFieldValue['valueName'],\n 'sequence' => $i,\n 'is_default' => $sfFieldValue['default'],\n ];\n }\n }\n } else {\n $objectFields = $this->getObjectFields($field->object_type);\n $fieldId = $field->crm_provider_id;\n\n // Only work with our field of interest.\n $objectField = array_filter($objectFields, function ($item) use ($fieldId) {\n return $item['name'] === $fieldId;\n });\n\n $objectField = array_shift($objectField);\n if (empty($objectField['picklistValues']) === false) {\n foreach ($objectField['picklistValues'] as $i => $sfFieldValue) {\n // Skip inactive values.\n if ($sfFieldValue['active'] === false) {\n continue;\n }\n\n // Setup default value.\n if ($sfFieldValue['defaultValue']) {\n $field->update(['default_value' => $sfFieldValue['value']]);\n }\n\n $values[] = [\n 'value' => $sfFieldValue['value'],\n 'label' => $sfFieldValue['label'],\n 'sequence' => $i,\n 'is_default' => $sfFieldValue['defaultValue'],\n ];\n }\n }\n }\n\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n if (($key = array_search($value['value'], $fieldsToPurge, true)) !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n // Get IDs of the values to be deleted\n $valuesToDelete = $field->values()->whereIn('value', $fieldsToPurge);\n $valuesToDeleteIds = $valuesToDelete->pluck('id');\n if (! $valuesToDeleteIds->isEmpty()) {\n $recordTypeFieldValuesRepository = app(RecordTypeFieldValuesRepository::class);\n $recordTypeFieldValuesRepository->deleteForCrmFieldValueIds($valuesToDeleteIds->toArray());\n\n // Now safely delete from crm_field_values\n $valuesToDelete->delete();\n }\n\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n return $fieldValues;\n }\n\n /**\n * Gets values from Global Value Picklists.\n */\n private function importGlobalValuePicklistValues(string $picklistName): array\n {\n $query = '\n SELECT\n Metadata\n FROM\n GlobalValueSet\n WHERE\n DeveloperName = :picklistName\n LIMIT 1';\n\n try {\n $sfValues = $this->queryHandler->metadata($query, [\n 'picklistName' => $picklistName,\n ]);\n\n // There is always 1 result at this point.\n $sfValue = $sfValues->current();\n\n return $sfValue['Metadata']['customValue'];\n } catch (NoResultsException $noResultsException) {\n // Nothing returned.\n\n return [];\n }\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileRecordTypes(): void\n {\n $objectTypes = [\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n 'task',\n 'event',\n ];\n\n foreach ($objectTypes as $objectType) {\n try {\n $crmRecordTypes = $this->getRecordTypes(ucfirst($objectType));\n\n foreach ($crmRecordTypes as $crmRecordType) {\n // If the record type is default and not the Master type, set this.\n if ($crmRecordType['default'] && $crmRecordType['recordTypeId'] !== '012000000000000AAA') {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $crmRecordType['recordTypeId'])\n ->first();\n\n if ($recordType) {\n $this->profile->{$objectType . '_record_type_id'} = $recordType->id;\n }\n }\n }\n } catch (HttpNotFoundException $exception) {\n Log::error('No access to ' . $objectType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n if ($this->profile->isDirty()) {\n $this->profile->save();\n }\n }\n\n /**\n * Gets business processes.\n */\n public function importBusinessProcesses(): void\n {\n $query = '\n SELECT\n Id, IsActive, Name, TableEnumOrId\n FROM\n BusinessProcess\n WHERE\n TableEnumOrId IN (\\'Lead\\',\\'Opportunity\\')';\n\n try {\n $sfProcesses = $this->queryHandler->query($query);\n\n // Upsert all processes for the team.\n foreach ($sfProcesses as $sfProcess) {\n /** @var BusinessProcess $businessProcess */\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $sfProcess['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => $sfProcess['Name'],\n 'type' => $sfProcess['TableEnumOrId'] === 'Lead' ? 'lead' : 'opportunity',\n 'is_selectable' => $sfProcess['IsActive'],\n ]);\n\n $this->importBusinessProcessStages($businessProcess);\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * Gets business process stages.\n */\n private function importBusinessProcessStages(BusinessProcess $businessProcess): void\n {\n $query = '\n SELECT\n Metadata\n FROM\n BusinessProcess\n WHERE\n Id = :processId';\n\n try {\n $stages = [];\n $sfProcessStages = $this->queryHandler->metadata($query, [\n 'processId' => $businessProcess->crm_provider_id,\n ]);\n\n // There is always 1 result at this point.\n $sfProcessStage = $sfProcessStages->current();\n\n // Upsert all processes for the team.\n foreach ($sfProcessStage['Metadata']['values'] as $sfProcessStage) {\n $sanitizedName = urldecode($sfProcessStage['valueName']); // Must decode: \"%2C\" becomes \",\" etc.\n\n $stage = $businessProcess->crm->stages()\n // This MUST match on label because this API doesn't use API Name.\n ->where('label', $sanitizedName)\n ->where('type', $businessProcess->type)\n ->where('is_selectable', 1)\n ->first();\n\n if ($stage) {\n $stages[] = $stage->id;\n }\n }\n\n $businessProcess->stages()->sync($stages);\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * Gets record types.\n */\n public function importRecordTypes(): void\n {\n $query = '\n SELECT\n Id, IsActive, Name, BusinessProcessId, SobjectType\n FROM\n RecordType';\n\n try {\n $sfRecordTypes = $this->queryHandler->query($query);\n\n // Upsert all record types for the process.\n foreach ($sfRecordTypes as $sfRecordType) {\n $businessProcess = null;\n if ($sfRecordType['BusinessProcessId']) {\n $businessProcess = $this->config->businessProcesses()\n ->where('crm_provider_id', $sfRecordType['BusinessProcessId'])\n ->first();\n }\n\n /** @var RecordType $recordType */\n $recordType = $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $sfRecordType['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'type' => mb_strtolower($sfRecordType['SobjectType']),\n 'name' => $sfRecordType['Name'],\n 'is_selectable' => $sfRecordType['IsActive'],\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $this->importRecordTypeFieldValues($recordType);\n }\n } catch (NoResultsException $noResultsException) {\n // Do nothing.\n }\n }\n\n /**\n * Import record type - field value mappings. This only works for standard fields.\n */\n private function importRecordTypeFieldValues(RecordType $recordType): void\n {\n try {\n $query = '\n SELECT\n Metadata\n FROM\n RecordType\n WHERE\n Id = :recordTypeId';\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'recordTypeId' => $recordType->crm_provider_id,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Sync field metadata.\n $picklists = $sfField['Metadata']['picklistValues'];\n\n foreach ($picklists as $picklist) {\n $field = $this->config->fields()->where([\n 'type' => Field::TYPE_PICKLIST,\n 'object_type' => $recordType->type,\n 'crm_provider_id' => $picklist['picklist'],\n ])->first();\n\n if ($field) {\n $fieldValues = [];\n\n foreach ($picklist['values'] as $value) {\n // Must decode: \"%2C\" becomes \",\" etc.\n $fieldValue = $field->values()\n ->where('value', urldecode($value['valueName']))\n ->first();\n\n if ($fieldValue) {\n $fieldValues[] = $fieldValue->id;\n }\n }\n\n $recordType->fieldValues()->sync($fieldValues);\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n }\n\n /**\n * @inheritdoc\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $params = [];\n $missingStage = null;\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n\n foreach ($types as $type) {\n if ($type === Stage::TYPE_LEAD) {\n $query = '\n SELECT\n Id, ApiName, MasterLabel, SortOrder\n FROM\n LeadStatus';\n } else {\n $query = '\n SELECT\n Id, ApiName, MasterLabel, IsActive, SortOrder, DefaultProbability\n FROM\n OpportunityStage';\n }\n\n if ($missingStageName) {\n $escapedStageName = ValueNormalizer::replaceQueryWithStringLiterals($missingStageName);\n\n $query .= ' WHERE ApiName = :stageName';\n\n $params = [\n 'stageName' => $escapedStageName,\n ];\n }\n\n try {\n $sfStages = $this->queryHandler->query($query, $params);\n } catch (NoResultsException $exception) {\n $sfStages = [];\n }\n\n $missingStage = null;\n\n // Upsert all stages for the team.\n foreach ($sfStages as $sfStage) {\n $selectable = true;\n if (array_key_exists('IsActive', $sfStage)) {\n $selectable = $sfStage['IsActive'];\n }\n\n $this->restoreAnyTrashedEntity($this->config->stages(), $sfStage['Id']);\n\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $sfStage['Id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($sfStage['ApiName'], 0, 50),\n 'label' => mb_strimwidth($sfStage['MasterLabel'], 0, 191),\n 'type' => $type,\n 'sequence' => $sfStage['SortOrder'] ?? 0,\n 'is_selectable' => $selectable,\n 'probability' => $sfStage['DefaultProbability'] ?? null,\n ]);\n\n if ($missingStageName && $missingStageName === $sfStage['ApiName']) {\n $missingStage = $stage;\n }\n }\n\n if ($missingStageName && $missingStage === null) {\n // If they requested a stage that still doesn't exist, it must be inactive so lazy create it.\n $missingStage = $this->config->stages()->create([\n 'crm_provider_id' => Uuid::uuid4(),\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($missingStageName, 0, 50),\n 'label' => mb_strimwidth($missingStageName, 0, 191),\n 'type' => $type,\n 'sequence' => 0,\n 'is_selectable' => 0,\n ]);\n }\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('lead');\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Lead\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfLeads = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfLeads as $sfLead) {\n // Only sync if previously imported.\n if ($this->hasLead($sfLead['Id'])) {\n $this->importLead($sfLead);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::LEAD);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n $fields = $this->getAllFieldsAsArray('lead');\n\n $sfLead = $this->getRecord('Lead', $crmId, $fields);\n\n return $this->importLead($sfLead);\n }\n\n private function importLead($crmData): ?Lead\n {\n /** @var ?Stage $stage */\n $stage = null;\n if (isset($crmData['Status'])) {\n // Get the current stage.\n $stage = $this->config\n ->stages()\n ->where('name', $crmData['Status'])\n ->where('type', Stage::TYPE_LEAD)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['Status']);\n }\n }\n\n // If we have no way of importing this, just return null :(\n if ($stage === null) {\n return null;\n }\n\n $countryCode = $crmData['CountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country name.\n if ($countryCode === null && empty($crmData['Country']) !== false) {\n $countryCode = $this->convertCountryNameToCode($crmData['Country']);\n }\n\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['Phone'] ?? '', 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n\n $mobilePhone = null;\n if (empty($crmData['MobilePhone']) === false) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['MobilePhone'], 0, 25);\n $mobilePhone = phone_e164($countryCode, $number);\n }\n\n $convertedDate = null;\n $convertedAccount = null;\n $convertedOpportunity = null;\n $convertedContact = null;\n\n if ($crmData['IsConverted'] == 'true') {\n $convertedDate = $crmData['ConvertedDate'];\n\n if (empty($crmData['ConvertedAccountId']) === false) {\n $convertedAccount = $this->config\n ->accounts()\n ->where('crm_provider_id', $crmData['ConvertedAccountId'])\n ->first();\n\n if ($convertedAccount === null) {\n try {\n $convertedAccount = $this->syncAccount($crmData['ConvertedAccountId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n\n if (empty($crmData['ConvertedOpportunityId']) === false) {\n $convertedOpportunity = $this->config\n ->opportunities()\n ->where('crm_provider_id', $crmData['ConvertedOpportunityId'])\n ->first();\n\n if ($convertedOpportunity === null) {\n try {\n $convertedOpportunity = $this->syncOpportunity($crmData['ConvertedOpportunityId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n\n if (empty($crmData['ConvertedContactId']) === false) {\n $convertedContact = $this->team\n ->crm\n ->contacts()\n ->where('crm_provider_id', $crmData['ConvertedContactId'])\n ->first();\n\n if ($convertedContact === null) {\n try {\n $convertedContact = $this->syncContact($crmData['ConvertedContactId']);\n } catch (HttpNotFoundException $exception) {\n // Probably the user has no permissions to access the converted data.\n }\n }\n }\n }\n\n if (empty($crmData['Company'])) {\n $company = 'Unknown';\n } else {\n $company = mb_strimwidth($crmData['Company'], 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['Website']) === false) {\n $domain = mb_strimwidth($crmData['Website'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'] ?? '',\n 'company' => $company,\n 'domain' => $domain,\n 'name' => $crmData['Name'] ? mb_strimwidth($crmData['Name'], 0, 191) : '',\n 'title' => $crmData['Title'] ? mb_strimwidth($crmData['Title'], 0, 128) : null,\n 'email' => $crmData['Email'] ? mb_strimwidth($crmData['Email'], 0, 80) : null,\n 'phone' => $parsedNumber['phone'],\n 'ext' => $parsedNumber['ext'] ?? null,\n 'mobile_phone' => $mobilePhone,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Lead::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'stage_id' => $stage->id,\n 'record_type_id' => null,\n 'converted_at' => $convertedDate,\n 'converted_account_id' => $convertedAccount->id ?? null,\n 'converted_opportunity_id' => $convertedOpportunity->id ?? null,\n 'converted_contact_id' => $convertedContact->id ?? null,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->leads(), $crmData['Id']);\n\n /** @var Lead $lead */\n $lead = $this->config->leads()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n if ($lead->wasChanged('converted_at') && $lead->getConvertedAt() !== null) {\n $this->eventDispatcher->dispatch(new LeadConverted($lead));\n }\n\n $this->handleObjectDeletion($lead, $crmData);\n\n return $lead;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('account');\n\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Account\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfAccounts = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfAccounts as $sfAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($sfAccount['Id'])) {\n $this->importAccount($sfAccount);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::ACCOUNT);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n $fields = $this->getAllFieldsAsArray('account');\n if (! in_array('Id', $fields, true)) {\n $this->logger->info('[Salesforce] Sync account cancelled. Fields are not available.', [\n 'crmId' => $crmId,\n 'userId' => $this->profile->getUserId(),\n ]);\n\n return null;\n }\n\n $sfAccount = $this->getRecord('Account', $crmId, $fields);\n\n return $this->importAccount($sfAccount);\n }\n\n private function importAccount($crmData): Account\n {\n $countryCode = $crmData['BillingCountryCode'] ?? $crmData['ShippingCountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country names.\n if ($countryCode === null && empty($crmData['BillingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['BillingCountry']);\n }\n\n if ($countryCode === null && empty($crmData['ShippingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['ShippingCountry']);\n }\n\n if (empty($crmData['Phone']) === false) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($crmData['Phone'], 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n $industry = null;\n if (empty($crmData['Industry']) === false) {\n $industry = mb_strimwidth($crmData['Industry'], 0, 40);\n }\n\n $domain = null;\n if (empty($crmData['Website']) === false) {\n $domain = mb_strimwidth($crmData['Website'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'],\n 'name' => mb_strimwidth($crmData['Name'], 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Account::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'industry' => $industry,\n 'domain' => $domain,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->accounts(), $crmData['Id']);\n\n /** @var Account $account */\n $account = $this->config->accounts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n $this->handleObjectDeletion($account, $crmData);\n\n return $account;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n $logParams = $parameters;\n $parameters['profile'] = $this->profile;\n $logParams['user'] = $this->profile->getUserId();\n\n if (count($strategies) > 1) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Multiple sync strategies used', [\n 'teamId' => $this->team->getUuid(),\n 'params' => $logParams,\n 'strategies_count' => count($strategies),\n ]);\n }\n\n foreach ($strategies as $syncStrategy) {\n $name = $syncStrategy->getStrategyName();\n\n try {\n $sfOpportunities = $syncStrategy->fetchOpportunities($parameters);\n $totalRecords = $sfOpportunities->count();\n\n foreach ($sfOpportunities as $sfOpportunity) {\n $this->importOpportunity($sfOpportunity);\n $syncCount++;\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n $this->logger->warning('[' . $this->getDisplayName() . '] No opportunities found', [\n 'teamId' => $this->team->getUuid(),\n 'name' => $name,\n 'params' => $logParams,\n 'reason' => $noResultsException->getMessage(),\n ]);\n } catch (CrmException $crmException) {\n // Nothing to sync.\n $this->logger->warning('[' . $this->getDisplayName() . '] Opportunity sync failed', [\n 'teamId' => $this->team->getUuid(),\n 'name' => $name,\n 'params' => $logParams,\n 'reason' => $crmException->getMessage(),\n ]);\n }\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::OPPORTUNITY, ['params' => $logParams]);\n\n // debug to see how if count of opportunities reaches 1000\n if ($syncCount >= 1000) {\n $this->logger->info(\n '[' . $this->getDisplayName() . '] Sync Opportunities - count warning',\n [\n 'team_id' => $this->team->getId(),\n 'params' => $logParams,\n 'count' => $syncCount,\n 'strategies_count' => count($strategies),\n 'total_records' => $totalRecords ?? null,\n ]\n );\n }\n\n return $syncCount;\n }\n\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n $parameters = [\n 'profile' => $this->profile,\n 'crm_id' => $crmId,\n ];\n\n try {\n $sfOpportunity = $strategy->fetchOpportunities($parameters);\n } catch (HttpNotFoundException $e) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [\n 'teamId' => $this->team->id_string,\n 'crmId' => $crmId,\n ]);\n\n return null;\n } catch (CrmException $crmException) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity sync failed', [\n 'teamId' => $this->team->id_string,\n 'crmId' => $crmId,\n 'exception' => $crmException->getMessage(),\n ]);\n\n return null;\n }\n\n if ($sfOpportunity instanceof ArrayIterator) {\n return $this->importOpportunity($sfOpportunity->getItems());\n }\n\n return $this->importOpportunity($sfOpportunity);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n /** @var ?Stage $stage */\n $stage = null;\n if (isset($crmData['StageName'])) {\n $stage = $this->config\n ->stages()\n ->where('name', $crmData['StageName'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->orderBy('is_selectable', 'DESC')\n ->orderBy('id')\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['StageName']);\n }\n }\n\n $recordType = null;\n if (empty($crmData['RecordTypeId']) === false) {\n /** @var ?RecordType $recordType */\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $crmData['RecordTypeId'])\n ->first();\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $account = null;\n if (empty($crmData['AccountId']) === false) {\n /** @var ?Account $account */\n $account = $this->config->accounts()\n ->where('crm_provider_id', (string) $crmData['AccountId'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['AccountId']);\n }\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $closeDate = null;\n if (empty($crmData['CloseDate']) === false) {\n $closeDate = Carbon::parse($crmData['CloseDate'])->format('Y-m-d');\n }\n\n $valueFieldName = 'Amount';\n if ($this->config->opportunity_value_field_id) {\n $valueFieldName = $this->config->opportunityValueField->crm_provider_id;\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile?->user_id ?? null,\n 'owner_id' => $crmData['OwnerId'] ?? null,\n 'name' => mb_strimwidth($crmData['Name'] ?? '', 0, 128),\n 'value' => $crmData[$valueFieldName],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['CurrencyIsoCode'] ?? null),\n 'close_date' => $closeDate,\n 'is_closed' => $crmData['IsClosed'],\n 'is_won' => $crmData['IsWon'],\n 'stage_id' => $stage?->id ?? null,\n 'record_type_id' => $recordType->id ?? null,\n 'remotely_created_at' => $createdDate,\n 'probability' => $crmData['Probability'] ?? null,\n 'forecast_category' => $crmData['ForecastCategoryName'] ?? null,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->opportunities(), $crmData['Id']);\n\n // Do not allow locked DB tables & other errors\n // to interrupt the process of reverting the trashed opportunities\n try {\n /** @var Opportunity $opportunity */\n $opportunity = $this->config->opportunities()\n ->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n // import external fields into crm_field_data if present\n $crmFields = $this->getOpportunitySyncableFields();\n\n $this->importOpportunityCrmFieldData($crmData, $crmFields, $opportunity->id);\n\n $this->handleObjectDeletion($opportunity, $crmData);\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n } catch (Exception $exception) {\n Sentry::captureException($exception);\n\n $this->logger->error('[Salesforce] importOpportunity failure.', [\n 'crm_provider_id' => $crmData['Id'],\n 'team_id' => $this->team->id,\n 'exception' => $exception->getMessage(),\n ]);\n\n $this->handleEntityDeletionByProviderId($this->config->opportunities(), $crmData);\n }\n\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $fields = $this->getAllFieldsAsArray('contact');\n if (\\in_array('Id', $fields, true) === false) {\n return $syncCount;\n }\n\n $query = '\n SELECT ' . rtrim(implode(',', $fields), ',') . '\n FROM Contact\n WHERE LastModifiedDate > :since\n ORDER BY LastModifiedDate ASC';\n\n try {\n $sfContacts = $this->queryHandler->query($query, [\n 'since' => $since->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($sfContacts as $sfContact) {\n // Only sync if previously imported.\n if ($this->hasContact($sfContact['Id'])) {\n $this->importContact($sfContact);\n $syncCount++;\n }\n }\n } catch (NoResultsException $noResultsException) {\n // Nothing to sync.\n }\n\n $this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::CONTACT);\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n $fields = $this->getAllFieldsAsArray('contact');\n if (! in_array('Id', $fields, true)) {\n $this->logger->info('[Salesforce] Sync contact cancelled. Fields are not available.', [\n 'crmId' => $crmId,\n 'userId' => $this->profile->getUserId(),\n ]);\n\n return null;\n }\n\n $sfContact = $this->getRecord('Contact', $crmId, $fields);\n\n return $this->importContact($sfContact);\n }\n\n private function importContact($crmData): Contact\n {\n $account = null;\n // Contacts may not have accounts...\n if (isset($crmData['AccountId'])) {\n $account = $this->config->accounts()\n ->where('crm_provider_id', (string) $crmData['AccountId'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['AccountId']);\n }\n }\n\n $countryCode = $crmData['MailingCountryCode'] ?? null;\n\n // Salesforce allows custom \"countries\" to be created. Disregard these.\n if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {\n $countryCode = null;\n }\n\n // If we have no country code, try to parse it from the country name.\n if ($countryCode === null && empty($crmData['MailingCountry']) === false) {\n $countryCode = $this->convertCountryNameToCode($crmData['MailingCountry']);\n\n if ($countryCode === null && $account) {\n $countryCode = $account->country_code;\n }\n }\n\n $ext = null;\n $parsedNumber = [];\n if (empty($crmData['Phone']) === false) {\n $number = Str::limit($crmData['Phone'], 25, '');\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n\n if (empty($parsedNumber['ext']) === false) {\n $ext = Str::limit($parsedNumber['ext'], 10, '');\n }\n }\n\n $mobileNumber = null;\n if (empty($crmData['MobilePhone']) === false) {\n $mobileNumber = Str::limit(phone_e164($countryCode, $crmData['MobilePhone']), 25, '');\n }\n\n $createdDate = null;\n if (empty($crmData['CreatedDate']) === false) {\n $createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');\n }\n\n $profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile?->user_id,\n 'owner_id' => $crmData['OwnerId'] ?? null,\n 'name' => ($crmData['Name'] ?? null) !== null ? mb_strimwidth($crmData['Name'], 0, 100) : '',\n 'title' => ($crmData['Title'] ?? null) !== null ? mb_strimwidth($crmData['Title'], 0, 128) : null,\n 'email' => ($crmData['Email'] ?? null) !== null ? mb_strimwidth($crmData['Email'], 0, 191) : null,\n 'country_code' => $countryCode,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $ext,\n 'mobile_phone' => $mobileNumber,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['Id'],\n modelType: Contact::class,\n fileName: $crmData['Id'],\n avatarText: $crmData['Name']\n ),\n 'remotely_created_at' => $createdDate,\n ];\n\n $this->restoreAnyTrashedEntity($this->config->contacts(), $crmData['Id']);\n\n /** @var Contact $contact */\n $contact = $this->config->contacts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);\n\n $this->handleObjectDeletion($contact, $crmData);\n\n return $contact;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n $fields = [\n 'InstanceName',\n 'OrganizationType',\n 'IsSandbox',\n ];\n\n $orgValues = $this->getRecord('Organization', $this->config->crm_provider_id, $fields);\n\n $edition = null;\n switch ($orgValues['OrganizationType']) {\n case 'Developer Edition':\n $edition = Configuration::EDITION_DEVELOPER;\n\n break;\n\n case 'Professional Edition':\n $edition = Configuration::EDITION_PROFESSIONAL;\n\n break;\n\n case 'Enterprise Edition':\n $edition = Configuration::EDITION_ENTERPRISE;\n\n break;\n }\n\n $this->config->edition = $edition;\n $this->config->instance = $orgValues['InstanceName'];\n\n // XXX: How can this state be possible?\n if ($this->config->version === null) {\n $this->config->version = Client::MIN_API_VERSION;\n }\n\n $installedVersion = $this->getInstalledAppVersion();\n if ($installedVersion !== null) {\n $installedVersion = (string) $this->getInstalledAppVersion();\n }\n\n $this->config->installed_app_version = $installedVersion;\n\n $this->config->save();\n }\n\n public function getInstalledAppVersion(): ?string\n {\n try {\n $query = '\n SELECT\n SubscriberPackageVersion.MajorVersion,\n SubscriberPackageVersion.MinorVersion,\n SubscriberPackageVersion.PatchVersion,\n SubscriberPackageVersion.BuildNumber\n FROM\n InstalledSubscriberPackage\n WHERE\n SubscriberPackageId = :packageId\n ';\n\n $sfFields = $this->queryHandler->metadata($query, [\n 'packageId' => self::INSTALLED_PACKAGE_ID,\n ]);\n\n // There is always 1 result at this point.\n $sfField = $sfFields->current();\n\n // Grab version number.\n $version = $sfField['SubscriberPackageVersion']['MajorVersion'] .\n $sfField['SubscriberPackageVersion']['MinorVersion'] .\n $sfField['SubscriberPackageVersion']['PatchVersion'] .\n $sfField['SubscriberPackageVersion']['BuildNumber'];\n } catch (\\Exception) {\n $version = null;\n }\n\n return $version;\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws \\Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // For SF we also check if Log Notes is enabled.\n if ($this->profile->log_notes === Profile::LOG_NOTE_NONE) {\n return;\n }\n\n if ($activity->opportunity_id && $activity->prospect === null) {\n return;\n }\n\n try {\n $transcriptionData = $this->generateTranscription($activity);\n\n $noteMaxLength = $this->profile->log_notes === Profile::LOG_NOTE_ENHANCED\n ? self::ENHANCED_NOTE_MAX_LENGTH\n : self::CLASSIC_NOTE_MAX_LENGTH;\n\n $title = 'Transcript for ';\n $title .= $activity->title ?? $activity->activity_title;\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $body = mb_strimwidth($transcriptionData, 0, $noteMaxLength);\n\n if ($activity->opportunity_id) {\n $objectId = $activity->opportunity->crm_provider_id;\n } else {\n $objectId = $activity->prospect->crm_provider_id;\n }\n\n $noteId = $this->saveNote($title, $body, $objectId);\n\n // Store crm logged id in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $noteId;\n $transcription->save();\n } catch (\\Exception $e) {\n \\Sentry::captureException($e);\n }\n }\n\n public function saveNote(string $title, string $body, string $objectId, ?NoteObject $noteObject = null): ?string\n {\n $noteId = null;\n\n try {\n if ($this->profile->log_notes === Profile::LOG_NOTE_ENHANCED) {\n $noteId = $this->buildEnhancedNote($title, $body, $objectId);\n } else {\n $noteId = $this->buildClassicNote($title, $body, $objectId);\n }\n } catch (HttpNotFoundException $exception) {\n // The profile not having access to create Enhanced Notes. Set their preference to Classic.\n if ($this->profile->log_notes === Profile::LOG_NOTE_ENHANCED) {\n $this->profile->update([\n 'log_notes' => Profile::LOG_NOTE_CLASSIC,\n ]);\n }\n }\n\n return $noteId;\n }\n\n /**\n * This is using the \"Enhanced\" Notes feature, NOT the \"Notes & Attachments\" feature being deprecated.\n *\n * @url https://salesforce.stackexchange.com/questions/104408/how-can-i-create-an-account-note-or-contact-note-via-api-that-is-visible-in-sale\n */\n private function buildEnhancedNote(string $title, string $body, string $objectId): string\n {\n // Decode stored entities, escape HTML (without quoting), then convert line breaks for Salesforce formatting\n $decodedBody = html_entity_decode($body, ENT_QUOTES | ENT_HTML5);\n $sanitizedBody = htmlspecialchars($decodedBody, ENT_NOQUOTES, 'UTF-8', false);\n $content = nl2br($sanitizedBody, false);\n $note = [\n 'OwnerId' => $this->profile->crm_provider_id,\n 'Title' => $title,\n 'Content' => base64_encode($content),\n ];\n\n $noteId = $this->createRecord('ContentNote', $note);\n\n $link = [\n 'ContentDocumentId' => $noteId,\n 'LinkedEntityId' => $objectId,\n 'ShareType' => 'I',\n ];\n\n $this->createRecord('ContentDocumentLink', $link);\n\n return $noteId;\n }\n\n private function buildClassicNote(string $title, string $body, string $objectId): string\n {\n if (in_array($this->parseObjectType($objectId), [Field::OBJECT_TASK, Field::OBJECT_EVENT])) {\n $this->logger->info('[Salesforce] Summary not sent', [\n 'profile_id' => $this->profile->id,\n 'objectId' => $objectId,\n 'reason' => 'Classical Note does not support Task/Event relation',\n ]);\n\n return '';\n }\n\n $titleTrimmed = null;\n\n if (mb_strlen($title) > 80) {\n $titleTrimmed = substr($title, 0, 77) . '...';\n }\n $payload = [\n 'OwnerId' => $this->profile->crm_provider_id,\n 'IsPrivate' => false,\n 'Title' => $titleTrimmed ?? $title,\n 'Body' => $titleTrimmed ? $title . PHP_EOL . $body : $body,\n 'ParentId' => $objectId,\n ];\n\n return $this->createRecord('Note', $payload);\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n if ($this->profile === null) {\n return [];\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $limitValues = ['limit' => $this->limit, 'offset' => $this->offset];\n $sosl = $queryBuilder->buildFindQuery($name, $scopes, $limitValues);\n\n $this->logger->info('[Salesforce] Find prospects', [\n 'profile_id' => $this->profile->id,\n 'sosl_query' => $sosl,\n 'search_string' => $name,\n 'scopes' => $scopes,\n ]);\n\n $data = Cache::remember($this->profile->id . $sosl, self::CACHE_TTL, function () use ($sosl) {\n $data = [];\n\n try {\n // Hit remote API.\n $objects = $this->queryHandler->search($sosl);\n\n // Build mapped list.\n foreach ($objects as $object) {\n $type = strtolower($object['attributes']['type']);\n\n $record = [\n 'crmId' => $object['Id'],\n 'name' => $object['Name'],\n 'prospectType' => $type,\n 'phoneNumbers' => [],\n 'crmUrl' => $this->generateProviderUrl($object['Id'], $type),\n ];\n\n switch ($type) {\n case 'lead':\n if (empty($object['Company']) === false) {\n $record['organization'] = $object['Company'];\n }\n\n if (empty($object['Title']) === false) {\n $record['title'] = $object['Title'];\n }\n\n $stage = $this->config->stages()\n ->where('type', Stage::TYPE_LEAD)\n ->where('name', $object['Status'])\n ->first();\n\n // Lazy create the stage.\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_LEAD], $object['Status']);\n }\n\n if ($stage) {\n $record += [\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n ];\n }\n\n if (empty($object['RecordTypeId']) === false) {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $object['RecordTypeId'])\n ->first();\n\n if ($recordType) {\n $record += [\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n }\n }\n\n break;\n\n case 'account':\n if (empty($object['Industry']) === false) {\n $record['industry'] = $object['Industry'];\n $record['detailsLine'] = $object['Industry'];\n }\n if (! empty($object['PersonEmail'])) {\n $record['detailsLine'] = $object['PersonEmail'];\n }\n\n break;\n\n case 'contact':\n // For contacts, we should try and fetch their account name too.\n if ($object['AccountId']) {\n // Cheaper to get this locally.\n $account = $this->config->accounts()\n ->where('crm_provider_id', $object['AccountId'])\n ->first(['name']);\n\n if ($account) {\n $record['organization'] = $account->name;\n }\n }\n\n if (! empty($object['IsPersonAccount']) && $object['Email']) {\n $record['detailsLine'] = $object['Email'];\n } else {\n if (empty($object['Title']) === false) {\n $record['title'] = $object['Title'];\n }\n }\n\n break;\n }\n\n // Add phone numbers to record.\n if (empty($object['Phone']) === false && $object['Phone']) {\n $record['phoneNumbers'][] = [\n 'number' => $object['Phone'],\n 'nationalFormat' => phone_national($this->profile->user->country_code, $object['Phone']),\n 'type' => 'phone',\n ];\n }\n\n if (empty($object['MobilePhone']) === false && $object['MobilePhone']) {\n $record['phoneNumbers'][] = [\n 'number' => $object['MobilePhone'],\n 'nationalFormat' => phone_national(\n $this->profile->user->country_code,\n $object['MobilePhone']\n ),\n 'type' => 'mobile',\n ];\n }\n\n $data[] = $record;\n }\n } catch (NoResultsException $e) {\n $data = [];\n }\n\n return $data;\n });\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n\n if ($crmAccountId === null) {\n return $data;\n }\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n try {\n // Perhaps their profile has no opportunity permissions.\n if ($this->profile === null || $this->profile->opportunity_fields === null) {\n return $data;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildFindOpportunitiesQuery();\n\n $objects = $this->queryHandler->query($query, ['accountId' => $crmAccountId]);\n\n foreach ($objects as $object) {\n $record = [\n 'crmId' => $object['Id'],\n 'name' => $object['Name'],\n 'won' => $object['IsWon'],\n 'closed' => $object['IsClosed'],\n ];\n\n $valueFieldName = 'Amount';\n if ($this->config->opportunity_value_field_id) {\n $valueFieldName = $this->config->opportunityValueField->crm_provider_id;\n }\n\n if (empty($object[$valueFieldName]) === false) {\n $currency = $object['CurrencyIsoCode'] ?? $this->config->default_currency;\n $value = formatCurrency($object[$valueFieldName], $currency);\n\n $record += [\n 'value' => $value,\n ];\n }\n\n $stage = $this->config->stages()\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->where('name', $object['StageName'])\n ->first();\n\n // Lazy create the stage.\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $object['StageName']);\n }\n\n $record += [\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n ];\n\n if (empty($object['RecordTypeId']) === false) {\n $recordType = $this->config->recordTypes()\n ->where('crm_provider_id', $object['RecordTypeId'])\n ->first();\n\n if ($recordType) {\n $record += [\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n }\n }\n\n if ($ownerId && isset($object['OwnerId']) && $object['OwnerId'] === $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n } catch (NoResultsException $e) {\n return $data;\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n public function getContactRolesFromCrm(?Carbon $since = null): array\n {\n $roles = [];\n\n if ($this->profile === null) {\n return $roles;\n }\n\n $queryBuilder = app(QueryBuilder::class, ['profile' => $this->profile]);\n\n $query = $queryBuilder->buildGetContactRolesQuery($since);\n\n try {\n $objects = $this->queryHandler->query($query);\n\n foreach ($objects as $object) {\n $roles[] = [\n 'id' => $object['Id'],\n 'contactId' => $object['ContactId'],\n 'opportunityId' => $object['OpportunityId'],\n 'ownerId' => $object['Opportunity']['OwnerId'] ?? null,\n 'isPrimary' => $object['IsPrimary'],\n 'role' => $object['Role'],\n ];\n }\n } catch (NoResultsException) {\n // Just return an empty array.\n $this->logger->info('[Salesforce] No contact roles found', [\n 'since' => $since?->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n }\n\n return $roles;\n }\n\n public function syncContactRoles(Carbon $since): int\n {\n $contactRoleRepository = app(ContactRoleRepository::class);\n\n $crmContactRoles = $this->getContactRolesFromCrm(since: $since);\n $syncCount = 0;\n $contactRoles = [];\n\n foreach ($crmContactRoles as $crmContactRole) {\n $contactRoles[] = $this->importContactRole($crmContactRole);\n $syncCount++;\n }\n\n $contactRoleRepository->saveContactRoles($contactRoles);\n\n $this->syncRemotelyDeletedContactRoles();\n\n return $syncCount;\n }\n\n private function importContactRole(array $contactRole): array\n {\n $contact = $this->config->contacts()\n ->where('crm_provider_id', $contactRole['contactId'])\n ->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($contactRole['contactId']);\n }\n\n $opportunity = $this->config->opportunities()\n ->where('crm_provider_id', $contactRole['opportunityId'])\n ->first();\n\n if ($opportunity === null) {\n $opportunity = $this->syncOpportunity($contactRole['opportunityId']);\n }\n\n $role = null;\n if (! empty($contactRole['role'])) {\n $role = mb_strimwidth($contactRole['role'], 0, 191);\n }\n\n return [\n 'crm_configuration_id' => $this->config->getId(),\n 'contact_id' => $contact->getId(),\n 'crm_provider_id' => $contactRole['id'],\n 'subject_type' => ContactRole::SUBJECT_TYPE_OPPORTUNITY,\n 'subject_id' => $opportunity->getId(),\n 'is_primary' => $contactRole['isPrimary'],\n 'role' => $role,\n ];\n }\n\n protected function syncRemotelyDeletedContactRoles(): bool\n {\n try {\n $deletedRemotely = $this->queryHandler->queryDeleted('OpportunityContactRole');\n } catch (NoResultsException $e) {\n return false;\n }\n\n $deletedOpportunities = $deletedRemotely->getResults();\n $deletedIds = array_column($deletedOpportunities, 'id');\n\n $contactRoleRepository = app(ContactRoleRepository::class);\n\n foreach (array_chunk($deletedIds, self::HARD_DELETE_CHUNK) as $chunk) {\n $contactRoleRepository->deleteContactRoles($chunk);\n\n $this->logger->info('[' . $this->getDisplayName() . '] Remotely deleted opportunities synced', [\n 'teamId' => $this->team->id_string,\n 'remotelyDeletedOpportunities' => $chunk,\n 'count' => count($chunk),\n ]);\n }\n\n return true;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $objects = [];\n\n $hasWho = \\in_array($objectType, ['lead', 'contact']);\n $playbook = $this->getPlaybook($this->profile->user);\n $fields = array_merge(\n $this->profile->getFieldsAsArray(parent::OBJECT_TASK),\n $playbook && $playbook->activityField ? [$playbook->activityField->crm_provider_id] : []\n );\n\n // Query should default to any open call for that user.\n $query = '\n SELECT ' . implode(',', array_unique($fields)) . '\n FROM Task\n WHERE OwnerId = :ownerId\n AND IsArchived = false\n AND IsDeleted = false\n AND IsClosed = false\n AND (';\n\n if ($objectType === 'account') {\n // This covers tasks tied to a related contact or opportunity too.\n $query .= '\n AccountId = :accountId';\n }\n\n if ($hasWho) {\n $query .= '\n WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($opportunityId) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ' ) ORDER BY LastModifiedDate DESC';\n\n try {\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $this->profile->crm_provider_id,\n 'whoId' => $objectId,\n 'whatId' => $opportunityId,\n 'accountId' => $objectId,\n ]);\n } catch (NoResultsException $e) {\n return $data;\n } finally {\n $this->logger->debug(sprintf('[Salesforce] Found %s tasks for query \"%s\"', count($objects), $query));\n }\n\n foreach ($objects as $object) {\n $dueDate = $object['ActivityDate'] ? Carbon::parse($object['ActivityDate'])->toIso8601String() : null;\n $data[] = [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'due' => $dueDate,\n 'type' => $object[$playbook->activityField->crm_provider_id],\n ];\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getEvents(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $objects = [];\n $user = $this->profile?->user;\n if ($this->profile === null || $user === null) {\n return $data;\n }\n\n $hasWho = \\in_array($objectType, ['lead', 'contact']);\n $playbook = $this->getPlaybook($user);\n $fields = array_merge(\n $this->profile->getFieldsAsArray(parent::OBJECT_EVENT),\n $playbook && $playbook->activityField ? [$playbook->activityField->crm_provider_id] : []\n );\n\n // Query should default to any event starting in the last week and ending up until today owned by the user.\n $query = '\n SELECT ' . implode(',', array_unique($fields)) . '\n FROM Event\n WHERE OwnerId = :ownerId\n AND IsArchived = false\n AND IsAllDayEvent = false\n AND StartDateTime >= LAST_N_DAYS:7\n AND EndDateTime <= TODAY\n AND (';\n\n if ($objectType === 'account') {\n // This covers events tied to a related contact or opportunity too.\n $query .= '\n AccountId = :accountId';\n }\n\n if ($hasWho) {\n $query .= '\n WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($opportunityId) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ' ) ORDER BY LastModifiedDate DESC';\n\n try {\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $this->profile->crm_provider_id,\n 'whoId' => $objectId,\n 'whatId' => $opportunityId,\n 'accountId' => $objectId,\n ]);\n } catch (NoResultsException $e) {\n return $data;\n } finally {\n $this->logger->debug(sprintf('[Salesforce] Found %s tasks for query \"%s\"', count($objects), $query));\n }\n\n foreach ($objects as $object) {\n $dueDate = $object['StartDateTime'] ? Carbon::parse($object['StartDateTime'])->toIso8601String() : null;\n\n $data[] = [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'due' => $dueDate,\n 'type' => $object[$playbook->activityField->crm_provider_id],\n ];\n }\n\n return $data;\n }\n\n /**\n * Try to find CRM Objects using email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByQuery($email, Field::TYPE_EMAIL);\n if ($sosl === null) {\n return null;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $email,\n QueryHandler::PRIORITISE_EMAIL\n );\n\n $data = $this->convertCrmData($objects, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n } catch (NoResultsException $e) {\n // Try the account next.\n if ($this->profile->account_fields === null) {\n return null;\n }\n }\n\n return null;\n }\n\n public function getDomain(string $email): ?string\n {\n // SF improved search - strip the domain extension, min domain name length 4\n return $this->getCompanyNameFromEmail(email: $email, minNameLength: 4);\n }\n\n /**\n * Try to find CRM objects using domain name of the email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByDomain(string $domain, ?int $userId = null): ?array\n {\n $companyName = $domain;\n\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByDomainQuery($companyName);\n\n try {\n $objects = $this->queryHandler->search($sosl);\n\n $data = $this->convertCrmData($objects, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n } catch (NoResultsException) {\n return null;\n }\n }\n\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Don't bother looking up numbers that are masked.\n if (str_contains($phone, '**')) {\n return null;\n }\n\n if ($this->isPhoneNumberOfTeamMember($phone)) {\n return null;\n }\n\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $phoneNational = phone_national(null, $phone) ?? '';\n $possiblePhoneFormats = collect([\n preg_replace('/\\D/', '', ltrim($phone, '0+')),\n preg_replace('/\\D/', '', $phoneNational),\n formatDashPhoneNumber($phone),\n $phoneNational,\n ])\n ->filter() // Removes null and empty strings\n ->unique()\n ->values();\n\n foreach ($possiblePhoneFormats as $phone) {\n $sosl = $queryBuilder->buildMatchByQuery($phone, Field::TYPE_PHONE);\n if ($sosl === null) {\n continue;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $phone,\n QueryHandler::PRIORITISE_PHONE\n );\n\n return $this->convertCrmData($objects, $userId);\n } catch (NoResultsException) {\n continue;\n }\n }\n\n return null;\n }\n\n private function isPhoneNumberOfTeamMember(string $phone): bool\n {\n $teamRepository = app(TeamRepository::class);\n $user = $teamRepository->findTeamMemberByPhone($this->team, $phone);\n\n if ($user instanceof User) {\n return true;\n }\n\n return false;\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->profile->id . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n /** Determine the CRM Objects which represent the call activity. */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n if ($this->profile === null) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $sosl = $queryBuilder->buildMatchByQuery($name, 'name');\n if ($sosl === null) {\n return false;\n }\n\n try {\n $objects = $this->queryHandler->search($sosl);\n } catch (NoResultsException $e) {\n return false;\n }\n\n $objects = $this->queryHandler->prioritiseResults(\n $objects,\n $name,\n QueryHandler::PRIORITISE_NAME\n );\n\n $data = $this->convertCrmData($objects, $userId);\n\n return (! empty(array_filter($data))) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n /**\n * @return array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n protected function convertCrmData(QueryIterator $objects, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n if ($objects->count() > 0) {\n $object = $objects->current();\n\n if ($object['attributes']['type'] === 'Lead') {\n $lead = $this->importLead($object);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } else {\n if ($object['attributes']['type'] === 'Contact') {\n $contact = $this->importContact($object);\n $account = $contact->account;\n } else {\n $account = $this->importAccount($object);\n }\n\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $sfOpportunities = $this->findOpportunities(\n $account?->getCrmProviderId(),\n $contact?->getCrmProviderId(),\n $userId\n );\n\n // Take the first opportunity, which will be ordered as priority based on their settings.\n if (! empty($sfOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($sfOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n } catch (Exception) {\n // Nothing to see here.\n }\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n if ($stage->type === Stage::TYPE_LEAD) {\n $objectType = 'Lead';\n $objectId = $crmObject->crm_provider_id;\n $objectStageType = 'Status';\n } else {\n $objectType = 'Opportunity';\n $objectId = $crmObject->crm_provider_id;\n $objectStageType = 'StageName';\n }\n\n $headers = [];\n if ($this->config->trigger_assignment_rules === false) {\n // @see: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers_autoassign.htm\n $headers = [\n 'Sforce-Auto-Assign' => 'false',\n ];\n }\n\n $this->updateRecord($objectType, $objectId, [$objectStageType => $stage->name], $headers);\n }\n\n public function parseObjectType(string $objectId): string\n {\n if (Str::startsWith($objectId, '001')) {\n return 'account';\n }\n\n if (Str::startsWith($objectId, '003')) {\n return 'contact';\n }\n\n if (Str::startsWith($objectId, '00Q')) {\n return 'lead';\n }\n\n if (Str::startsWith($objectId, '006')) {\n return 'opportunity';\n }\n\n if (Str::startsWith($objectId, '00U')) {\n return 'event';\n }\n\n if (Str::startsWith($objectId, '00T')) {\n return 'task';\n }\n\n throw new \\InvalidArgumentException('Unsupported Object Type');\n }\n\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, ['profile' => $this->profile]);\n $query = $queryBuilder->buildGetUsersQuery($userToSearch);\n\n try {\n $salesforceUsers = $this->queryHandler->query($query, [\n 'active' => true,\n ]);\n } catch (NoResultsException $e) {\n $this->logger->info('[Salesforce] Sync Profiles. No users found', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n $teamRepository = app(TeamRepository::class);\n $customRules = $this->getCustomProfileRules($teamRepository);\n\n foreach ($salesforceUsers as $crmUser) {\n if ($crmUser['Email'] === null) {\n continue;\n }\n\n if (! $this->customProfileValidation($crmUser, $customRules)) {\n continue;\n }\n\n $user = $teamRepository->findActiveTeamMemberByEmail($this->team, $crmUser['Email']);\n\n if (! $user instanceof User) {\n continue;\n }\n\n $edition = $crmUser['UserPreferencesLightningExperiencePreferred']\n ? Profile::EDITION_LIGHTNING\n : Profile::EDITION_CLASSIC;\n\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->updateOrCreateProfile(\n $user,\n [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmUser['Id'],\n ],\n [\n 'user_id' => $user->getId(),\n 'edition' => $edition,\n 'has_external_cti' => ! empty($crmUser['CallCenterId']),\n 'crm_profile_id' => $crmUser['ProfileId'],\n ]\n );\n\n if ($userToSearch instanceof User && $userToSearch->getId() === $user->getId()) {\n return $profile;\n }\n }\n\n // Clean up inactive profiles\n try {\n $this->archiveInactiveProfiles();\n } catch (\\Exception $e) {\n $this->logger->warning('[Salesforce] Profile archiving failed', [\n 'teamId' => $this->team->getUuid(),\n 'reason' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $url = null;\n\n // For Salesforce it's easy, we just point every object to the apex domain and they handle it.\n switch ($objectType) {\n case 'lead':\n case 'account':\n case 'contact':\n case 'opportunity':\n case 'task':\n case 'event':\n case 'activity':\n\n $url = $this->config->crm_base_url . '/' . $providerId;\n\n break;\n }\n\n return $url;\n }\n\n public function buildTaskSearchFields(): array\n {\n return ['Id', 'WhoId', 'WhatId', 'AccountId'];\n }\n\n public function getTaskByFilterConditions(\n array $fields,\n array $filters,\n bool $bulkSearch = false,\n bool $strictFilters = true\n ): ?array {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildSearchTaskQuery($fields, $filters, $bulkSearch, $strictFilters);\n\n try {\n if (! $bulkSearch) {\n $objects = $this->queryHandler->query($query, $filters);\n if ($objects->count() === 1) {\n return $objects->current();\n }\n }\n\n if ($bulkSearch) {\n $objects = $this->queryHandler->query($query);\n $records = [];\n foreach ($objects as $record) {\n $key = $record[end($fields)];\n $records[$key] = $record;\n }\n\n return $records;\n }\n } catch (\\Exception $e) {\n $this->logger->info('[Salesforce] Failed to execute query', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n public function mapCrmObjects(array $task): array\n {\n $activityData = [];\n\n if (! empty($task['WhoId'])) {\n $type = $this->parseObjectType($task['WhoId']);\n $activityData[$type] = $task['WhoId'];\n }\n if (! empty($task['AccountId'])) {\n $activityData['account'] = $task['AccountId'];\n }\n if (! empty($task['WhatId'])) {\n $activityData['opportunity'] = $task['WhatId'];\n }\n\n return $activityData;\n }\n\n /**\n * Get SF task by Outreach call id.\n */\n public function getTaskByFilter(\n string $activityFieldType,\n array $filters,\n string $operator = '=',\n array $additionalFields = []\n ): ?array {\n $data = [];\n\n try {\n // Default (base) fields.\n $fields = ['Id', 'Subject', 'Description', 'ActivityDate', 'WhoId', 'WhatId', $activityFieldType];\n\n foreach ($additionalFields as $additionalField) {\n $fields[] = $additionalField->crm_provider_id;\n }\n\n $fields = array_unique($fields);\n\n // Find task with the same Outreach id as the call id.\n $query = 'SELECT ' . implode(',', $fields) . '\n FROM Task\n WHERE IsArchived = false AND IsDeleted = false';\n\n foreach ($filters as $key => $value) {\n $key = preg_quote($key, '/');\n $key = str_replace(['\\'', '\"'], '', $key);\n // Prepare the substitution.\n $strKey = \":$key\";\n\n $query .= \" AND $key $operator $strKey\";\n }\n\n $query .= ' ORDER BY LastModifiedDate DESC LIMIT 1';\n\n $objects = $this->queryHandler->query($query, $filters);\n\n // There should be only one task related to this call if any.\n if ($objects->count() === 1) {\n $object = $objects->current();\n\n $dueDate = $object['ActivityDate'] ? Carbon::parse($object['ActivityDate'])->toIso8601String() : null;\n\n $data = array_merge($object, [\n 'crmId' => $object['Id'],\n 'subject' => $object['Subject'],\n 'summary' => $object['Description'],\n 'due' => $dueDate,\n 'Type' => $object[$activityFieldType],\n ]);\n }\n } catch (NoResultsException $e) {\n // Filters don't match any records.\n } catch (ServiceUnavailableException $serviceUnavailableException) {\n // Service cannot be queried. We should probably log this.\n }\n\n return $data;\n }\n\n /**\n * Get Salesforce fields including datetime fields\n *\n * @param $objectType\n */\n private function getAllFieldsAsArray($objectType): array\n {\n $basicFields = [];\n // Not all users have access to all object fields.\n if ($this->profile->{$objectType . '_fields'}) {\n $basicFields = explode(',', $this->profile->{$objectType . '_fields'});\n }\n\n $extraFields = [\n 'CreatedDate',\n 'LastModifiedDate',\n 'IsDeleted',\n ];\n\n if ($objectType === self::OBJECT_OPPORTUNITY\n && $this->config->opportunity_value_field_id\n && ! in_array($this->config->opportunityValueField->crm_provider_id, $basicFields)\n ) {\n $extraFields[] = $this->config->opportunityValueField->crm_provider_id;\n }\n\n return array_unique(array_merge($basicFields, $extraFields));\n }\n\n /**\n * Generate transcription for activity description.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! ($this->config->store_transcript)) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n return $this->transcriptionService\n ->findTranscriptionByActivity($activity)\n ->map(static function (array $transcriptionSegment): string {\n return $transcriptionSegment['formattedStartsAt'] . ' | ' . $transcriptionSegment['transcript'];\n })\n ->implode(PHP_EOL);\n }\n\n /**\n * Find related Salesforce event based on activity data\n *\n * @return array<string>\n */\n public function fetchRelatedActivity(Activity $activity): array\n {\n $this->logger->info('[Salesforce] Searching for related activity', [\n 'activityId' => $activity->getUuid(),\n 'ownerId' => $this->profile?->crm_provider_id,\n ]);\n\n $sfEvent = $this->fetchRelatedEvent($activity);\n if (empty($sfEvent)) {\n $this->logger->info('[Salesforce] No related activity found', [\n 'activityId' => $activity->getUuid(),\n 'ownerId' => $this->profile?->crm_provider_id,\n 'account' => $activity->hasAccount()\n ? $activity->getAccount()->getCrmProviderId()\n : null,\n ]);\n\n return [];\n }\n\n return $sfEvent;\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n if ($activity->isTypeConference() === false) {\n return null;\n }\n\n if ($activity->hasActualStartTime() === false && $activity->hasScheduledStartTime() === false) {\n return null;\n }\n\n if (! $activity->hasProspect()) {\n $this->logger->info('[Salesforce] Skip look up, Activity not linked to Lead, Contact or Account', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $playbook = $this->getPlaybook($activity->getUser());\n if ($playbook !== null && $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_TASK) {\n $this->logger->info('[Salesforce] Skip auto-sync for task-based playbook', [\n 'activityUuid' => $activity->getUuid(),\n 'playbookId' => $playbook->getId(),\n 'playbookType' => $playbook->getActivityType(),\n ]);\n\n return null;\n }\n\n try {\n $sfEvent = $this->fetchRelatedActivity($activity);\n if (empty($sfEvent)) {\n return null;\n }\n\n [$activityField, $activityType] = $this->resolveActivityTypeFromEvent($activity, $sfEvent);\n\n $this->logger->info('[Salesforce] Found related activity', [\n 'activityId' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n 'activityFieldName' => $activityField,\n 'crmActivityType' => ($activityField !== null && isset($sfEvent[$activityField]))\n ? $sfEvent[$activityField]\n : null,\n 'activityType' => $activityType,\n ]);\n\n $userId = $this->findRelatedActivityUserId($activity, $sfEvent);\n\n if ($activity->getUserId() !== $userId) {\n $this->logger->info('[Salesforce] Updating meeting owner', [\n 'activityId' => $activity->getUuid(),\n 'oldUserId' => $activity->getUserId(),\n 'newUserId' => $userId,\n ]);\n }\n\n $this->updateSfEventDescription($activity, $sfEvent);\n\n $activity->update([\n 'user_id' => $userId,\n 'crm_provider_id' => $sfEvent['Id'],\n 'playbook_category_id' => $activityType->id ?? $activity->getCategory()?->getId(),\n ]);\n\n $this->logger->info('[Salesforce] Activity updated', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return $activity;\n } catch (\\Exception $exception) {\n \\Sentry::captureException($exception);\n\n throw $exception;\n }\n }\n\n /**\n * @param array<string, mixed> $sfEvent\n *\n * @return array{0: string|null, 1: mixed}\n */\n private function resolveActivityTypeFromEvent(Activity $activity, array $sfEvent): array\n {\n $activityField = $this->getActivityFieldName($activity);\n $activityType = null;\n\n if ($activityField !== null && ! empty($sfEvent[$activityField])) {\n $playbook = $this->getPlaybook($activity->getUser());\n $activityType = $this->getPlaybookCategory($playbook, strval($sfEvent[$activityField]));\n }\n\n return [$activityField, $activityType];\n }\n\n /**\n * @param array<string> $sfEvent\n */\n private function findRelatedActivityUserId(Activity $activity, array $sfEvent): int\n {\n $userId = $activity->getUserId();\n\n if (empty($sfEvent['OwnerId']) === false) {\n $profile = $this\n ->config\n ->profiles()\n ->where('crm_provider_id', $sfEvent['OwnerId'])\n ->get()\n ->filter(static function (Profile $profile) use ($activity): bool {\n if (! $activity->isTypeConference()) {\n return ! empty($profile->user) ? $profile->user->isStatusActive() : false;\n }\n\n $participants = $activity->getParticipants();\n\n return ! empty($profile->user)\n ? $profile->user->isStatusActive()\n && $profile->user->hasPermission(PermissionEnum::RECORD_MEETING)\n && $participants->contains('user_id', $profile->user_id)\n : false;\n })\n ->first();\n\n if ($profile) {\n $userId = $profile->user_id;\n }\n }\n\n return $userId;\n }\n\n /**\n * @param array<string, mixed> $sfEvent\n */\n private function updateSfEventDescription(Activity $activity, array $sfEvent): void\n {\n try {\n if (str_contains($sfEvent['Description'], $activity->id_string)) {\n return;\n }\n\n $payload = [\n 'Description' => $sfEvent['Description']\n . PHP_EOL\n . PHP_EOL\n . (new DecorateActivity())->generateDescription($activity),\n ];\n\n $this->logger->info('[Salesforce] Update record', [\n 'activityId' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n 'payload' => $payload,\n ]);\n\n $payload = array_merge(\n $payload,\n $this->payloadBuilder->fetchCustomFieldData($activity, Field::OBJECT_EVENT)\n );\n\n $this->updateRecord('Event', $sfEvent['Id'], $payload);\n } catch (\\Exception) {\n $this->logger->error('[Salesforce] Failed to update record', [\n 'activityUuid' => $activity->getUuid(),\n 'sfEvent' => $sfEvent['Id'],\n ]);\n }\n }\n\n /**\n * Returns the most recently modified Event within time range (if any).\n *\n * @return array|null An Event record from Salesforce.\n */\n private function fetchRelatedEvent(Activity $activity): ?array\n {\n $ownerId = $this->profile?->crm_provider_id;\n if ($ownerId === null) {\n return [];\n }\n\n /** @var ?Carbon $from */\n /** @var ?Carbon $to */\n [$from, $to] = $this->getFromToDates($activity);\n\n try {\n $whoId = null;\n $hasWho = $activity->lead_id || $activity->contact_id;\n if ($hasWho) {\n $whoId = $activity->hasLead()\n ? $activity->getLead()->crm_provider_id\n : $activity->getContact()->crm_provider_id;\n }\n\n if ($hasWho === false && $activity->account_id === null) {\n return null;\n }\n\n $query = $this->buildFetchRelatedEventQuery($activity);\n\n $objects = $this->queryHandler->query($query, [\n 'ownerId' => $ownerId,\n 'whoId' => $whoId,\n 'whatId' => $activity->hasOpportunity() ? $activity->getOpportunity()->crm_provider_id : null,\n 'accountId' => $activity->hasAccount() ? $activity->getAccount()->crm_provider_id : null,\n 'from' => $from?->format('Y-m-d\\TH:i:s\\Z'),\n 'to' => $to?->format('Y-m-d\\TH:i:s\\Z'),\n ]);\n\n foreach ($objects as $object) {\n return $object;\n }\n } catch (NoResultsException $e) {\n return [];\n }\n\n return [];\n }\n\n private function getFromToDates(Activity $activity): array\n {\n $from = null;\n $to = null;\n\n /** @var ?CalendarEvent $calendarEvent */\n $calendarEvent = $activity->calendarEvent()->first();\n if ($calendarEvent !== null) {\n $from = $calendarEvent->getStartTime();\n $to = $calendarEvent->getEndTime();\n }\n\n // For non-calendar imported activities\n // Also double check if calendar event dates could be null?\n // If null use what we've got so far\n if ($from === null || $to === null) {\n $from = $activity->hasScheduledStartTime()\n ? $activity->getScheduledStartTime()\n : $activity->getActualStartTime();\n $to = $activity->hasScheduledEndTime()\n ? $activity->getScheduledEndTime()->addMinutes(15)\n : $activity->getActualEndTime();\n }\n\n return [$from, $to];\n }\n\n /**\n * Determines the appropriate activity field name for querying Salesforce events.\n *\n * This method follows a hierarchy to determine the field name:\n * 1. Uses the playbook's activity field if it exists and is in the profile's accessible fields\n * 2. Falls back to the default activity field if the profile has no event fields configured\n * 3. Returns null if no suitable field is found\n *\n * @param Activity $activity The activity to determine the field for\n *\n * @return string|null The field name to use in queries, or null if none is available\n */\n private function getActivityFieldName(Activity $activity): ?string\n {\n if ($this->profile === null) {\n $this->logger->warning('[Salesforce] Cannot determine activity field - profile not found', [\n 'activityId' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $profileEventFields = $this->profile->getFieldsAsArray('event');\n\n if (empty($profileEventFields)) {\n $defaultActivityField = $this->getDefaultActivityField(Field::OBJECT_EVENT);\n $defaultFieldName = $defaultActivityField?->getAttribute('crm_provider_id');\n // Profile not yet synced — fall back to the default activity field.\n // There is a small chance that the profile won't have Default Activity Type field access\n // in which case the query will fail.\n // This is however an edge case and should be reviewed for profile sync issues.\n Sentry::withScope(function (\\Sentry\\State\\Scope $scope) use ($defaultFieldName): void {\n $scope->setContext('details', [\n 'profileId' => $this->profile->id,\n 'defaultField' => $defaultFieldName,\n ]);\n Sentry::captureMessage(\n '[Salesforce] Profile event fields empty, falling back to default activity field.',\n \\Sentry\\Severity::warning()\n );\n });\n\n return $defaultFieldName;\n }\n\n $playbook = $this->getPlaybook($activity->getUser());\n\n if (! is_null($playbook) && ! is_null($playbook->getActivityField())) {\n $playbookFieldName = $playbook->getActivityField()->getAttribute('crm_provider_id');\n\n if (in_array($playbookFieldName, $profileEventFields, true)) {\n return $playbookFieldName;\n }\n\n $this->logger->warning('[Salesforce] Playbook activity field not found in profile fields', [\n 'activityId' => $activity->getUuid(),\n 'playbookField' => $playbookFieldName,\n 'profileId' => $this->profile->id,\n ]);\n }\n\n return null;\n }\n\n private function buildFetchRelatedEventQuery(Activity $activity): string\n {\n $hasWho = $activity->lead_id || $activity->contact_id;\n\n $activityFieldName = $this->getActivityFieldName($activity);\n $fields = array_filter(['Id', 'Description', 'OwnerId', $activityFieldName]);\n\n $ownerCondition = '(OwnerId = :ownerId OR CreatedById = :ownerId)';\n\n $query = '\n SELECT ' . implode(',', $fields) . '\n FROM Event\n WHERE ' . $ownerCondition . '\n AND IsArchived = false\n AND IsAllDayEvent = false\n AND StartDateTime >= :from\n AND EndDateTime <= :to\n AND (';\n\n $operator = '';\n if ($activity->account_id) {\n // This covers events tied to a related contact or opportunity too.\n $query .= 'AccountId = :accountId';\n\n $operator = ' OR ';\n }\n\n if ($hasWho) {\n $query .= $operator . 'WhoId = :whoId';\n\n // If we are also going to check on a specific opportunity, set that up.\n if ($activity->opportunity_id) {\n $query .= ' OR WhatId = :whatId';\n }\n }\n\n $query .= ') ORDER BY LastModifiedDate DESC';\n\n return $query;\n }\n\n public function fetchProspect(array $task): array\n {\n $lead = $account = $opportunity = $contact = $stage = $countryCode = null;\n $externalId = $task['WhoId'] ?? null;\n\n // Lead or Contact\n if ($externalId) {\n try {\n [$lead, $account, $opportunity, $contact, $stage, $countryCode] = $this->parseRecords($externalId);\n } catch (\\InvalidArgumentException $exception) {\n // Invalid object type.\n }\n }\n\n // If we happen to know the opportunity or account from the Task, figure that out.\n if (empty($task['WhatId']) === false) {\n // WhatId could be either Account ID or Opportunity ID.\n // If WhatId is Opportunity ID, get the opportunity and stage from the CRM.\n try {\n [, $account, $opportunity, , $stage, ] = $this->parseRecords($task['WhatId']);\n } catch (\\InvalidArgumentException $exception) {\n // Invalid object type.\n }\n }\n\n return [$lead, $account, $opportunity, $contact, $stage, $countryCode];\n }\n\n /**\n * Save activity transcription summary as note\n */\n public function saveTranscriptionSummaryAsNote(\n ActivityContract $activity,\n string $title,\n string $body,\n ?string $objectId,\n ?NoteObject $noteObject = null,\n ): ?string {\n return $this->saveNote($title, $body, (string) $objectId);\n }\n\n public function getObjectByFilterConditions(string $objectType, array $fields, array $filters): ?array\n {\n if ($this->profile === null) {\n return null;\n }\n\n $queryBuilder = app(QueryBuilder::class, [\n 'profile' => $this->profile,\n ]);\n\n $query = $queryBuilder->buildObjectSearchQuery($objectType, $fields, $filters);\n\n try {\n $objects = $this->queryHandler->query($query, $filters);\n if ($objects->count() === 1) {\n return $objects->current();\n }\n } catch (\\Exception $e) {\n $this->logger->info('[Salesforce] Failed to execute query', [\n 'query' => $query,\n 'error' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n private function getCustomProfileRules(TeamRepository $teamRepository): array\n {\n $teamSettings = $teamRepository->getTeamSetting($this->team, 'custom_profile_validation');\n\n if ($teamSettings instanceof TeamSettings && $teamSettings->getValueType() === 'array') {\n $customRules = json_decode($teamSettings->getValue(), true);\n if (is_array($customRules)) {\n return $customRules;\n }\n }\n\n return [];\n }\n\n private function customProfileValidation(array $crmUser, array $customRules): bool\n {\n foreach ($customRules as $customRule) {\n if ($crmUser[$customRule['field']] !== $customRule['value']) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * When syncing Contact / Lead / Account / Opportunity / Stage crm entities,\n * validate and restore locally trashed objects,\n * before updating them. Objects are identified by CrmProviderId\n */\n private function restoreAnyTrashedEntity(HasMany $targetEntity, string $crmProviderId): void\n {\n $recordExists = $targetEntity->withTrashed()->where(['crm_provider_id' => $crmProviderId])->first();\n if ($recordExists && $recordExists->trashed()) {\n $recordExists->restore();\n }\n }\n\n #[\\Override] public function supportsNotes(): bool\n {\n return true;\n }\n\n private function getOwnerProfile(?string $ownerId): ?Profile\n {\n if ($ownerId === null) {\n return null;\n }\n\n return $this->config->profiles()\n ->where('crm_provider_id', $ownerId)\n ->first();\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-15845258123973217
|
-7851939513083164217
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
11
130
3
21
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Salesforce;
use Carbon\Carbon;
use Exception;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Events\Dispatcher;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Jiminny\Component\Country\CountriesMap;
use Jiminny\Contracts\Acl\PermissionEnum;
use Jiminny\Contracts\Repositories\TeamRepository;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\ImportsBusinessProcessesInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\SalesforceBatchSyncInterface;
use Jiminny\Contracts\Services\Crm\Provider\SalesforceInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\RemoteNoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SearchTaskInterface;
use Jiminny\Contracts\Services\Crm\SendSummaryToCrmInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SupportsObjectTypeParseInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmProfileRecordTypesInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Enums\CrmObject;
use Jiminny\Events\Activities\Crm\LeadConverted;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpBadRequestException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\NoResultsException;
use Jiminny\Exceptions\ServiceUnavailableException;
use Jiminny\Jobs\Crm\NoteObject;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Calendar\CalendarEvent;
use Jiminny\Models\Contact;
use Jiminny\Models\Contracts\ActivityContract;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\ContactRole;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Crm\RecordType;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\TeamSettings;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\ContactRoleRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\Crm\RecordTypeFieldValuesRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\Helpers\ArrayIterator;
use Jiminny\Services\Crm\MatchDomainByEmailInterface;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Services\Crm\ResolveCompanyNameByEmailTrait;
use Jiminny\Services\Crm\Salesforce\Fields\FieldHelper;
use Jiminny\Services\Crm\Salesforce\Fields\FieldTypeConverter;
use Jiminny\Services\Crm\Salesforce\Fields\ValueNormalizer;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\FollowupActivityTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\LogActivityTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\RecordManipulationsTrait;
use Jiminny\Services\Crm\Salesforce\ServiceTraits\SyncFieldsTrait;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
use Ramsey\Uuid\Uuid;
use Sentry\Laravel\Facade as Sentry;
class Service extends BaseService implements
SalesforceInterface,
SalesforceBatchSyncInterface,
SyncCrmEntitiesInterface,
SyncCrmProfileRecordTypesInterface,
ImportsBusinessProcessesInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
SendSummaryToCrmInterface,
MatchDomainByEmailInterface,
SearchTaskInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
SupportsObjectTypeParseInterface,
RemoteNoteEntityManipulationInterface,
VerifyTaskExistsInterface
{
use ResolveCompanyNameByEmailTrait;
use SyncFieldsTrait;
use DeleteObjectsTrait;
use RecordManipulationsTrait;
use ServiceTraits\BatchSyncTrait;
use FollowupActivityTrait;
use LogActivityTrait;
/**
* Note Body Limit for the Old Note-Taking Tool
*
* @var int
*/
private const int CLASSIC_NOTE_MAX_LENGTH = 32000;
/**
* Note Content Limit for the New Notes
*
* @var int
*/
private const int ENHANCED_NOTE_MAX_LENGTH = 50000000;
private const string INSTALLED_PACKAGE_ID = '033Tw0000007bKbIAI';
private const int CACHE_TTL = 600;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day - 86400
/**
* @var Client
*/
protected $client;
protected PayloadBuilder $payloadBuilder;
protected QueryHandler $queryHandler;
private OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
public function __construct(
Client $client,
PayloadBuilder $payloadBuilder,
protected Dispatcher $eventDispatcher,
private readonly CountriesMap $countriesMap,
private readonly ProspectPhotoPathService $prospectPhotoPathService,
) {
parent::__construct();
$this->client = $client;
$this->payloadBuilder = $payloadBuilder;
$this->queryHandler = app(QueryHandler::class, [
'client' => $this->client,
'logger' => $this->logger,
]);
$this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
}
public function getDisplayName(): string
{
return 'Salesforce';
}
public function getJobDelay(): int
{
return 1;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
return $user->getSocialAccount(SocialAccount::PROVIDER_SALESFORCE);
}
public function verifyTaskExists(Activity $activity): bool
{
$crmProviderId = $activity->getCrmProviderId();
$cacheKey = "crm_task_exists:{$this->config->getId()}:$crmProviderId";
return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($activity, $crmProviderId) {
$playbook = $this->getPlaybookFromActivity($activity);
if ($playbook === null) {
$this->logger->warning('[Salesforce] Cannot verify task - no playbook found', [
'activity' => $activity->getId(),
'crm_provider_id' => $crmProviderId,
]);
return false;
}
$objectType = $playbook->getActivityType() === Playbook::ACTIVITY_TYPE_EVENT ? 'Event' : 'Task';
try {
$record = $this->getRecord($objectType, $crmProviderId, ['Id', 'IsDeleted']);
return ! empty($record) && ($record['IsDeleted'] ?? false) === false;
} catch (HttpNotFoundException|HttpBadRequestException) {
$this->logger->info('[Salesforce] Activity record not found during verification', [
'activity' => $activity->getId(),
'object_type' => $objectType,
'crm_provider_id' => $crmProviderId,
'config_id' => $this->config->getId(),
]);
return false;
}
});
}
public function query(string $queryToRun, array $parameters = []): QueryIterator
{
// Due to poorly designed external calls, this method cannot be entirely removed
return $this->queryHandler->query($queryToRun, $parameters);
}
/*=========== Organization Information ===============*/
/**
* Get a list of all the API Versions for the instance.
*
* @throws CrmException
*
* @return mixed
*
*/
public function getApiVersions()
{
$url = $this->config->crm_base_url . '/services/data';
$response = $this->client->get($url);
return json_decode($response->getBody(), true);
}
/**
* Gets the valid recordTypes for a given Salesforce Object via the describe API.
*/
private function getRecordTypes(string $crmObject): array
{
$url = $this->client->getObjectsUrl() . $crmObject . '/describe';
$response = $this->client->get($url);
$jsonResponse = json_decode($response->getBody(), true);
$fields = [];
foreach ($jsonResponse['recordTypeInfos'] as $row) {
$fields[] = ['recordTypeId' => $row['recordTypeId'], 'default' => $row['defaultRecordTypeMapping']];
}
return $fields;
}
/**
* Convert raw field data into a format compatible with CRM APIs.
*/
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return ValueNormalizer::normalize($fieldType, $fieldValue, $internal);
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
$defaultFields = ($activityType === Playbook::ACTIVITY_TYPE_TASK)
? FieldDefinitions::defaultTaskFields()
: FieldDefinitions::defaultEventFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'Type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK, Playbook::ACTIVITY_TYPE_EVENT];
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldFilter = ($activityType === Playbook::ACTIVITY_TYPE_TASK)
? FieldDefinitions::taskFollowupFieldsFilter()
: FieldDefinitions::eventFollowupFieldsFilter();
foreach ($fieldFilter as $eachFilter) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $eachFilter);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
/**
* This one is now called only when ImportActivityTypes is triggered or SyncFieldMetadata executed manually
* Regular sync now uses SharedSyncFieldsTrait -> syncSingleObjectType
* Needs to be replaced later on
*/
public function syncField(Field $field): void
{
try {
if (FieldHelper::isCustomField($field)) {
$query = '
SELECT
Id, Metadata, TableEnumOrId
FROM
CustomField
WHERE
DeveloperName = :fieldName
AND
TableEnumOrId = :fieldType
AND
NamespacePrefix = :namespacePrefix';
// We need to constrain the field lookup to the object, in case it's used in multiple places.
$objectType = \in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true)
? 'activity'
: $field->object_type;
$sfFields = $this->queryHandler->metadata($query, [
'fieldName' => substr($field->crm_provider_id, 0, -\strlen('__c')),
'fieldType' => ucfirst($objectType),
// This is used to ensure we only consider the field within the org, not installed packages.
'namespacePrefix' => 'null',
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
// Sync field metadata.
$metadata = $sfField['Metadata'];
$field->description = mb_strimwidth($metadata['description'] ?? '', 0, 191);
$field->label = mb_strimwidth($metadata['label'] ?? '', 0, Field::LABEL_MAX_LENGTH);
$field->type = $this->convertFieldType($metadata['type'], $field->getEntityName());
$field->is_mandatory = ($metadata['required'] === true);
$field->length = $metadata['length'];
$field->default_value = mb_strimwidth(trim($metadata['defaultValue'] ?? '', '"'), 0, 191);
$field->save();
} else {
$query = '
SELECT
Id, DataType, DeveloperName, Label, Length, Description
FROM
FieldDefinition
WHERE
DurableId = :entityName';
$entityName = $field->getEntityName();
$sfFields = $this->queryHandler->metadata($query, [
'entityName' => $entityName,
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
$convertedType = $this->convertFieldType($sfField['DataType'], $entityName);
$label = mb_strimwidth($sfField['Label'], 0, Field::LABEL_MAX_LENGTH);
if ($field->isBusinessType()) {
$label = 'Opportunity Type';
}
$field->description = mb_strimwidth($sfField['Description'], 0, Field::DESCRIPTION_MAX_LENGTH);
$field->label = $label;
$field->type = $convertedType;
$field->length = $sfField['Length'];
$field->save();
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
private function convertFieldType(string $from, ?string $entityName = null): string
{
$converter = new FieldTypeConverter();
return $converter->convert($from, $entityName);
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$values = [];
$fieldValues = [];
try {
if (FieldHelper::isCustomField($field)) {
$query = '
SELECT
Id, Metadata, TableEnumOrId
FROM
CustomField
WHERE
DeveloperName = :fieldName
AND
TableEnumOrId = :fieldType
AND
NamespacePrefix = :namespacePrefix';
// We need to constrain the field lookup to the object, in case it's used in multiple places.
$objectType = \in_array($field->object_type, [Field::OBJECT_TASK, Field::OBJECT_EVENT], true) ?
'activity' : $field->object_type;
$sfFields = $this->queryHandler->metadata($query, [
'fieldName' => substr($field->crm_provider_id, 0, -\strlen('__c')),
'fieldType' => ucfirst($objectType),
// This is used to ensure we only consider the field within the org, not installed packages.
'namespacePrefix' => 'null',
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
$valueSet = $sfField['Metadata']['valueSet'];
if ($valueSet['valueSetName'] === null) {
// Local picklist values can be obtained easily.
$picklistValues = $valueSet['valueSetDefinition']['value'];
} else {
// But for some fields, we just get the Global Value Picklist pointer so need to do more work.
$picklistValues = $this->importGlobalValuePicklistValues($valueSet['valueSetName']);
}
// Import all active values.
foreach ($picklistValues as $i => $sfFieldValue) {
// Setup default value.
if ($sfFieldValue['default']) {
$field->update(['default_value' => $sfFieldValue['valueName']]);
}
// This comes through as null if active (lol).
if ($sfFieldValue['isActive'] !== false) {
$values[] = [
'value' => $sfFieldValue['valueName'],
'label' => $sfFieldValue['valueName'],
'sequence' => $i,
'is_default' => $sfFieldValue['default'],
];
}
}
} else {
$objectFields = $this->getObjectFields($field->object_type);
$fieldId = $field->crm_provider_id;
// Only work with our field of interest.
$objectField = array_filter($objectFields, function ($item) use ($fieldId) {
return $item['name'] === $fieldId;
});
$objectField = array_shift($objectField);
if (empty($objectField['picklistValues']) === false) {
foreach ($objectField['picklistValues'] as $i => $sfFieldValue) {
// Skip inactive values.
if ($sfFieldValue['active'] === false) {
continue;
}
// Setup default value.
if ($sfFieldValue['defaultValue']) {
$field->update(['default_value' => $sfFieldValue['value']]);
}
$values[] = [
'value' => $sfFieldValue['value'],
'label' => $sfFieldValue['label'],
'sequence' => $i,
'is_default' => $sfFieldValue['defaultValue'],
];
}
}
}
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
if (($key = array_search($value['value'], $fieldsToPurge, true)) !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
// Get IDs of the values to be deleted
$valuesToDelete = $field->values()->whereIn('value', $fieldsToPurge);
$valuesToDeleteIds = $valuesToDelete->pluck('id');
if (! $valuesToDeleteIds->isEmpty()) {
$recordTypeFieldValuesRepository = app(RecordTypeFieldValuesRepository::class);
$recordTypeFieldValuesRepository->deleteForCrmFieldValueIds($valuesToDeleteIds->toArray());
// Now safely delete from crm_field_values
$valuesToDelete->delete();
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
return $fieldValues;
}
/**
* Gets values from Global Value Picklists.
*/
private function importGlobalValuePicklistValues(string $picklistName): array
{
$query = '
SELECT
Metadata
FROM
GlobalValueSet
WHERE
DeveloperName = :picklistName
LIMIT 1';
try {
$sfValues = $this->queryHandler->metadata($query, [
'picklistName' => $picklistName,
]);
// There is always 1 result at this point.
$sfValue = $sfValues->current();
return $sfValue['Metadata']['customValue'];
} catch (NoResultsException $noResultsException) {
// Nothing returned.
return [];
}
}
/**
* @inheritdoc
*/
public function syncProfileRecordTypes(): void
{
$objectTypes = [
'lead',
'account',
'contact',
'opportunity',
'task',
'event',
];
foreach ($objectTypes as $objectType) {
try {
$crmRecordTypes = $this->getRecordTypes(ucfirst($objectType));
foreach ($crmRecordTypes as $crmRecordType) {
// If the record type is default and not the Master type, set this.
if ($crmRecordType['default'] && $crmRecordType['recordTypeId'] !== '012000000000000AAA') {
$recordType = $this->config->recordTypes()
->where('crm_provider_id', $crmRecordType['recordTypeId'])
->first();
if ($recordType) {
$this->profile->{$objectType . '_record_type_id'} = $recordType->id;
}
}
}
} catch (HttpNotFoundException $exception) {
Log::error('No access to ' . $objectType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
if ($this->profile->isDirty()) {
$this->profile->save();
}
}
/**
* Gets business processes.
*/
public function importBusinessProcesses(): void
{
$query = '
SELECT
Id, IsActive, Name, TableEnumOrId
FROM
BusinessProcess
WHERE
TableEnumOrId IN (\'Lead\',\'Opportunity\')';
try {
$sfProcesses = $this->queryHandler->query($query);
// Upsert all processes for the team.
foreach ($sfProcesses as $sfProcess) {
/** @var BusinessProcess $businessProcess */
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => $sfProcess['Id'],
], [
'team_id' => $this->team->id,
'name' => $sfProcess['Name'],
'type' => $sfProcess['TableEnumOrId'] === 'Lead' ? 'lead' : 'opportunity',
'is_selectable' => $sfProcess['IsActive'],
]);
$this->importBusinessProcessStages($businessProcess);
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* Gets business process stages.
*/
private function importBusinessProcessStages(BusinessProcess $businessProcess): void
{
$query = '
SELECT
Metadata
FROM
BusinessProcess
WHERE
Id = :processId';
try {
$stages = [];
$sfProcessStages = $this->queryHandler->metadata($query, [
'processId' => $businessProcess->crm_provider_id,
]);
// There is always 1 result at this point.
$sfProcessStage = $sfProcessStages->current();
// Upsert all processes for the team.
foreach ($sfProcessStage['Metadata']['values'] as $sfProcessStage) {
$sanitizedName = urldecode($sfProcessStage['valueName']); // Must decode: "%2C" becomes "," etc.
$stage = $businessProcess->crm->stages()
// This MUST match on label because this API doesn't use API Name.
->where('label', $sanitizedName)
->where('type', $businessProcess->type)
->where('is_selectable', 1)
->first();
if ($stage) {
$stages[] = $stage->id;
}
}
$businessProcess->stages()->sync($stages);
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* Gets record types.
*/
public function importRecordTypes(): void
{
$query = '
SELECT
Id, IsActive, Name, BusinessProcessId, SobjectType
FROM
RecordType';
try {
$sfRecordTypes = $this->queryHandler->query($query);
// Upsert all record types for the process.
foreach ($sfRecordTypes as $sfRecordType) {
$businessProcess = null;
if ($sfRecordType['BusinessProcessId']) {
$businessProcess = $this->config->businessProcesses()
->where('crm_provider_id', $sfRecordType['BusinessProcessId'])
->first();
}
/** @var RecordType $recordType */
$recordType = $this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => $sfRecordType['Id'],
], [
'team_id' => $this->team->id,
'type' => mb_strtolower($sfRecordType['SobjectType']),
'name' => $sfRecordType['Name'],
'is_selectable' => $sfRecordType['IsActive'],
'business_process_id' => $businessProcess->id ?? null,
]);
$this->importRecordTypeFieldValues($recordType);
}
} catch (NoResultsException $noResultsException) {
// Do nothing.
}
}
/**
* Import record type - field value mappings. This only works for standard fields.
*/
private function importRecordTypeFieldValues(RecordType $recordType): void
{
try {
$query = '
SELECT
Metadata
FROM
RecordType
WHERE
Id = :recordTypeId';
$sfFields = $this->queryHandler->metadata($query, [
'recordTypeId' => $recordType->crm_provider_id,
]);
// There is always 1 result at this point.
$sfField = $sfFields->current();
// Sync field metadata.
$picklists = $sfField['Metadata']['picklistValues'];
foreach ($picklists as $picklist) {
$field = $this->config->fields()->where([
'type' => Field::TYPE_PICKLIST,
'object_type' => $recordType->type,
'crm_provider_id' => $picklist['picklist'],
])->first();
if ($field) {
$fieldValues = [];
foreach ($picklist['values'] as $value) {
// Must decode: "%2C" becomes "," etc.
$fieldValue = $field->values()
->where('value', urldecode($value['valueName']))
->first();
if ($fieldValue) {
$fieldValues[] = $fieldValue->id;
}
}
$recordType->fieldValues()->sync($fieldValues);
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
}
/**
* @inheritdoc
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$params = [];
$missingStage = null;
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
foreach ($types as $type) {
if ($type === Stage::TYPE_LEAD) {
$query = '
SELECT
Id, ApiName, MasterLabel, SortOrder
FROM
LeadStatus';
} else {
$query = '
SELECT
Id, ApiName, MasterLabel, IsActive, SortOrder, DefaultProbability
FROM
OpportunityStage';
}
if ($missingStageName) {
$escapedStageName = ValueNormalizer::replaceQueryWithStringLiterals($missingStageName);
$query .= ' WHERE ApiName = :stageName';
$params = [
'stageName' => $escapedStageName,
];
}
try {
$sfStages = $this->queryHandler->query($query, $params);
} catch (NoResultsException $exception) {
$sfStages = [];
}
$missingStage = null;
// Upsert all stages for the team.
foreach ($sfStages as $sfStage) {
$selectable = true;
if (array_key_exists('IsActive', $sfStage)) {
$selectable = $sfStage['IsActive'];
}
$this->restoreAnyTrashedEntity($this->config->stages(), $sfStage['Id']);
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $sfStage['Id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($sfStage['ApiName'], 0, 50),
'label' => mb_strimwidth($sfStage['MasterLabel'], 0, 191),
'type' => $type,
'sequence' => $sfStage['SortOrder'] ?? 0,
'is_selectable' => $selectable,
'probability' => $sfStage['DefaultProbability'] ?? null,
]);
if ($missingStageName && $missingStageName === $sfStage['ApiName']) {
$missingStage = $stage;
}
}
if ($missingStageName && $missingStage === null) {
// If they requested a stage that still doesn't exist, it must be inactive so lazy create it.
$missingStage = $this->config->stages()->create([
'crm_provider_id' => Uuid::uuid4(),
'team_id' => $this->team->id,
'name' => mb_strimwidth($missingStageName, 0, 50),
'label' => mb_strimwidth($missingStageName, 0, 191),
'type' => $type,
'sequence' => 0,
'is_selectable' => 0,
]);
}
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$fields = $this->getAllFieldsAsArray('lead');
if (\in_array('Id', $fields, true) === false) {
return $syncCount;
}
$query = '
SELECT ' . rtrim(implode(',', $fields), ',') . '
FROM Lead
WHERE LastModifiedDate > :since
ORDER BY LastModifiedDate ASC';
try {
$sfLeads = $this->queryHandler->query($query, [
'since' => $since->format('Y-m-d\TH:i:s\Z'),
]);
foreach ($sfLeads as $sfLead) {
// Only sync if previously imported.
if ($this->hasLead($sfLead['Id'])) {
$this->importLead($sfLead);
$syncCount++;
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::LEAD);
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
$fields = $this->getAllFieldsAsArray('lead');
$sfLead = $this->getRecord('Lead', $crmId, $fields);
return $this->importLead($sfLead);
}
private function importLead($crmData): ?Lead
{
/** @var ?Stage $stage */
$stage = null;
if (isset($crmData['Status'])) {
// Get the current stage.
$stage = $this->config
->stages()
->where('name', $crmData['Status'])
->where('type', Stage::TYPE_LEAD)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['Status']);
}
}
// If we have no way of importing this, just return null :(
if ($stage === null) {
return null;
}
$countryCode = $crmData['CountryCode'] ?? null;
// Salesforce allows custom "countries" to be created. Disregard these.
if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {
$countryCode = null;
}
// If we have no country code, try to parse it from the country name.
if ($countryCode === null && empty($crmData['Country']) !== false) {
$countryCode = $this->convertCountryNameToCode($crmData['Country']);
}
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['Phone'] ?? '', 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
$mobilePhone = null;
if (empty($crmData['MobilePhone']) === false) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['MobilePhone'], 0, 25);
$mobilePhone = phone_e164($countryCode, $number);
}
$convertedDate = null;
$convertedAccount = null;
$convertedOpportunity = null;
$convertedContact = null;
if ($crmData['IsConverted'] == 'true') {
$convertedDate = $crmData['ConvertedDate'];
if (empty($crmData['ConvertedAccountId']) === false) {
$convertedAccount = $this->config
->accounts()
->where('crm_provider_id', $crmData['ConvertedAccountId'])
->first();
if ($convertedAccount === null) {
try {
$convertedAccount = $this->syncAccount($crmData['ConvertedAccountId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
if (empty($crmData['ConvertedOpportunityId']) === false) {
$convertedOpportunity = $this->config
->opportunities()
->where('crm_provider_id', $crmData['ConvertedOpportunityId'])
->first();
if ($convertedOpportunity === null) {
try {
$convertedOpportunity = $this->syncOpportunity($crmData['ConvertedOpportunityId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
if (empty($crmData['ConvertedContactId']) === false) {
$convertedContact = $this->team
->crm
->contacts()
->where('crm_provider_id', $crmData['ConvertedContactId'])
->first();
if ($convertedContact === null) {
try {
$convertedContact = $this->syncContact($crmData['ConvertedContactId']);
} catch (HttpNotFoundException $exception) {
// Probably the user has no permissions to access the converted data.
}
}
}
}
if (empty($crmData['Company'])) {
$company = 'Unknown';
} else {
$company = mb_strimwidth($crmData['Company'], 0, 191);
}
$domain = null;
if (empty($crmData['Website']) === false) {
$domain = mb_strimwidth($crmData['Website'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$createdDate = null;
if (empty($crmData['CreatedDate']) === false) {
$createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$data = [
'team_id' => $this->team->id,
'user_id' => $profile?->user_id,
'owner_id' => $crmData['OwnerId'] ?? '',
'company' => $company,
'domain' => $domain,
'name' => $crmData['Name'] ? mb_strimwidth($crmData['Name'], 0, 191) : '',
'title' => $crmData['Title'] ? mb_strimwidth($crmData['Title'], 0, 128) : null,
'email' => $crmData['Email'] ? mb_strimwidth($crmData['Email'], 0, 80) : null,
'phone' => $parsedNumber['phone'],
'ext' => $parsedNumber['ext'] ?? null,
'mobile_phone' => $mobilePhone,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['Id'],
modelType: Lead::class,
fileName: $crmData['Id'],
avatarText: $crmData['Name']
),
'stage_id' => $stage->id,
'record_type_id' => null,
'converted_at' => $convertedDate,
'converted_account_id' => $convertedAccount->id ?? null,
'converted_opportunity_id' => $convertedOpportunity->id ?? null,
'converted_contact_id' => $convertedContact->id ?? null,
'country_code' => $countryCode,
'remotely_created_at' => $createdDate,
];
$this->restoreAnyTrashedEntity($this->config->leads(), $crmData['Id']);
/** @var Lead $lead */
$lead = $this->config->leads()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);
if ($lead->wasChanged('converted_at') && $lead->getConvertedAt() !== null) {
$this->eventDispatcher->dispatch(new LeadConverted($lead));
}
$this->handleObjectDeletion($lead, $crmData);
return $lead;
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$fields = $this->getAllFieldsAsArray('account');
if (\in_array('Id', $fields, true) === false) {
return $syncCount;
}
$query = '
SELECT ' . rtrim(implode(',', $fields), ',') . '
FROM Account
WHERE LastModifiedDate > :since
ORDER BY LastModifiedDate ASC';
try {
$sfAccounts = $this->queryHandler->query($query, [
'since' => $since->format('Y-m-d\TH:i:s\Z'),
]);
foreach ($sfAccounts as $sfAccount) {
// Only sync if previously imported.
if ($this->hasAccount($sfAccount['Id'])) {
$this->importAccount($sfAccount);
$syncCount++;
}
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::ACCOUNT);
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
$fields = $this->getAllFieldsAsArray('account');
if (! in_array('Id', $fields, true)) {
$this->logger->info('[Salesforce] Sync account cancelled. Fields are not available.', [
'crmId' => $crmId,
'userId' => $this->profile->getUserId(),
]);
return null;
}
$sfAccount = $this->getRecord('Account', $crmId, $fields);
return $this->importAccount($sfAccount);
}
private function importAccount($crmData): Account
{
$countryCode = $crmData['BillingCountryCode'] ?? $crmData['ShippingCountryCode'] ?? null;
// Salesforce allows custom "countries" to be created. Disregard these.
if ($countryCode && $this->countriesMap->countryExists($countryCode) === false) {
$countryCode = null;
}
// If we have no country code, try to parse it from the country names.
if ($countryCode === null && empty($crmData['BillingCountry']) === false) {
$countryCode = $this->convertCountryNameToCode($crmData['BillingCountry']);
}
if ($countryCode === null && empty($crmData['ShippingCountry']) === false) {
$countryCode = $this->convertCountryNameToCode($crmData['ShippingCountry']);
}
if (empty($crmData['Phone']) === false) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($crmData['Phone'], 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
$industry = null;
if (empty($crmData['Industry']) === false) {
$industry = mb_strimwidth($crmData['Industry'], 0, 40);
}
$domain = null;
if (empty($crmData['Website']) === false) {
$domain = mb_strimwidth($crmData['Website'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$createdDate = null;
if (empty($crmData['CreatedDate']) === false) {
$createdDate = Carbon::parse($crmData['CreatedDate'])->setTimezone('UTC');
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$data = [
'team_id' => $this->team->id,
'user_id' => $profile?->user_id,
'owner_id' => $crmData['OwnerId'],
'name' => mb_strimwidth($crmData['Name'], 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['Id'],
modelType: Account::class,
fileName: $crmData['Id'],
avatarText: $crmData['Name']
),
'industry' => $industry,
'domain' => $domain,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'country_code' => $countryCode,
'remotely_created_at' => $createdDate,
];
$this->restoreAnyTrashedEntity($this->config->accounts(), $crmData['Id']);
/** @var Account $account */
$account = $this->config->accounts()->updateOrCreate(['crm_provider_id' => $crmData['Id']], $data);
$this->handleObjectDeletion($account, $crmData);
return $account;
}
/**
* @inheritdoc
*/
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
$logParams = $parameters;
$parameters['profile'] = $this->profile;
$logParams['user'] = $this->profile->getUserId();
if (count($strategies) > 1) {
$this->logger->warning('[' . $this->getDisplayName() . '] Multiple sync strategies used', [
'teamId' => $this->team->getUuid(),
'params' => $logParams,
'strategies_count' => count($strategies),
]);
}
foreach ($strategies as $syncStrategy) {
$name = $syncStrategy->getStrategyName();
try {
$sfOpportunities = $syncStrategy->fetchOpportunities($parameters);
$totalRecords = $sfOpportunities->count();
foreach ($sfOpportunities as $sfOpportunity) {
$this->importOpportunity($sfOpportunity);
$syncCount++;
}
} catch (NoResultsException $noResultsException) {
// Nothing to sync.
$this->logger->warning('[' . $this->getDisplayName() . '] No opportunities found', [
'teamId' => $this->team->getUuid(),
'name' => $name,
'params' => $logParams,
'reason' => $noResultsException->getMessage(),
]);
} catch (CrmException $crmException) {
// Nothing to sync.
$this->logger->warning('[' . $this->getDisplayName() . '] Opportunity sync failed', [
'teamId' => $this->team->getUuid(),
'name' => $name,
'params' => $logParams,
'reason' => $crmException->getMessage(),
]);
}
}
$this->syncRemotelyDeletedObjectsWithErrorHandling(CrmObject::OPPORTUNITY, ['params' => $logParams]);
// debug to see how if count of opportunities reaches 1000
if ($syncCount >= 1000) {
$this->logger->info(
'[' . $this->getDisplayName() . '] Sync Opportunities - count warning',
[
'team_id' => $this->team->getId(),
'params' => $logParams,
'count' => $syncCount,
'strategies_count' => count($strategies),
'total_records' => $totalRecords ?? null,
]
);
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
$parameters = [
'profile' => $this->profile,
'crm_id' => $crmId,
];
try {
$sfOpportunity = $strategy->fetchOpportunities($parameters);
} catch (HttpNotFoundException $e) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [
'teamId' => $this->team->id_string,
'crmId' => $crmId,
]);
return null;
} catch (CrmException $crmException) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity sync failed', [
'teamId' => $this->team->id_string,
'crmId' => $crmId,
'exception' => $crmException->getMessage(),
]);
return null;
}
if ($sfOpportunity instanceof ArrayIterator) {
return $this->importOpportunity($sfOpportunity->getItems());
}
return $this->importOpportunity($sfOpportunity);
}
private function importOpportunity($crmData): ?Opportunity
{
/** @var ?Stage $stage */
$stage = null;
if (isset($crmData['StageName'])) {
$stage = $this->config
->stages()
->where('name', $crmData['StageName'])
->where('type', Stage::TYPE_OPPORTUNITY)
->orderBy('is_selectable', 'DESC')
->orderBy('id')
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['StageName']);
}
}
$recordType = null;
if (empty($crmData['RecordTypeId']) === false) {
/** @var ?RecordType $recordType */
$recordType = $this->config->recordTypes()
->where('crm_provider_id', $crmData['RecordTypeId'])
->first();
}
$profile = $this->getOwnerProfile($crmData['OwnerId'] ?? null);
$account = null;
if (empty($crmData['AccountId']) === false) {
/** @var ?Account $account */
$account = $this->config->accounts()
->whe...
|
45404
|
NULL
|
NULL
|
NULL
|
|
45404
|
1625
|
45
|
2026-05-14T14:34:58.916690+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769298916_m1.jpg...
|
PhpStorm
|
faVsco.js – AccountController.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelplhl100% C•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTest* :8• Thu 14 May 17:34:58Q18Projectv+,> D Telephony• D Webhook› D Hubspot> D IntegrationAppSubscriptions© ActivityProviderController.pt© ActivityTranscriptionControl© BaseController.php® CalendarController.php© ReportController.phpSoftphoneWebhookControlle20© AbstractController.php• CommentContextinterface.php33© ConferencesOptinOutControllel35© Controller.php© ExportController.php36© FrontendController.phpT FrontendControllerTrait.php© GeocodingController.php37 (0Р >5051© HealthCheckController.php© LiveCoachController.php© MissingTeamController.php© MobileController.php52 (0g >6566© NotificationController.php© NotificationProviderController.f 67 Qg© PlaybackController.php© PlaylistController.php© PusherController.php© SlackController.php68697071© SupportController.php© TeamSetupController.php72 đ >© UserAutomatedReportsControll81© WelcomeController.php82> D MiddlewareD RequestsD Resources›Responses© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.php© UserAutomatedReportsController.php:=custom.logPlanhatService.php© AutomatedReportResult.phpSendReportJob.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php=laravel.log© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© Salesforce/Service.phpT LogActivityTrait.phpSF [jiminny@localhost]© Pipedrive/Service.phpClose/Service.phpCopper/Service.phpBullhornService.php© PlainTextDecorateActivity.phpA HS_local [jiminny@localho:WT ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.php X.env.staging=.env4 console [QAI PROD] X© DetachActivityObject.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.php4 console [PROD]© HubspotPaginationService.php© HandleHubspotRateLimit.phpclass AccountController extends AbstractControllerpublic function__construct(prevace reduonty Loggerancertace+cogger,)f...3A console (EU]A6DGo jiminny084143 ×4 л215•m_layout_id =2162,1661,66799,66217/** New Account / Company Created */POST /webhook/intapp/acc-addpublic function created(): JsonResponse{... }218219.id = 33;220221/** Existing Account / Company Updated */POST /webhook/intapp/acc-updpublic function updated(): JsonResponse{... }222223224id THEN •(own225/** Existing Account / Company Deleted */POST /webhook/intapp/acc-delpublic function deleted(): JsonResponse226227228229return $this->handleBulkDeletion(targetKey: 'externalCompanies', fallbackKey: self::TARGET_KEY, eventName230hubspot':2312321 usageprotected function deleteTarget(Team Steam, string $targetId): void{...}233 V= 11512582;234Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams69:33UTF-8Ca 4 spaces...
|
NULL
|
6009738359263312153
|
NULL
|
visual_change
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelplhl100% C•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTest* :8• Thu 14 May 17:34:58Q18Projectv+,> D Telephony• D Webhook› D Hubspot> D IntegrationAppSubscriptions© ActivityProviderController.pt© ActivityTranscriptionControl© BaseController.php® CalendarController.php© ReportController.phpSoftphoneWebhookControlle20© AbstractController.php• CommentContextinterface.php33© ConferencesOptinOutControllel35© Controller.php© ExportController.php36© FrontendController.phpT FrontendControllerTrait.php© GeocodingController.php37 (0Р >5051© HealthCheckController.php© LiveCoachController.php© MissingTeamController.php© MobileController.php52 (0g >6566© NotificationController.php© NotificationProviderController.f 67 Qg© PlaybackController.php© PlaylistController.php© PusherController.php© SlackController.php68697071© SupportController.php© TeamSetupController.php72 đ >© UserAutomatedReportsControll81© WelcomeController.php82> D MiddlewareD RequestsD Resources›Responses© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.php© UserAutomatedReportsController.php:=custom.logPlanhatService.php© AutomatedReportResult.phpSendReportJob.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php=laravel.log© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© Salesforce/Service.phpT LogActivityTrait.phpSF [jiminny@localhost]© Pipedrive/Service.phpClose/Service.phpCopper/Service.phpBullhornService.php© PlainTextDecorateActivity.phpA HS_local [jiminny@localho:WT ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.php X.env.staging=.env4 console [QAI PROD] X© DetachActivityObject.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.php4 console [PROD]© HubspotPaginationService.php© HandleHubspotRateLimit.phpclass AccountController extends AbstractControllerpublic function__construct(prevace reduonty Loggerancertace+cogger,)f...3A console (EU]A6DGo jiminny084143 ×4 л215•m_layout_id =2162,1661,66799,66217/** New Account / Company Created */POST /webhook/intapp/acc-addpublic function created(): JsonResponse{... }218219.id = 33;220221/** Existing Account / Company Updated */POST /webhook/intapp/acc-updpublic function updated(): JsonResponse{... }222223224id THEN •(own225/** Existing Account / Company Deleted */POST /webhook/intapp/acc-delpublic function deleted(): JsonResponse226227228229return $this->handleBulkDeletion(targetKey: 'externalCompanies', fallbackKey: self::TARGET_KEY, eventName230hubspot':2312321 usageprotected function deleteTarget(Team Steam, string $targetId): void{...}233 V= 11512582;234Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams69:33UTF-8Ca 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45403
|
1626
|
25
|
2026-05-14T14:34:55.998531+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769295998_m2.jpg...
|
PhpStorm
|
faVsco.js – IntegrationAppTrait.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Jiminny... ~ActivityFilesLater@ jiminny-x-integrat Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preuiew in sact[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pmv Q SearchDate ModifiedYesterday at 13.3Yesterday at 13:36Yesterday at 13:36Yesterday at 13.30Yesterdav at 13:35Yesterday at 13:34Yesterday at 13:34Yesterdav at 13:3kYesterday at 13:33Yesterday at 13.32Yesterdav at 13:31resterday at 15:30Yesterdav at 13:30Yesterday at 13:29Yesterday at 13:29Yesterday at 13:28Yecterdav at 12:28resterday at 13-21Yesterdav at 13:26Yesterday at 13:26Yesterday at 13:25Yesterday at 13:25Voctorday at 12:01Yesterday at 13.23Yesterdav at 13:22resterady al 15.clYesterday at 13:20Yesterday at 13.19Yecterdav at 12:19Yesterdav at 13:18Yesterday at 13-1/Yesterdav at 13:17Yesterday at 13:16Yesterday at 13:15Yecterdav at 12:15Yesterday at 13.14Yecterdav at 13:10Yesterday at 13:13Yesterday at 13:12Yoctorday at 12:11Yesterday at 13.10Yecterdav at 12:10Yesterdav at 13:09Yesterdav at 13:08v Size23 KB9 KB13 Kb16 KE17 KB29 KB16 K:12 KB9 KEIKBn8 KBI37 KB10 KB7 KE8 KB9 KB8 KB172 KR14 KB13 KB9 KE18 KB12 KB10 KBI16 KB6 KB6KB12 KE23 KB8 KB16 K:11 KB20 KP34 KB10 KB7 K:5 KB11 KB26 KBMPEG-4 movieMPEG-4 movieMPEG-4 movieMPEG-4 movieMPE0"4 movieMDSG-A movieMP2G-4 movieMPEG-4 movieMPEG"4 movieMPEG-4 movieMoEeh movioMPEG-4 movieMPEG-1 movieMPEG-4 movieMPEG-4 movieMPEG-4 movieMPEG-4 movieMDEG.A movicMPEG-4 movieMPEG-4 movieMPEG-4 movieMPEG-4 movieMDEC A movidMPEG-4 movieMDEG-A movieMPEG-4 movieMPEG-4 movieMDEC.A moviaMPEG-4 movie111 KC102 KB88 KBMDEG-A moviaMPEG-4 movie59 KB1MPEG-A movie98 KB MPEG-4 movie97 KB66 K3MPEG-4 movieMDEG.A movioAAKP93 KB/8 KBMPEG-4 movie50 KгMDEG-A movid58 KBMPEG-4 movie27 KB7KBMPEG-4 movieAl Notes: OffLeave• • CFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc tolde0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esv1 config.vmlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•AlfredwPmazanoko.imnaoc.YWIfана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentK:PDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.47 GB availabld• Inu 14 May 1/•34:02Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 г+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
8033363151644175702
|
NULL
|
click
|
ocr
|
NULL
|
Jiminny... ~ActivityFilesLater@ jiminny-x-integrat Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preuiew in sact[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pmv Q SearchDate ModifiedYesterday at 13.3Yesterday at 13:36Yesterday at 13:36Yesterday at 13.30Yesterdav at 13:35Yesterday at 13:34Yesterday at 13:34Yesterdav at 13:3kYesterday at 13:33Yesterday at 13.32Yesterdav at 13:31resterday at 15:30Yesterdav at 13:30Yesterday at 13:29Yesterday at 13:29Yesterday at 13:28Yecterdav at 12:28resterday at 13-21Yesterdav at 13:26Yesterday at 13:26Yesterday at 13:25Yesterday at 13:25Voctorday at 12:01Yesterday at 13.23Yesterdav at 13:22resterady al 15.clYesterday at 13:20Yesterday at 13.19Yecterdav at 12:19Yesterdav at 13:18Yesterday at 13-1/Yesterdav at 13:17Yesterday at 13:16Yesterday at 13:15Yecterdav at 12:15Yesterday at 13.14Yecterdav at 13:10Yesterday at 13:13Yesterday at 13:12Yoctorday at 12:11Yesterday at 13.10Yecterdav at 12:10Yesterdav at 13:09Yesterdav at 13:08v Size23 KB9 KB13 Kb16 KE17 KB29 KB16 K:12 KB9 KEIKBn8 KBI37 KB10 KB7 KE8 KB9 KB8 KB172 KR14 KB13 KB9 KE18 KB12 KB10 KBI16 KB6 KB6KB12 KE23 KB8 KB16 K:11 KB20 KP34 KB10 KB7 K:5 KB11 KB26 KBMPEG-4 movieMPEG-4 movieMPEG-4 movieMPEG-4 movieMPE0"4 movieMDSG-A movieMP2G-4 movieMPEG-4 movieMPEG"4 movieMPEG-4 movieMoEeh movioMPEG-4 movieMPEG-1 movieMPEG-4 movieMPEG-4 movieMPEG-4 movieMPEG-4 movieMDEG.A movicMPEG-4 movieMPEG-4 movieMPEG-4 movieMPEG-4 movieMDEC A movidMPEG-4 movieMDEG-A movieMPEG-4 movieMPEG-4 movieMDEC.A moviaMPEG-4 movie111 KC102 KB88 KBMDEG-A moviaMPEG-4 movie59 KB1MPEG-A movie98 KB MPEG-4 movie97 KB66 K3MPEG-4 movieMDEG.A movioAAKP93 KB/8 KBMPEG-4 movie50 KгMDEG-A movid58 KBMPEG-4 movie27 KB7KBMPEG-4 movieAl Notes: OffLeave• • CFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc tolde0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esv1 config.vmlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•AlfredwPmazanoko.imnaoc.YWIfана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentK:PDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.47 GB availabld• Inu 14 May 1/•34:02Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 г+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45402
|
1625
|
44
|
2026-05-14T14:34:55.979914+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769295979_m1.jpg...
|
PhpStorm
|
faVsco.js – IntegrationAppTrait.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelplhl100% CFV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit K vHandleHubspotRateLimitTest* :8• Thu 14 May 17:34:55QProjectv.х:-© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.php© UserAutomatedReportsController.php:=custom.log> D TelephonyPlanhatService.php© AutomatedReportResult.phpSendReportJob.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php=laravel.log• D Webhook› D Hubspot© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© Salesforce/Service.phpT LogActivityTrait.phpSF [jiminny@localhost]v D IntegrationAppSubscriptions© Pipedrive/Service.phpClose/Service.phpCopper/Service.php© AccountController.phpBullhornService.php© PlainTextDecorateActivity.phpA HS_local [jiminny@localho:W18© ContactController.php© ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php X= .env.staging4 console [QAI PROD] XT IntegrationAppTrait.phpE.env© DetachActivityObject.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.php4 console [PROD]© LeadController.php© HubspotPaginationService.php© HandleHubspotRateLimit.phpA console (EU]© OpportunityController.ph© ProfileController.php13trait IntegrationAppTraitA7D68 jiminny91© SystemController.phpprotected function handleBulkDeletion(string StargetKey, string $fallbackKey, string SeventName): JsonResp084143 ×4 лT TokenDataTrait.php109215•m_layout_id =© ActivityProviderController.pt 1102162,1661,66799,66© ActivityTranscriptionControl 111217© BaseController.php112if (empty(StargetIds)) {218© CalendarController.php113$this->logger->warning('No target IDs found alter fallback for ' . $eventName);219.id = 33;© ReportController.php114220© SoftphoneWebhookControlle 115return new JsonResponse([], status: JsonResponse::HTTP_BAD_REQUEST);221© AbstractController.php116-222• CommentContextinterface.php117—223© ConferencesOptinOutControllel118foreach ($targetIds as $targetId) {224id THEN '(own© Controller.php119Sthis-›deleteTarget(team: Steam, targetid: (string) $targetId);225© ExportController.php120226© FrontendController.php121-227T FrontendControllerTrait.php122return new JsonResponse([],status: JsonResponse: :HTTP_0K);228© GeocodingController.php123229© HealthCheckController.php124230hubspot':-© LiveCoachController.phpno usages231© MissingTeamController.php125 @abstract protected function deleteTarget(Team $team, string $targetId): void;232© MobileController.php126233V= 11512582;© NotificationController.php127234© NotificationProviderController.p© PlaybackController.php© PlaylistController.php© PusherController.php© SlackController.phpWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams124:1UTF-8Ca 4 spaces...
|
NULL
|
-7430928778279164914
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelplhl100% CFV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit K vHandleHubspotRateLimitTest* :8• Thu 14 May 17:34:55QProjectv.х:-© AutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.php© UserAutomatedReportsController.php:=custom.log> D TelephonyPlanhatService.php© AutomatedReportResult.phpSendReportJob.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php=laravel.log• D Webhook› D Hubspot© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© Salesforce/Service.phpT LogActivityTrait.phpSF [jiminny@localhost]v D IntegrationAppSubscriptions© Pipedrive/Service.phpClose/Service.phpCopper/Service.php© AccountController.phpBullhornService.php© PlainTextDecorateActivity.phpA HS_local [jiminny@localho:W18© ContactController.php© ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php X= .env.staging4 console [QAI PROD] XT IntegrationAppTrait.phpE.env© DetachActivityObject.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.php4 console [PROD]© LeadController.php© HubspotPaginationService.php© HandleHubspotRateLimit.phpA console (EU]© OpportunityController.ph© ProfileController.php13trait IntegrationAppTraitA7D68 jiminny91© SystemController.phpprotected function handleBulkDeletion(string StargetKey, string $fallbackKey, string SeventName): JsonResp084143 ×4 лT TokenDataTrait.php109215•m_layout_id =© ActivityProviderController.pt 1102162,1661,66799,66© ActivityTranscriptionControl 111217© BaseController.php112if (empty(StargetIds)) {218© CalendarController.php113$this->logger->warning('No target IDs found alter fallback for ' . $eventName);219.id = 33;© ReportController.php114220© SoftphoneWebhookControlle 115return new JsonResponse([], status: JsonResponse::HTTP_BAD_REQUEST);221© AbstractController.php116-222• CommentContextinterface.php117—223© ConferencesOptinOutControllel118foreach ($targetIds as $targetId) {224id THEN '(own© Controller.php119Sthis-›deleteTarget(team: Steam, targetid: (string) $targetId);225© ExportController.php120226© FrontendController.php121-227T FrontendControllerTrait.php122return new JsonResponse([],status: JsonResponse: :HTTP_0K);228© GeocodingController.php123229© HealthCheckController.php124230hubspot':-© LiveCoachController.phpno usages231© MissingTeamController.php125 @abstract protected function deleteTarget(Team $team, string $targetId): void;232© MobileController.php126233V= 11512582;© NotificationController.php127234© NotificationProviderController.p© PlaybackController.php© PlaylistController.php© PusherController.php© SlackController.phpWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams124:1UTF-8Ca 4 spaces...
|
45401
|
NULL
|
NULL
|
NULL
|
|
45400
|
1625
|
42
|
2026-05-14T14:34:39.943319+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769279943_m1.jpg...
|
PhpStorm
|
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project Files
Preview
Filter
Open in Find Tool Win Project Files
Preview
Filter
Open in Find Tool Window
inte
IntegrationAppTrait.php .../app/.../Webhook/IntegrationAppSubscriptions/IntegrationAppTrait.php
integration-app.php .../config/integration-app.php
IntegrationConfig.php .../app/Services/Activity/AmazonConnect/IntegrationConfig.php, class
IntegrationConfig.php .../app/Services/Activity/Apollo/IntegrationConfig.php, class
IntegrationConfig.php .../app/Services/Activity/FiveNine/IntegrationConfig.php, class
IntegrationConfig.php .../app/Services/Activity/Orum/IntegrationConfig.php, final class
IntegrationAppInterface.php .../app/Contracts/Services/Crm/Provider/IntegrationAppInterface.php, interface
IntegrationAppProviders.php .../app/Services/Crm/IntegrationApp/Config/IntegrationAppProviders.php, class
IntegrationClientInterface.php .../app/Services/Activity/BaseService/IntegrationClientInterface.php, interface
IntegrationAppAccessException.php .../.../IntegrationApp/Accessors/IntegrationAppAccessException.php, exception class
IntegrationAppDefaultStrategy.php .../.../ProspectSearchStrategy/IntegrationAppDefaultStrategy.php, class
IntegrationAppServiceTrait.php .../app/.../Crm/IntegrationApp/Jobs/IntegrationAppServiceTrait.php
IntegerMinMaxRangeTest.php .../tests/Unit/Component/ActivitySearch/IntegerMinMaxRangeTest.php, class
IntegrationAppCrmGeneratorFactory.php .../app/.../DTO/Utils/IntegrationAppCrmGeneratorFactory.php, class
IntegrationClientInterface.php.html build/coverage/Services/Activity/BaseService
… more
IntegrationAppTrait.php .../app/.../Webhook/IntegrationAppSubscriptions/IntegrationAppTrait.php
integration-app.php .../config/integration-app.php
IntegrationConfig.php .../app/Services/Activity/AmazonConnect/IntegrationConfig.php, class
IntegrationConfig.php .../app/Services/Activity/Apollo/IntegrationConfig.php, class
IntegrationConfig.php .../app/Services/Activity/FiveNine/IntegrationConfig.php, class
IntegrationConfig.php .../app/Services/Activity/Orum/IntegrationConfig.php, final class
IntegrationAppInterface.php .../app/Contracts/Services/Crm/Provider/IntegrationAppInterface.php, interface
IntegrationAppProviders.php .../app/Services/Crm/IntegrationApp/Config/IntegrationAppProviders.php, class
IntegrationClientInterface.php .../app/Services/Activity/BaseService/IntegrationClientInterface.php, interface
IntegrationAppAccessException.php .../.../IntegrationApp/Accessors/IntegrationAppAccessException.php, exception class
IntegrationAppDefaultStrategy.php .../.../ProspectSearchStrategy/IntegrationAppDefaultStrategy.php, class
IntegrationAppServiceTrait.php .../app/.../Crm/IntegrationApp/Jobs/IntegrationAppServiceTrait.php
IntegerMinMaxRangeTest.php .../tests/Unit/Component/ActivitySearch/IntegerMinMaxRangeTest.php, class
IntegrationAppCrmGeneratorFactory.php .../app/.../DTO/Utils/IntegrationAppCrmGeneratorFactory.php, class
IntegrationClientInterface.php.html build/coverage/Services/Activity/BaseService
… more
Http/Controllers/Webhook/IntegrationAppSubscriptions/IntegrationAppTrait.php
Open In Right Split...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project Files","depth":2,"bounds":{"left":0.8298611,"top":0.25,"width":0.07430556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Preview","depth":2,"bounds":{"left":0.90416664,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Filter","depth":2,"bounds":{"left":0.9222222,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open in Find Tool Window","depth":2,"bounds":{"left":0.94027776,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextField","text":"inte","depth":1,"bounds":{"left":0.50555557,"top":0.29222223,"width":0.45277777,"height":0.032222223},"on_screen":true,"value":"inte","role_description":"text field","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"IntegrationAppTrait.php .../app/.../Webhook/IntegrationAppSubscriptions/IntegrationAppTrait.php","depth":2,"bounds":{"left":0.49930555,"top":0.33666667,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"integration-app.php .../config/integration-app.php","depth":2,"bounds":{"left":0.49930555,"top":0.3611111,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationConfig.php .../app/Services/Activity/AmazonConnect/IntegrationConfig.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.38555557,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationConfig.php .../app/Services/Activity/Apollo/IntegrationConfig.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.41,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationConfig.php .../app/Services/Activity/FiveNine/IntegrationConfig.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.43444446,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationConfig.php .../app/Services/Activity/Orum/IntegrationConfig.php, final class","depth":2,"bounds":{"left":0.49930555,"top":0.4588889,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationAppInterface.php .../app/Contracts/Services/Crm/Provider/IntegrationAppInterface.php, interface","depth":2,"bounds":{"left":0.49930555,"top":0.48333332,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationAppProviders.php .../app/Services/Crm/IntegrationApp/Config/IntegrationAppProviders.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.50777775,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationClientInterface.php .../app/Services/Activity/BaseService/IntegrationClientInterface.php, interface","depth":2,"bounds":{"left":0.49930555,"top":0.5322222,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationAppAccessException.php .../.../IntegrationApp/Accessors/IntegrationAppAccessException.php, exception class","depth":2,"bounds":{"left":0.49930555,"top":0.5566667,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationAppDefaultStrategy.php .../.../ProspectSearchStrategy/IntegrationAppDefaultStrategy.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.58111113,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationAppServiceTrait.php .../app/.../Crm/IntegrationApp/Jobs/IntegrationAppServiceTrait.php","depth":2,"bounds":{"left":0.49930555,"top":0.60555553,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegerMinMaxRangeTest.php .../tests/Unit/Component/ActivitySearch/IntegerMinMaxRangeTest.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.63,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationAppCrmGeneratorFactory.php .../app/.../DTO/Utils/IntegrationAppCrmGeneratorFactory.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.65444446,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationClientInterface.php.html build/coverage/Services/Activity/BaseService","depth":2,"bounds":{"left":0.49930555,"top":0.6788889,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"… more","depth":2,"bounds":{"left":0.49930555,"top":0.7033333,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationAppTrait.php .../app/.../Webhook/IntegrationAppSubscriptions/IntegrationAppTrait.php","depth":4,"bounds":{"left":0.49930555,"top":0.33666667,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"integration-app.php .../config/integration-app.php","depth":4,"bounds":{"left":0.49930555,"top":0.3611111,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationConfig.php .../app/Services/Activity/AmazonConnect/IntegrationConfig.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.38555557,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationConfig.php .../app/Services/Activity/Apollo/IntegrationConfig.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.41,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationConfig.php .../app/Services/Activity/FiveNine/IntegrationConfig.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.43444446,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationConfig.php .../app/Services/Activity/Orum/IntegrationConfig.php, final class","depth":4,"bounds":{"left":0.49930555,"top":0.4588889,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationAppInterface.php .../app/Contracts/Services/Crm/Provider/IntegrationAppInterface.php, interface","depth":4,"bounds":{"left":0.49930555,"top":0.48333332,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationAppProviders.php .../app/Services/Crm/IntegrationApp/Config/IntegrationAppProviders.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.50777775,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationClientInterface.php .../app/Services/Activity/BaseService/IntegrationClientInterface.php, interface","depth":4,"bounds":{"left":0.49930555,"top":0.5322222,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationAppAccessException.php .../.../IntegrationApp/Accessors/IntegrationAppAccessException.php, exception class","depth":4,"bounds":{"left":0.49930555,"top":0.5566667,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationAppDefaultStrategy.php .../.../ProspectSearchStrategy/IntegrationAppDefaultStrategy.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.58111113,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationAppServiceTrait.php .../app/.../Crm/IntegrationApp/Jobs/IntegrationAppServiceTrait.php","depth":4,"bounds":{"left":0.49930555,"top":0.60555553,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegerMinMaxRangeTest.php .../tests/Unit/Component/ActivitySearch/IntegerMinMaxRangeTest.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.63,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationAppCrmGeneratorFactory.php .../app/.../DTO/Utils/IntegrationAppCrmGeneratorFactory.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.65444446,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"IntegrationClientInterface.php.html build/coverage/Services/Activity/BaseService","depth":4,"bounds":{"left":0.49930555,"top":0.6788889,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"… more","depth":4,"bounds":{"left":0.49930555,"top":0.7033333,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"Http/Controllers/Webhook/IntegrationAppSubscriptions/IntegrationAppTrait.php","depth":1,"bounds":{"left":0.51319444,"top":0.74777776,"width":0.31388888,"height":0.018888889},"on_screen":true,"help_text":"Http/Controllers/Webhook/IntegrationAppSubscriptions/IntegrationAppTrait.php","role_description":"text"},{"role":"AXLink","text":"Open In Right Split","depth":1,"bounds":{"left":0.8673611,"top":0.74777776,"width":0.08055556,"height":0.018888889},"on_screen":true,"role_description":"link","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
975656886183946544
|
7936716316427509309
|
visual_change
|
accessibility
|
NULL
|
Project Files
Preview
Filter
Open in Find Tool Win Project Files
Preview
Filter
Open in Find Tool Window
inte
IntegrationAppTrait.php .../app/.../Webhook/IntegrationAppSubscriptions/IntegrationAppTrait.php
integration-app.php .../config/integration-app.php
IntegrationConfig.php .../app/Services/Activity/AmazonConnect/IntegrationConfig.php, class
IntegrationConfig.php .../app/Services/Activity/Apollo/IntegrationConfig.php, class
IntegrationConfig.php .../app/Services/Activity/FiveNine/IntegrationConfig.php, class
IntegrationConfig.php .../app/Services/Activity/Orum/IntegrationConfig.php, final class
IntegrationAppInterface.php .../app/Contracts/Services/Crm/Provider/IntegrationAppInterface.php, interface
IntegrationAppProviders.php .../app/Services/Crm/IntegrationApp/Config/IntegrationAppProviders.php, class
IntegrationClientInterface.php .../app/Services/Activity/BaseService/IntegrationClientInterface.php, interface
IntegrationAppAccessException.php .../.../IntegrationApp/Accessors/IntegrationAppAccessException.php, exception class
IntegrationAppDefaultStrategy.php .../.../ProspectSearchStrategy/IntegrationAppDefaultStrategy.php, class
IntegrationAppServiceTrait.php .../app/.../Crm/IntegrationApp/Jobs/IntegrationAppServiceTrait.php
IntegerMinMaxRangeTest.php .../tests/Unit/Component/ActivitySearch/IntegerMinMaxRangeTest.php, class
IntegrationAppCrmGeneratorFactory.php .../app/.../DTO/Utils/IntegrationAppCrmGeneratorFactory.php, class
IntegrationClientInterface.php.html build/coverage/Services/Activity/BaseService
… more
IntegrationAppTrait.php .../app/.../Webhook/IntegrationAppSubscriptions/IntegrationAppTrait.php
integration-app.php .../config/integration-app.php
IntegrationConfig.php .../app/Services/Activity/AmazonConnect/IntegrationConfig.php, class
IntegrationConfig.php .../app/Services/Activity/Apollo/IntegrationConfig.php, class
IntegrationConfig.php .../app/Services/Activity/FiveNine/IntegrationConfig.php, class
IntegrationConfig.php .../app/Services/Activity/Orum/IntegrationConfig.php, final class
IntegrationAppInterface.php .../app/Contracts/Services/Crm/Provider/IntegrationAppInterface.php, interface
IntegrationAppProviders.php .../app/Services/Crm/IntegrationApp/Config/IntegrationAppProviders.php, class
IntegrationClientInterface.php .../app/Services/Activity/BaseService/IntegrationClientInterface.php, interface
IntegrationAppAccessException.php .../.../IntegrationApp/Accessors/IntegrationAppAccessException.php, exception class
IntegrationAppDefaultStrategy.php .../.../ProspectSearchStrategy/IntegrationAppDefaultStrategy.php, class
IntegrationAppServiceTrait.php .../app/.../Crm/IntegrationApp/Jobs/IntegrationAppServiceTrait.php
IntegerMinMaxRangeTest.php .../tests/Unit/Component/ActivitySearch/IntegerMinMaxRangeTest.php, class
IntegrationAppCrmGeneratorFactory.php .../app/.../DTO/Utils/IntegrationAppCrmGeneratorFactory.php, class
IntegrationClientInterface.php.html build/coverage/Services/Activity/BaseService
… more
Http/Controllers/Webhook/IntegrationAppSubscriptions/IntegrationAppTrait.php
Open In Right Split...
|
45399
|
NULL
|
NULL
|
NULL
|
|
45399
|
1625
|
41
|
2026-05-14T14:34:36.869805+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769276869_m1.jpg...
|
PhpStorm
|
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project Files
Preview
Filter
Open in Find Tool Win Project Files
Preview
Filter
Open in Find Tool Window
interg
InterconnectGroup.php vendor/google/apiclient-services/src/Compute/InterconnectGroup.php, class
InterconnectGroups.php vendor/google/.../src/Compute/Resource/InterconnectGroups.php, class
InterconnectGroupConfigured.php vendor/google/.../src/Compute/InterconnectGroupConfigured.php, class
InterconnectGroupIntent.php vendor/google/.../src/Compute/InterconnectGroupIntent.php, class
InterconnectGroupInterconnect.php vendor/google/.../src/Compute/InterconnectGroupInterconnect.php, class
InterconnectGroupPhysicalStructure.php vendor/.../Compute/InterconnectGroupPhysicalStructure.php, class
InterconnectGroupsCreateMembers.php vendor/.../Compute/InterconnectGroupsCreateMembers.php, class
InterconnectGroupConfiguredTopologyCapability.php vendor/google/apiclien…TopologyCapability.php, class
InterconnectGroupPhysicalStructureMetros.php .../InterconnectGroupPhysicalStructureMetros.php, class
InterconnectGroupsCreateMembersRequest.php .../InterconnectGroupsCreateMembersRequest.php, class
InterconnectGroupPhysicalStructureMetrosFacilities.php vendor/google/apiclie…reMetrosFacilities.php, class
InterconnectGroupsCreateMembersInterconnectInput.php vendor/google/apicli…nterconnectInput.php, class
InterconnectGroupsGetOperationalStatusResponse.php vendor/google/apiclie…nalStatusResponse.php, class
InterconnectGroupPhysicalStructureMetrosFacilitiesZones.php vendor/google/apic…FacilitiesZones.php, class
InterconnectGroupConfiguredTopologyCapabilityIntendedCapabilityBlockers.php vendor/go…ockers.php, class
InterconnectGroup.php vendor/google/apiclient-services/src/Compute/InterconnectGroup.php, class
InterconnectGroups.php vendor/google/.../src/Compute/Resource/InterconnectGroups.php, class
InterconnectGroupConfigured.php vendor/google/.../src/Compute/InterconnectGroupConfigured.php, class
InterconnectGroupIntent.php vendor/google/.../src/Compute/InterconnectGroupIntent.php, class
InterconnectGroupInterconnect.php vendor/google/.../src/Compute/InterconnectGroupInterconnect.php, class
InterconnectGroupPhysicalStructure.php vendor/.../Compute/InterconnectGroupPhysicalStructure.php, class
InterconnectGroupsCreateMembers.php vendor/.../Compute/InterconnectGroupsCreateMembers.php, class
InterconnectGroupConfiguredTopologyCapability.php vendor/google/apiclien…TopologyCapability.php, class
InterconnectGroupPhysicalStructureMetros.php .../InterconnectGroupPhysicalStructureMetros.php, class
InterconnectGroupsCreateMembersRequest.php .../InterconnectGroupsCreateMembersRequest.php, class
InterconnectGroupPhysicalStructureMetrosFacilities.php vendor/google/apiclie…reMetrosFacilities.php, class
InterconnectGroupsCreateMembersInterconnectInput.php vendor/google/apicli…nterconnectInput.php, class
InterconnectGroupsGetOperationalStatusResponse.php vendor/google/apiclie…nalStatusResponse.php, class
InterconnectGroupPhysicalStructureMetrosFacilitiesZones.php vendor/google/apic…FacilitiesZones.php, class
InterconnectGroupConfiguredTopologyCapabilityIntendedCapabilityBlockers.php vendor/go…ockers.php, class
src/Compute/InterconnectGroup.php
Open In Right Split...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project Files","depth":2,"bounds":{"left":0.8298611,"top":0.25,"width":0.07430556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Preview","depth":2,"bounds":{"left":0.90416664,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Filter","depth":2,"bounds":{"left":0.9222222,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open in Find Tool Window","depth":2,"bounds":{"left":0.94027776,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextField","text":"interg","depth":1,"bounds":{"left":0.50555557,"top":0.29222223,"width":0.45277777,"height":0.032222223},"on_screen":true,"value":"interg","role_description":"text field","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"InterconnectGroup.php vendor/google/apiclient-services/src/Compute/InterconnectGroup.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.33666667,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroups.php vendor/google/.../src/Compute/Resource/InterconnectGroups.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.3611111,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupConfigured.php vendor/google/.../src/Compute/InterconnectGroupConfigured.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.38555557,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupIntent.php vendor/google/.../src/Compute/InterconnectGroupIntent.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.41,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupInterconnect.php vendor/google/.../src/Compute/InterconnectGroupInterconnect.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.43444446,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupPhysicalStructure.php vendor/.../Compute/InterconnectGroupPhysicalStructure.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.4588889,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupsCreateMembers.php vendor/.../Compute/InterconnectGroupsCreateMembers.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.48333332,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupConfiguredTopologyCapability.php vendor/google/apiclien…TopologyCapability.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.50777775,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupPhysicalStructureMetros.php .../InterconnectGroupPhysicalStructureMetros.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.5322222,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupsCreateMembersRequest.php .../InterconnectGroupsCreateMembersRequest.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.5566667,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupPhysicalStructureMetrosFacilities.php vendor/google/apiclie…reMetrosFacilities.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.58111113,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupsCreateMembersInterconnectInput.php vendor/google/apicli…nterconnectInput.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.60555553,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupsGetOperationalStatusResponse.php vendor/google/apiclie…nalStatusResponse.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.63,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupPhysicalStructureMetrosFacilitiesZones.php vendor/google/apic…FacilitiesZones.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.65444446,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupConfiguredTopologyCapabilityIntendedCapabilityBlockers.php vendor/go…ockers.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.6788889,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroup.php vendor/google/apiclient-services/src/Compute/InterconnectGroup.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.33666667,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroups.php vendor/google/.../src/Compute/Resource/InterconnectGroups.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.3611111,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupConfigured.php vendor/google/.../src/Compute/InterconnectGroupConfigured.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.38555557,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupIntent.php vendor/google/.../src/Compute/InterconnectGroupIntent.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.41,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupInterconnect.php vendor/google/.../src/Compute/InterconnectGroupInterconnect.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.43444446,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupPhysicalStructure.php vendor/.../Compute/InterconnectGroupPhysicalStructure.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.4588889,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupsCreateMembers.php vendor/.../Compute/InterconnectGroupsCreateMembers.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.48333332,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupConfiguredTopologyCapability.php vendor/google/apiclien…TopologyCapability.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.50777775,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupPhysicalStructureMetros.php .../InterconnectGroupPhysicalStructureMetros.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.5322222,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupsCreateMembersRequest.php .../InterconnectGroupsCreateMembersRequest.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.5566667,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupPhysicalStructureMetrosFacilities.php vendor/google/apiclie…reMetrosFacilities.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.58111113,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupsCreateMembersInterconnectInput.php vendor/google/apicli…nterconnectInput.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.60555553,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupsGetOperationalStatusResponse.php vendor/google/apiclie…nalStatusResponse.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.63,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupPhysicalStructureMetrosFacilitiesZones.php vendor/google/apic…FacilitiesZones.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.65444446,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"InterconnectGroupConfiguredTopologyCapabilityIntendedCapabilityBlockers.php vendor/go…ockers.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.6788889,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"src/Compute/InterconnectGroup.php","depth":1,"bounds":{"left":0.51319444,"top":0.74777776,"width":0.14444445,"height":0.018888889},"on_screen":true,"help_text":"src/Compute/InterconnectGroup.php","role_description":"text"},{"role":"AXLink","text":"Open In Right Split","depth":1,"bounds":{"left":0.8673611,"top":0.74777776,"width":0.08055556,"height":0.018888889},"on_screen":true,"role_description":"link","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
1586768157064059430
|
-5849935481565501195
|
visual_change
|
accessibility
|
NULL
|
Project Files
Preview
Filter
Open in Find Tool Win Project Files
Preview
Filter
Open in Find Tool Window
interg
InterconnectGroup.php vendor/google/apiclient-services/src/Compute/InterconnectGroup.php, class
InterconnectGroups.php vendor/google/.../src/Compute/Resource/InterconnectGroups.php, class
InterconnectGroupConfigured.php vendor/google/.../src/Compute/InterconnectGroupConfigured.php, class
InterconnectGroupIntent.php vendor/google/.../src/Compute/InterconnectGroupIntent.php, class
InterconnectGroupInterconnect.php vendor/google/.../src/Compute/InterconnectGroupInterconnect.php, class
InterconnectGroupPhysicalStructure.php vendor/.../Compute/InterconnectGroupPhysicalStructure.php, class
InterconnectGroupsCreateMembers.php vendor/.../Compute/InterconnectGroupsCreateMembers.php, class
InterconnectGroupConfiguredTopologyCapability.php vendor/google/apiclien…TopologyCapability.php, class
InterconnectGroupPhysicalStructureMetros.php .../InterconnectGroupPhysicalStructureMetros.php, class
InterconnectGroupsCreateMembersRequest.php .../InterconnectGroupsCreateMembersRequest.php, class
InterconnectGroupPhysicalStructureMetrosFacilities.php vendor/google/apiclie…reMetrosFacilities.php, class
InterconnectGroupsCreateMembersInterconnectInput.php vendor/google/apicli…nterconnectInput.php, class
InterconnectGroupsGetOperationalStatusResponse.php vendor/google/apiclie…nalStatusResponse.php, class
InterconnectGroupPhysicalStructureMetrosFacilitiesZones.php vendor/google/apic…FacilitiesZones.php, class
InterconnectGroupConfiguredTopologyCapabilityIntendedCapabilityBlockers.php vendor/go…ockers.php, class
InterconnectGroup.php vendor/google/apiclient-services/src/Compute/InterconnectGroup.php, class
InterconnectGroups.php vendor/google/.../src/Compute/Resource/InterconnectGroups.php, class
InterconnectGroupConfigured.php vendor/google/.../src/Compute/InterconnectGroupConfigured.php, class
InterconnectGroupIntent.php vendor/google/.../src/Compute/InterconnectGroupIntent.php, class
InterconnectGroupInterconnect.php vendor/google/.../src/Compute/InterconnectGroupInterconnect.php, class
InterconnectGroupPhysicalStructure.php vendor/.../Compute/InterconnectGroupPhysicalStructure.php, class
InterconnectGroupsCreateMembers.php vendor/.../Compute/InterconnectGroupsCreateMembers.php, class
InterconnectGroupConfiguredTopologyCapability.php vendor/google/apiclien…TopologyCapability.php, class
InterconnectGroupPhysicalStructureMetros.php .../InterconnectGroupPhysicalStructureMetros.php, class
InterconnectGroupsCreateMembersRequest.php .../InterconnectGroupsCreateMembersRequest.php, class
InterconnectGroupPhysicalStructureMetrosFacilities.php vendor/google/apiclie…reMetrosFacilities.php, class
InterconnectGroupsCreateMembersInterconnectInput.php vendor/google/apicli…nterconnectInput.php, class
InterconnectGroupsGetOperationalStatusResponse.php vendor/google/apiclie…nalStatusResponse.php, class
InterconnectGroupPhysicalStructureMetrosFacilitiesZones.php vendor/google/apic…FacilitiesZones.php, class
InterconnectGroupConfiguredTopologyCapabilityIntendedCapabilityBlockers.php vendor/go…ockers.php, class
src/Compute/InterconnectGroup.php
Open In Right Split...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45398
|
1625
|
40
|
2026-05-14T14:34:33.344050+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769273344_m1.jpg...
|
PhpStorm
|
faVsco.js – BullhornService.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
73
3
11
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Bullhorn;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\Provider\BullhornInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\ApplicationException;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\DomainException;
use Jiminny\Exceptions\HttpBadRequestException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\ServiceUnavailableException;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\UserRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
use Ramsey\Uuid\Uuid;
class BullhornService extends BaseService implements
BullhornInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const string ENTITY_LEAD = 'Candidate';
private const string ENTITY_OPPORTUNITY = 'JobOrder';
private const string ENTITY_ACCOUNT = 'ClientCorporation';
private const string ENTITY_CONTACT = 'ClientContact';
private const string ENTITY_ACTIVITY = 'Note';
private const array OPPORTUNITY_FIELDS = [
'id',
'owner',
'status',
'title',
'salary',
'salaryUnit',
'payRate',
'isOpen',
'employmentType',
'dateClosed',
'startDate',
'dateLastModified',
'dateAdded',
'clientCorporation',
'correlatedCustomText10', // currency
];
private const array TASK_FIELDS = [
'id',
'comments',
'dateAdded',
'dateLastModified',
'externalID',
'isDeleted',
'corporateUsers',
'clientContacts',
'commentingPerson',
'candidates',
'jobOrder',
'minutesSpent',
'action',
];
private const array LEAD_FIELDS = [
'id',
'name',
'owner',
'occupation',
'companyName',
'companyURL',
'mobile',
'phone',
'phone2',
'phone3',
'workPhone',
'status',
'address',
'dateAdded',
'dateLastModified',
];
private const array CONTACT_FIELDS = [
'id',
'name',
'occupation',
'mobile',
'phone',
'phone2',
'phone3',
'address',
'clientCorporation',
'dateAdded',
'owner',
];
private const array ACCOUNT_FIELDS = [
'id',
'name',
'phone',
'industryList',
'address',
'companyURL',
'dateAdded',
];
public function __construct(
BullhornClientInterface $client,
private readonly UserRepository $userRepository,
private readonly ProspectPhotoPathService $prospectPhotoPathService
) {
parent::__construct();
$this->client = $client;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);
}
public function getDisplayName(): string
{
return 'Bullhorn';
}
public function createTranscriptNotes(Activity $activity): void
{
// Not done until a customer requests it.
}
public function syncProfileFields(): void
{
$fieldTypes = [
'lead',
'account',
'contact',
'opportunity',
'task',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))
);
if (! empty($changedFields)) {
$fields = implode(',', $newFields);
Log::debug(
sprintf(
'%s fields changed from %s to: %s',
ucfirst($fieldType),
$this->profile->{$fieldType . '_fields'},
$fields,
),
);
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (\Exception $exception) {
\Log::error('No access to ' . $fieldType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
$this->profile->save();
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
//parent::OBJECT_ACCOUNT,
//parent::OBJECT_CONTACT,
//parent::OBJECT_OPPORTUNITY,
//parent::OBJECT_LEAD,
];
}
protected function getFields(string $crmObject): array
{
$fields = [];
foreach ($this->getObjectFields($crmObject) as $row) {
$fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];
}
return $fields;
}
private function getObjectFields(string $objectType): array
{
$entityType = $this->convertObjectTypeToResource($objectType);
return Cache::remember(
key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,
ttl: 60 * 60,
callback: function () use ($entityType) {
$entity = $this->client->get('meta/' . $entityType, [
'fields' => '*',
]);
return $entity['fields'];
},
);
}
public function getDefaultFields(string $activityType): array
{
$fields = [];
$defaultFields = FieldDefinitions::defaultFields();
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
return $fields;
}
public function getDefaultActivityField(string $activityType): Field
{
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'action',
'object_type' => $activityType,
])->first();
return $activityField;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
// We are not yet supporting follow-ups for this system.
return [];
}
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return $fieldValue;
}
public function syncField(Field $field): void
{
$resource = $this->convertObjectTypeToResource($field->object_type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => $field->crm_provider_id,
'meta' => 'full',
]);
$bhField = $entity['fields'][0];
$isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);
$description = null;
if (empty($bhField['description']) === false) {
$description = mb_strimwidth($bhField['description'], 0, 191);
}
$label = 'Unknown';
if (empty($bhField['label']) === false) {
$label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);
}
$field->length = $bhField['maxLength'] ?? null;
$field->is_mandatory = $isMandatory;
$field->description = $description;
$field->label = $label;
$field->type = $this->convertFieldType(
$bhField['dataType'] ?? null,
$bhField['dataSpecialization'] ?? null,
$bhField['inputType'] ?? null
);
$field->save();
if (empty($bhField['options']) === false) {
$values = [];
// Import all values.
foreach ($bhField['options'] as $i => $option) {
$values[] = [
'value' => $option['value'],
'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),
'sequence' => $i,
];
}
// Take the existing set of field values.
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
// For all current values, upsert the field.
$field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
$key = array_search($value['value'], $fieldsToPurge, false);
if ($key !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
}
}
public function importPicklistValues(Field $field): array
{
// Taken care of in syncField.
return [];
}
private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string
{
if ($type === null) {
return Field::TYPE_UNSUPPORTED;
}
$type = strtolower($type);
$specialization = strtolower($specialization);
$inputType = strtolower($inputType);
switch ($type) {
case 'boolean':
return Field::TYPE_BOOLEAN;
case 'integer':
switch ($specialization) {
case 'integer':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'bigdecimal':
switch ($specialization) {
case 'money':
return Field::TYPE_CURRENCY;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'double':
switch ($specialization) {
case 'float':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'timestamp':
switch ($specialization) {
case 'date':
return Field::TYPE_DATE;
case 'time':
return Field::TYPE_TIME;
case 'datetime':
return Field::TYPE_DATETIME;
default:
return Field::TYPE_DATE;
}
// no break
case 'string':
switch ($inputType) {
case 'textarea':
return Field::TYPE_TEXTAREA;
case 'select':
return Field::TYPE_PICKLIST;
default:
return Field::TYPE_TEXT;
}
// no break
default:
// This is not actually a supported field.
return Field::TYPE_UNSUPPORTED;
}
}
private function importContact($crmData): Contact
{
$account = $mobilePhone = $phone = $email = null;
if (empty($crmData['clientCorporation']) === false) {
$account = $this->team
->accounts()
->where('crm_provider_id', $crmData['clientCorporation']['id'])
->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
}
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => $crmData['name'],
'email' => $email,
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'title' => $crmData['occupation'],
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Contact::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importOpportunity($crmData): ?Opportunity
{
if ($crmData['clientCorporation']['id']) {
$account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
} else {
// If there is nothing to associate this with, don't import it.
return null;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$stage = $this->config->stages()
->where('crm_provider_id', $crmData['status'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);
}
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => mb_strimwidth($crmData['title'], 0, 128),
'value' => $crmData['salary'] ?? $crmData['payRate'],
'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),
'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),
'is_closed' => $crmData['isOpen'] !== true,
'is_won' => strtolower($crmData['status']) === 'placed',
'stage_id' => $stage->id,
'record_type_id' => null,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importAccount($crmData): Account
{
$countryCode = $domain = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$name = $crmData['name'] ?? 'Unknown';
if ($crmData['companyURL'] !== null) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$data = [
'team_id' => $this->team->id,
'user_id' => null,
'owner_id' => null,
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Account::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'country_code' => $countryCode,
'domain' => $domain,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importLead($crmData): ?Lead
{
// Get the current stage.
$stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);
}
// If we have no way of importing this, just return null :(
if ($stage === null) {
return null;
}
$countryCode = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$mobilePhone = $phone = $email = null;
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$company = 'Unknown';
if (empty($crmData['companyName']) === false) {
$companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];
$company = mb_strimwidth($companyName, 0, 191);
}
$domain = null;
if (empty($crmData['companyURL']) === false) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'company' => $company,
'domain' => $domain,
'name' => mb_strimwidth($crmData['name'], 0, 191),
'title' => mb_strimwidth($crmData['occupation'], 0, 128),
'email' => mb_strimwidth($email, 0, 80),
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Lead::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'stage_id' => $stage->id,
'country_code' => $countryCode,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
/**
* @throws ApplicationException
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhContacts = $this->client->get('search/ClientContact', $params);
foreach ($bhContacts['data'] as $bhContact) {
// Only sync if previously imported.
if ($this->hasContact($bhContact['id'])) {
$this->importContact($bhContact);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategies = $strategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
$total = 0;
$count = 0;
$offset = 0;
try {
$bhOpportunities = [];
foreach ($strategies as $syncStrategy) {
$opportunitiesData = $syncStrategy->fetchOpportunities($parameters);
$total = (int) ($opportunitiesData['total'] ?? 0);
$count = (int) ($opportunitiesData['count'] ?? 0);
$offset = (int) ($opportunitiesData['start'] ?? 0);
$bhOpportunities[] = $opportunitiesData['data'] ?? [];
}
$bhOpportunities = array_merge(...$bhOpportunities);
foreach ($bhOpportunities as $bhOpportunity) {
$this->importOpportunity($bhOpportunity);
$syncCount++;
}
} catch (\Exception $exception) {
$this->logger->info('Failed to sync opportunities', [
'params' => $parameters,
'exception' => $exception->getMessage(),
]);
}
// only log if there are one sync strategy
if (count($strategies) === 1 && $total > $count + $offset) {
$this->logger->info('[Bullhorn] Sync Opportunities - count warning', [
'team_id' => $this->team->getId(),
'total' => $total,
'count' => $count,
'offset' => $offset,
]);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhAccounts = $this->client->get('search/ClientCorporation', $params);
foreach ($bhAccounts['data'] as $bhAccount) {
// Only sync if previously imported.
if ($this->hasAccount($bhAccount['id'])) {
$this->importAccount($bhAccount);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhLeads = $this->client->get('search/Candidate', $params);
if ($bhLeads === null) {
return $syncCount;
}
foreach ($bhLeads['data'] as $bhLead) {
// Only sync if previously imported.
if ($this->hasLead($bhLead['id'])) {
$this->importLead($bhLead);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncContact(string $crmId): ?Contact
{
try {
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importContact($data['data']);
}
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategy = $strategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
try {
$data = $strategy->fetchOpportunities(['crm_id' => $crmId]);
} catch (HttpNotFoundException $exception) {
$this->logger->info('[Bullhorn] Opportunity not found', [
'crm_id' => $crmId,
'reason' => $exception->getMessage(),
]);
}
return $this->importOpportunity($data['data'] ?? []);
}
public function syncAccount(string $crmId): ?Account
{
try {
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importAccount($data['data']);
}
public function syncLead(string $crmId): ?Lead
{
try {
$data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importLead($data['data']);
}
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$missingStage = null;
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
foreach ($types as $type) {
$resource = $this->convertObjectTypeToResource($type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => 'status',
'meta' => 'full',
]);
$missingStage = null;
if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {
throw new \UnexpectedValueException('Invalid response from Bullhorn API');
}
// Upsert all stages for the team.
foreach ($entity['fields'][0]['options'] as $i => $option) {
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $option['value'],
'type' => $type,
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($option['value'], 0, 50),
'label' => mb_strimwidth($option['label'], 0, 191),
'sequence' => $i,
'is_selectable' => 1,
]);
if ($missingStageName && $missingStageName === $option['value']) {
$missingStage = $stage;
}
}
if ($missingStageName && $missingStage === null) {
// If they requested a stage that still doesn't exist, it must be inactive so lazy create it.
$missingStage = $this->config->stages()->create([
'team_id' => $this->team->id,
'crm_provider_id' => Uuid::uuid4(),
'name' => mb_strimwidth($missingStageName, 0, 50),
'label' => mb_strimwidth($missingStageName, 0, 191),
'type' => $type,
'sequence' => 0,
'is_selectable' => 0,
]);
}
}
return $missingStage;
}
public function syncOrganization(): void
{
// There appears to be nothing we can sync/map to.
}
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$data = \Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {
$result = [];
try {
$objects = $this->client->get('find', [
'query' => $name,
'meta' => 'basic',
'countPerEntity' => $count,
]);
} catch (\GuzzleHttp\Exception\ServerException $exception) {
throw new ServiceUnavailableException($exception->getMessage());
}
foreach ($objects['data'] as $object) {
try {
$prospectType = $this->convertResourceToObjectType($object['entityType']);
} catch (\UnexpectedValueException $exception) {
// We don't support this, so skip it.
continue;
}
$record = [
'crmId' => $object['entityId'],
'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),
'prospectType' => $prospectType,
'phoneNumbers' => [],
];
// Unfortunately we need to go and query each entity itself to get the data we need.
switch ($object['entityType']) {
case self::ENTITY_ACCOUNT:
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['industry'] = $entity['industryList'];
if (empty($entity['phone']) === false) {
$record['phoneNumbers'][] = [
'number' => $entity['phone'],
'nationalFormat' => phone_national(null, $entity['phone']),
'type' => 'phone',
];
}
break;
case self::ENTITY_CONTACT:
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
case self::ENTITY_LEAD:
$bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);
$entity = $bhData['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['companyName'];
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
default:
// We are not interested in this entity type so skip it.
continue 2;
}
$result[] = $record;
}
return $result;
});
return $data;
}
public function getClient(): BullhornClientInterface
{
return $this->client;
}
private function getFieldsAsString(array $fields)
{
return implode(', ', $fields);
}
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),
];
$onlyOpen = true;
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort'] = '-dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort'] = '+dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
$onlyOpen = false;
}
if ($onlyOpen) {
$where .= ' AND isOpen: true';
}
$params['query'] = $where;
$bhOpportunities = $this->client->get('search/JobOrder', $params);
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
foreach ($bhOpportunities['data'] as $bhOpportunity) {
$stage = $this->config
->stages()
->where('crm_provider_id', $bhOpportunity['status'])
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);
}
$record = [
'crmId' => $bhOpportunity['id'],
'name' => $bhOpportunity['title'],
'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),
'won' => strtolower($bhOpportunity['status']) === 'placed',
'closed' => $bhOpportunity['isOpen'] !== true,
'stage' => [
'id' => $stage->id_string,
'name' => $stage->name,
],
'recordType' => [],
];
if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = [];
// For now it has not been agreed on how to implement this e.g. appointments or tasks?
return [];
if ($objectType === 'account' && $opportunityId === null) {
// You cannot attach tasks to only accounts.
return [];
}
// Query should default to any open task.
$where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;
// If we are also going to check on a specific job order, set that up.
if ($opportunityId) {
$where .= ' OR JobOrder: ' . (int) $opportunityId;
}
$where .= ')';
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::TASK_FIELDS),
'query' => $where,
];
$bhTasks = $this->client->get('search/Task', $params);
foreach ($bhTasks['data'] as $bhTask) {
$data[] = [
'crmId' => $bhTask['id'],
'subject' => $bhTask['subject'],
'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),
'type' => null,
];
}
return $data;
}
/**
* @url [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] CrmException
* @throws DomainException
*/
private function buildNotePayload(Activity $activity): Activity
{
if ($activity->hasActivityType() === false) {
throw new DomainException('[Bullhorn] No activity type assigned');
}
$action = $this->getCrmType($activity->getActivityType());
if ($action === null) {
throw new DomainException('[Bullhorn] No mapped CRM type for "' . $activity->category->name . '"');
}
if ($activity->lead_id === null && $activity->contact_id === null) {
throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');
}
$payload = [
'comments' => $this->generateActivityDescription($activity),
'action' => $action->value,
'commentingPerson' => [
'id' => (int) $this->profile->crm_provider_id,
'type' => 'CorporateUser',
],
'externalID' => $activity->id_string,
'minutesSpent' => $activity->duration,
'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),
];
if ($activity->lead_id) {
$payload['personReference'] = [
'id' => (int) $activity->lead->crm_provider_id,
'type' => 'Candidate',
];
}
if ($activity->contact_id) {
$payload['personReference'] = [
'id' => (int) $activity->contact->crm_provider_id,
'type' => 'ClientContact',
];
}
if ($activity->opportunity_id) {
$payload['jobOrders'] = [
'replaceAll' => [
(int) $activity->opportunity->crm_provider_id,
],
];
}
$bhActivity = $this->client->put('entity/Note', $payload);
$activity->crm_provider_id = $bhActivity['changedEntityId'];
$activity->save();
return $activity;
}
private function generateActivityDescription(Activity $activity): string
{
$description = '';
switch ($activity->type) {
case Activity::TYPE_SOFTPHONE:
case Activity::TYPE_SOFTPHONE_INBOUND:
case Activity::TYPE_CONFERENCE:
if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
// Dialer calls have no native field for the subject.
if ($activity->title) {
$description .= sprintf(
'<p><span style="font-size: 16px; line-height: 19.2px;">%s</span></p>',
$activity->title,
);
}
// Conference meetings log duration into a distinct field, so log this in the main text.
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Call Duration: %s</span></p>',
$activity->duration_for_humans,
);
// Tell them which number was dialed.
if ($activity->to) {
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Dialed: %s</span></p>',
$activity->to->phone_number,
);
}
$description .= '<p></p>';
}
if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.6645833,"top":0.027777778,"width":0.15902779,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.82361114,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.8472222,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.87083334,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.9291667,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9527778,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9763889,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.7326389,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"73","depth":4,"bounds":{"left":0.7534722,"top":0.3122222,"width":0.020833334,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.77847224,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"11","depth":4,"bounds":{"left":0.79930556,"top":0.3122222,"width":0.01875,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.8215278,"top":0.31,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.8368056,"top":0.31,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Bullhorn;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\BullhornInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\ApplicationException;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\DomainException;\nuse Jiminny\\Exceptions\\HttpBadRequestException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\ServiceUnavailableException;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\UserRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\nuse Ramsey\\Uuid\\Uuid;\n\nclass BullhornService extends BaseService implements\n BullhornInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const string ENTITY_LEAD = 'Candidate';\n private const string ENTITY_OPPORTUNITY = 'JobOrder';\n private const string ENTITY_ACCOUNT = 'ClientCorporation';\n private const string ENTITY_CONTACT = 'ClientContact';\n private const string ENTITY_ACTIVITY = 'Note';\n\n private const array OPPORTUNITY_FIELDS = [\n 'id',\n 'owner',\n 'status',\n 'title',\n 'salary',\n 'salaryUnit',\n 'payRate',\n 'isOpen',\n 'employmentType',\n 'dateClosed',\n 'startDate',\n 'dateLastModified',\n 'dateAdded',\n 'clientCorporation',\n 'correlatedCustomText10', // currency\n ];\n\n private const array TASK_FIELDS = [\n 'id',\n 'comments',\n 'dateAdded',\n 'dateLastModified',\n 'externalID',\n 'isDeleted',\n 'corporateUsers',\n 'clientContacts',\n 'commentingPerson',\n 'candidates',\n 'jobOrder',\n 'minutesSpent',\n 'action',\n ];\n\n private const array LEAD_FIELDS = [\n 'id',\n 'name',\n 'owner',\n 'occupation',\n 'companyName',\n 'companyURL',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'workPhone',\n 'status',\n 'address',\n 'dateAdded',\n 'dateLastModified',\n ];\n\n private const array CONTACT_FIELDS = [\n 'id',\n 'name',\n 'occupation',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'address',\n 'clientCorporation',\n 'dateAdded',\n 'owner',\n ];\n\n private const array ACCOUNT_FIELDS = [\n 'id',\n 'name',\n 'phone',\n 'industryList',\n 'address',\n 'companyURL',\n 'dateAdded',\n ];\n\n public function __construct(\n BullhornClientInterface $client,\n private readonly UserRepository $userRepository,\n private readonly ProspectPhotoPathService $prospectPhotoPathService\n ) {\n parent::__construct();\n\n $this->client = $client;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);\n }\n\n public function getDisplayName(): string\n {\n return 'Bullhorn';\n }\n\n public function createTranscriptNotes(Activity $activity): void\n {\n // Not done until a customer requests it.\n }\n\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n 'task',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))\n );\n\n if (! empty($changedFields)) {\n $fields = implode(',', $newFields);\n Log::debug(\n sprintf(\n '%s fields changed from %s to: %s',\n ucfirst($fieldType),\n $this->profile->{$fieldType . '_fields'},\n $fields,\n ),\n );\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (\\Exception $exception) {\n \\Log::error('No access to ' . $fieldType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n //parent::OBJECT_ACCOUNT,\n //parent::OBJECT_CONTACT,\n //parent::OBJECT_OPPORTUNITY,\n //parent::OBJECT_LEAD,\n ];\n }\n\n protected function getFields(string $crmObject): array\n {\n $fields = [];\n foreach ($this->getObjectFields($crmObject) as $row) {\n $fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];\n }\n\n return $fields;\n }\n\n private function getObjectFields(string $objectType): array\n {\n $entityType = $this->convertObjectTypeToResource($objectType);\n\n return Cache::remember(\n key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,\n ttl: 60 * 60,\n callback: function () use ($entityType) {\n $entity = $this->client->get('meta/' . $entityType, [\n 'fields' => '*',\n ]);\n\n return $entity['fields'];\n },\n );\n }\n\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n $defaultFields = FieldDefinitions::defaultFields();\n\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n\n return $fields;\n }\n\n public function getDefaultActivityField(string $activityType): Field\n {\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'action',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n // We are not yet supporting follow-ups for this system.\n return [];\n }\n\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return $fieldValue;\n }\n\n public function syncField(Field $field): void\n {\n $resource = $this->convertObjectTypeToResource($field->object_type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => $field->crm_provider_id,\n 'meta' => 'full',\n ]);\n\n $bhField = $entity['fields'][0];\n\n $isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);\n $description = null;\n if (empty($bhField['description']) === false) {\n $description = mb_strimwidth($bhField['description'], 0, 191);\n }\n\n $label = 'Unknown';\n if (empty($bhField['label']) === false) {\n $label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);\n }\n\n $field->length = $bhField['maxLength'] ?? null;\n $field->is_mandatory = $isMandatory;\n $field->description = $description;\n $field->label = $label;\n $field->type = $this->convertFieldType(\n $bhField['dataType'] ?? null,\n $bhField['dataSpecialization'] ?? null,\n $bhField['inputType'] ?? null\n );\n\n $field->save();\n\n if (empty($bhField['options']) === false) {\n $values = [];\n\n // Import all values.\n foreach ($bhField['options'] as $i => $option) {\n $values[] = [\n 'value' => $option['value'],\n 'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),\n 'sequence' => $i,\n ];\n }\n\n // Take the existing set of field values.\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n // For all current values, upsert the field.\n $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n $key = array_search($value['value'], $fieldsToPurge, false);\n if ($key !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n }\n }\n\n public function importPicklistValues(Field $field): array\n {\n // Taken care of in syncField.\n return [];\n }\n\n private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string\n {\n if ($type === null) {\n return Field::TYPE_UNSUPPORTED;\n }\n\n $type = strtolower($type);\n $specialization = strtolower($specialization);\n $inputType = strtolower($inputType);\n\n switch ($type) {\n case 'boolean':\n return Field::TYPE_BOOLEAN;\n\n case 'integer':\n switch ($specialization) {\n case 'integer':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'bigdecimal':\n switch ($specialization) {\n case 'money':\n return Field::TYPE_CURRENCY;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'double':\n switch ($specialization) {\n case 'float':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'timestamp':\n switch ($specialization) {\n case 'date':\n return Field::TYPE_DATE;\n case 'time':\n return Field::TYPE_TIME;\n case 'datetime':\n return Field::TYPE_DATETIME;\n default:\n return Field::TYPE_DATE;\n }\n\n // no break\n case 'string':\n switch ($inputType) {\n case 'textarea':\n return Field::TYPE_TEXTAREA;\n case 'select':\n return Field::TYPE_PICKLIST;\n default:\n return Field::TYPE_TEXT;\n }\n\n // no break\n default:\n // This is not actually a supported field.\n return Field::TYPE_UNSUPPORTED;\n }\n }\n\n private function importContact($crmData): Contact\n {\n $account = $mobilePhone = $phone = $email = null;\n if (empty($crmData['clientCorporation']) === false) {\n $account = $this->team\n ->accounts()\n ->where('crm_provider_id', $crmData['clientCorporation']['id'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n }\n\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => $crmData['name'],\n 'email' => $email,\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'title' => $crmData['occupation'],\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Contact::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n if ($crmData['clientCorporation']['id']) {\n $account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n } else {\n // If there is nothing to associate this with, don't import it.\n return null;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $stage = $this->config->stages()\n ->where('crm_provider_id', $crmData['status'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => mb_strimwidth($crmData['title'], 0, 128),\n 'value' => $crmData['salary'] ?? $crmData['payRate'],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),\n 'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),\n 'is_closed' => $crmData['isOpen'] !== true,\n 'is_won' => strtolower($crmData['status']) === 'placed',\n 'stage_id' => $stage->id,\n 'record_type_id' => null,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importAccount($crmData): Account\n {\n $countryCode = $domain = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $name = $crmData['name'] ?? 'Unknown';\n\n if ($crmData['companyURL'] !== null) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => null,\n 'owner_id' => null,\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Account::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'country_code' => $countryCode,\n 'domain' => $domain,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importLead($crmData): ?Lead\n {\n // Get the current stage.\n $stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);\n }\n\n // If we have no way of importing this, just return null :(\n if ($stage === null) {\n return null;\n }\n\n $countryCode = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $mobilePhone = $phone = $email = null;\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $company = 'Unknown';\n if (empty($crmData['companyName']) === false) {\n $companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];\n $company = mb_strimwidth($companyName, 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['companyURL']) === false) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'company' => $company,\n 'domain' => $domain,\n 'name' => mb_strimwidth($crmData['name'], 0, 191),\n 'title' => mb_strimwidth($crmData['occupation'], 0, 128),\n 'email' => mb_strimwidth($email, 0, 80),\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Lead::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'stage_id' => $stage->id,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhContacts = $this->client->get('search/ClientContact', $params);\n\n foreach ($bhContacts['data'] as $bhContact) {\n // Only sync if previously imported.\n if ($this->hasContact($bhContact['id'])) {\n $this->importContact($bhContact);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategies = $strategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n $total = 0;\n $count = 0;\n $offset = 0;\n\n try {\n $bhOpportunities = [];\n foreach ($strategies as $syncStrategy) {\n $opportunitiesData = $syncStrategy->fetchOpportunities($parameters);\n $total = (int) ($opportunitiesData['total'] ?? 0);\n $count = (int) ($opportunitiesData['count'] ?? 0);\n $offset = (int) ($opportunitiesData['start'] ?? 0);\n $bhOpportunities[] = $opportunitiesData['data'] ?? [];\n }\n\n $bhOpportunities = array_merge(...$bhOpportunities);\n\n foreach ($bhOpportunities as $bhOpportunity) {\n $this->importOpportunity($bhOpportunity);\n $syncCount++;\n }\n } catch (\\Exception $exception) {\n $this->logger->info('Failed to sync opportunities', [\n 'params' => $parameters,\n 'exception' => $exception->getMessage(),\n ]);\n }\n\n // only log if there are one sync strategy\n if (count($strategies) === 1 && $total > $count + $offset) {\n $this->logger->info('[Bullhorn] Sync Opportunities - count warning', [\n 'team_id' => $this->team->getId(),\n 'total' => $total,\n 'count' => $count,\n 'offset' => $offset,\n ]);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhAccounts = $this->client->get('search/ClientCorporation', $params);\n\n foreach ($bhAccounts['data'] as $bhAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($bhAccount['id'])) {\n $this->importAccount($bhAccount);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhLeads = $this->client->get('search/Candidate', $params);\n if ($bhLeads === null) {\n return $syncCount;\n }\n\n foreach ($bhLeads['data'] as $bhLead) {\n // Only sync if previously imported.\n if ($this->hasLead($bhLead['id'])) {\n $this->importLead($bhLead);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n\n public function syncContact(string $crmId): ?Contact\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importContact($data['data']);\n }\n\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategy = $strategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n try {\n $data = $strategy->fetchOpportunities(['crm_id' => $crmId]);\n } catch (HttpNotFoundException $exception) {\n $this->logger->info('[Bullhorn] Opportunity not found', [\n 'crm_id' => $crmId,\n 'reason' => $exception->getMessage(),\n ]);\n }\n\n return $this->importOpportunity($data['data'] ?? []);\n }\n\n public function syncAccount(string $crmId): ?Account\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importAccount($data['data']);\n }\n\n public function syncLead(string $crmId): ?Lead\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importLead($data['data']);\n }\n\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $missingStage = null;\n\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n\n foreach ($types as $type) {\n $resource = $this->convertObjectTypeToResource($type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => 'status',\n 'meta' => 'full',\n ]);\n\n $missingStage = null;\n\n if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {\n throw new \\UnexpectedValueException('Invalid response from Bullhorn API');\n }\n\n // Upsert all stages for the team.\n foreach ($entity['fields'][0]['options'] as $i => $option) {\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $option['value'],\n 'type' => $type,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($option['value'], 0, 50),\n 'label' => mb_strimwidth($option['label'], 0, 191),\n 'sequence' => $i,\n 'is_selectable' => 1,\n ]);\n\n if ($missingStageName && $missingStageName === $option['value']) {\n $missingStage = $stage;\n }\n }\n\n if ($missingStageName && $missingStage === null) {\n // If they requested a stage that still doesn't exist, it must be inactive so lazy create it.\n $missingStage = $this->config->stages()->create([\n 'team_id' => $this->team->id,\n 'crm_provider_id' => Uuid::uuid4(),\n 'name' => mb_strimwidth($missingStageName, 0, 50),\n 'label' => mb_strimwidth($missingStageName, 0, 191),\n 'type' => $type,\n 'sequence' => 0,\n 'is_selectable' => 0,\n ]);\n }\n }\n\n return $missingStage;\n }\n\n public function syncOrganization(): void\n {\n // There appears to be nothing we can sync/map to.\n }\n\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $data = \\Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {\n $result = [];\n\n try {\n $objects = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => $count,\n ]);\n } catch (\\GuzzleHttp\\Exception\\ServerException $exception) {\n throw new ServiceUnavailableException($exception->getMessage());\n }\n\n foreach ($objects['data'] as $object) {\n try {\n $prospectType = $this->convertResourceToObjectType($object['entityType']);\n } catch (\\UnexpectedValueException $exception) {\n // We don't support this, so skip it.\n continue;\n }\n\n $record = [\n 'crmId' => $object['entityId'],\n 'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),\n 'prospectType' => $prospectType,\n 'phoneNumbers' => [],\n ];\n\n // Unfortunately we need to go and query each entity itself to get the data we need.\n switch ($object['entityType']) {\n case self::ENTITY_ACCOUNT:\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['industry'] = $entity['industryList'];\n if (empty($entity['phone']) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity['phone'],\n 'nationalFormat' => phone_national(null, $entity['phone']),\n 'type' => 'phone',\n ];\n }\n\n break;\n\n case self::ENTITY_CONTACT:\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n case self::ENTITY_LEAD:\n $bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);\n $entity = $bhData['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['companyName'];\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n default:\n // We are not interested in this entity type so skip it.\n continue 2;\n }\n\n $result[] = $record;\n }\n\n return $result;\n });\n\n return $data;\n }\n\n public function getClient(): BullhornClientInterface\n {\n return $this->client;\n }\n\n private function getFieldsAsString(array $fields)\n {\n return implode(', ', $fields);\n }\n\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),\n ];\n\n $onlyOpen = true;\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort'] = '-dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort'] = '+dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n $onlyOpen = false;\n }\n\n if ($onlyOpen) {\n $where .= ' AND isOpen: true';\n }\n\n $params['query'] = $where;\n\n $bhOpportunities = $this->client->get('search/JobOrder', $params);\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n foreach ($bhOpportunities['data'] as $bhOpportunity) {\n $stage = $this->config\n ->stages()\n ->where('crm_provider_id', $bhOpportunity['status'])\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);\n }\n\n $record = [\n 'crmId' => $bhOpportunity['id'],\n 'name' => $bhOpportunity['title'],\n 'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),\n 'won' => strtolower($bhOpportunity['status']) === 'placed',\n 'closed' => $bhOpportunity['isOpen'] !== true,\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n 'recordType' => [],\n ];\n\n if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = [];\n\n // For now it has not been agreed on how to implement this e.g. appointments or tasks?\n return [];\n\n if ($objectType === 'account' && $opportunityId === null) {\n // You cannot attach tasks to only accounts.\n return [];\n }\n\n // Query should default to any open task.\n $where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;\n\n // If we are also going to check on a specific job order, set that up.\n if ($opportunityId) {\n $where .= ' OR JobOrder: ' . (int) $opportunityId;\n }\n\n $where .= ')';\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => $where,\n ];\n\n $bhTasks = $this->client->get('search/Task', $params);\n\n foreach ($bhTasks['data'] as $bhTask) {\n $data[] = [\n 'crmId' => $bhTask['id'],\n 'subject' => $bhTask['subject'],\n 'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),\n 'type' => null,\n ];\n }\n\n return $data;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * ?Lead,\n * ?Account,\n * ?Opportunity,\n * ?Contact,\n * ?Stage,\n * ?string\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $bhObject = $this->client->get('find', [\n 'query' => $email,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember === false) {\n $bhObject = $this->client->get('find', [\n 'query' => $rawPhoneNumber ?? $phone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n if (empty($bhObject['data'])) {\n $nationalPhone = phone_national(null, $rawPhoneNumber ?? $phone);\n $formattedPhone = ltrim($nationalPhone, '+0');\n $bhObject = $this->client->get('find', [\n 'query' => $formattedPhone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n }\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n return null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 3) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = \\Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n $bhObject = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->team->getId() . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n public function saveActivity(Activity $activity): Activity\n {\n\n if ($activity->hasCrmProviderId()) {\n return $activity;\n }\n\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildNotePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n /**\n * @throws CrmException\n * @throws DomainException\n */\n private function buildNotePayload(Activity $activity): Activity\n {\n if ($activity->hasActivityType() === false) {\n throw new DomainException('[Bullhorn] No activity type assigned');\n }\n\n $action = $this->getCrmType($activity->getActivityType());\n if ($action === null) {\n throw new DomainException('[Bullhorn] No mapped CRM type for \"' . $activity->category->name . '\"');\n }\n\n if ($activity->lead_id === null && $activity->contact_id === null) {\n throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');\n }\n\n $payload = [\n 'comments' => $this->generateActivityDescription($activity),\n 'action' => $action->value,\n 'commentingPerson' => [\n 'id' => (int) $this->profile->crm_provider_id,\n 'type' => 'CorporateUser',\n ],\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n 'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),\n ];\n\n if ($activity->lead_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->lead->crm_provider_id,\n 'type' => 'Candidate',\n ];\n }\n\n if ($activity->contact_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->contact->crm_provider_id,\n 'type' => 'ClientContact',\n ];\n }\n\n if ($activity->opportunity_id) {\n $payload['jobOrders'] = [\n 'replaceAll' => [\n (int) $activity->opportunity->crm_provider_id,\n ],\n ];\n }\n\n $bhActivity = $this->client->put('entity/Note', $payload);\n\n $activity->crm_provider_id = $bhActivity['changedEntityId'];\n $activity->save();\n\n return $activity;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = '';\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: %s</span></p>',\n $activity->to->phone_number,\n );\n }\n $description .= '<p></p>';\n }\n\n if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: %s</span></p>',\n $activity->from->phone_number,\n );\n $description .= '<p></p>';\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span>'\n . '</p>';\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span>'\n . '</p>';\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= sprintf(\n '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . '<a href=\"%s\" target=\"_blank\">'\n . 'Review in Jiminny'\n . '</a>'\n . '️</span>'\n . '</p>',\n $playbackUrl,\n );\n }\n\n if ($activity->isTypeConference()) {\n $description .= '<p><strong>Attendees</strong></p><ul>';\n\n // Only include participants that joined.\n $participants = $activity->participants()->ghost(false)->whereNotNull('enter_time')->get();\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->name) {\n $attendee .= $participant->name;\n if ($participant->phone_number) {\n $attendee .= ' (' . $participant->phone_number . ')';\n } elseif ($participant->email) {\n $attendee .= ' (' . $participant->email . ')';\n }\n } else {\n $attendee .= $participant->phone_number;\n }\n\n if ($participant->is_ghost) {\n $attendee .= ' <strong>coach</coach>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $description .= $attendee . '</li>';\n }\n $description .= '</ul>';\n }\n\n if (count($activity->notes) > 0) {\n $description .= '<p><strong>Notes</strong></p>';\n\n foreach ($activity->notes as $note) {\n $time = ($note->time > 3600) ? gmdate('H:i:s', $note->time) : gmdate('i:s', $note->time);\n $description .= '<p>' . $time . ' ' . $note->note . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n if ($activity->summary) {\n $description .= '<p><strong>Summary</strong></p><p>' . $activity->summary . '</p><p></p>';\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n // Use Rich-text formatting.\n $description = sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>%s</strong></span></p>',\n $activity->title,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->description,\n );\n\n break;\n }\n\n return $description;\n }\n\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // Not yet required by current customers.\n return null;\n }\n\n public function updateStage($crmObject, Stage $stage): void\n {\n $objectId = $crmObject->crm_provider_id;\n\n $this->updateRecord($stage->type, $objectId, ['status' => $stage->crm_provider_id]);\n }\n\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $start = 0;\n $payload = [\n 'fields' => 'id,email',\n 'where' => 'isDeleted=false',\n 'count' => 500,\n ];\n\n $payload['start'] = $start;\n $profiles = $this->client->get('query/CorporateUser', $payload);\n\n foreach ($profiles['data'] as $profile) {\n if (empty($profile['email'])) {\n continue;\n }\n\n $user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);\n\n // Only import profiles for users we have locally.\n if ($user) {\n $profile = $user->crmProfile()->updateOrCreate([\n 'crm_configuration_id' => $this->config->id,\n 'crm_provider_id' => $profile['id'],\n ]);\n\n if ($userToSearch && $userToSearch->id === $user->id) {\n return $profile;\n }\n }\n }\n\n return null;\n }\n\n protected function convertCrmData(array $entities, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n $mappedEntities = [];\n foreach ($entities as $entity) {\n if (in_array($entity['entityType'], [self::ENTITY_LEAD, self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n $mappedEntities[] = $entity;\n }\n }\n\n // If there is only one match, sync the data and return the object(s).\n if (count($mappedEntities) === 1) {\n $entity = $mappedEntities[0];\n\n if ($entity['entityType'] === self::ENTITY_LEAD) {\n $lead = $this->syncLead($entity['entityId']);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } elseif (in_array($entity['entityType'], [self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n if ($entity['entityType'] === self::ENTITY_CONTACT) {\n $contact = $this->syncContact($entity['entityId']);\n $account = $contact->account;\n } else {\n $account = $this->syncAccount($entity['entityId']);\n }\n\n if ($contact?->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $bhOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact?->crm_provider_id,\n $userId,\n );\n\n // Take the first opportunity, which will be ordered as priority based on their settings.\n if (! empty($bhOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($bhOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n } catch (Exception) {\n // Nothing to see here.\n }\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n // There doesn't appear to be a way to deeplink to anything on https://app.bullhornstaffing.com.\n return null;\n }\n\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $this->client->post('entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId, $data);\n }\n\n public function getRecord(string $objectType, string $objectId, array $fields = ['id']): array\n {\n return $this->client->get(\n url: 'entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId,\n data: ['fields' => $this->getFieldsAsString($fields)],\n );\n }\n\n private function convertObjectTypeToResource(string $objectType)\n {\n switch ($objectType) {\n case FieldData::OBJECT_OPPORTUNITY:\n return self::ENTITY_OPPORTUNITY;\n\n case FieldData::OBJECT_CONTACT:\n return self::ENTITY_CONTACT;\n\n case FieldData::OBJECT_LEAD:\n return self::ENTITY_LEAD;\n\n case FieldData::OBJECT_ACCOUNT:\n return self::ENTITY_ACCOUNT;\n\n case FieldData::OBJECT_TASK:\n return self::ENTITY_ACTIVITY;\n\n default:\n throw new \\UnexpectedValueException('Unsupported object type \"' . $objectType . '\"');\n }\n }\n\n private function convertResourceToObjectType(string $resource): string\n {\n switch ($resource) {\n case self::ENTITY_OPPORTUNITY:\n return FieldData::OBJECT_OPPORTUNITY;\n\n case self::ENTITY_CONTACT:\n return FieldData::OBJECT_CONTACT;\n\n case self::ENTITY_LEAD:\n return FieldData::OBJECT_LEAD;\n\n case self::ENTITY_ACCOUNT:\n return FieldData::OBJECT_ACCOUNT;\n\n case self::ENTITY_ACTIVITY:\n return FieldData::OBJECT_TASK;\n\n default:\n throw new \\UnexpectedValueException('Unsupported resource \"' . $resource . '\"');\n }\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n // We need to know when it started to determine when to look for related activity.\n if ($activity->hasActualStartTime() === false) {\n return null;\n }\n\n try {\n $bhNote = $this->fetchRelatedActivity($activity);\n if (empty($bhNote)) {\n $this->logger->info('[Bullhorn] No related activity found', [\n 'activity' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $activityType = $this->getPlaybookCategory($this->getPlaybook($activity->user), $bhNote['action']);\n $comments = $bhNote['comments'] . '<br />//<br />' . $this->generateActivityDescription($activity);\n // Now update the Note to contain our data.\n $payload = [\n 'comments' => $comments,\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n ];\n\n $this->logger->info('[Bullhorn] updating related activity', [\n 'activity' => $activity->getUuid(),\n 'activityType' => $activityType->id ?? null,\n ]);\n\n $this->client->post('entity/Note/' . $bhNote['id'], $payload);\n\n $playbookCategoryId = null;\n if ($activity->getCategory() !== null) {\n $playbookCategoryId = $activity->getCategory()->getId();\n }\n\n // Update our activity to reflect the remote data.\n $activity->update([\n 'crm_provider_id' => $bhNote['id'],\n 'summary' => $bhNote['comments'],\n 'playbook_category_id' => $activityType->id ?? $playbookCategoryId,\n ]);\n\n return $activity;\n } catch (\\Exception $exception) {\n \\Sentry::captureException($exception);\n\n throw $exception;\n }\n }\n\n /**\n * Returns the most recently modified note within time range (if any).\n *\n * @return array A Note record from Bullhorn.\n */\n public function fetchRelatedActivity(Activity $activity): array\n {\n $from = $activity->hasScheduledStartTime()\n ? $activity->getScheduledStartTime()\n : $activity->getActualStartTime();\n $to = $activity->hasActualEndTime()\n ? $activity->getActualEndTime()?->addMinutes(15)\n : $from?->clone()->addMinutes(15);\n\n $filterStatements = [\n 'isDeleted: false',\n '*:* -externalID:[* TO *]', // externalID should be null e.g. we did not already relate it.\n sprintf('commentingPerson: %d', (int) $this->profile->crm_provider_id),\n ];\n\n /**\n * @XXX: Bullhorn does not specify the time zone in their docs. I've found a forum thread in which someone from\n * staff asserts it's UTC, however in my field test I've found it to be GMT-0300 (USA east coast).\n * To make the code immune to such glitches we will add 24h to start/end boundaries and will filter out\n * any excess items in code\n */\n $filterStatements[] = sprintf(\n 'dateLastModified:[%s TO %s]',\n $from?->clone()->subHours(24)->format('YmdHis'),\n $to->clone()->addHours(24)->format('YmdHis'),\n );\n\n if ($activity->lead_id) {\n $filterStatements[] = sprintf('candidateUserID: %d', (int) $activity->lead->crm_provider_id);\n }\n\n if ($activity->contact_id) {\n $filterStatements[] = sprintf('clientContactUserID: %d', (int) $activity->contact->crm_provider_id);\n }\n\n // if there is no contact or lead associated to the activity exit\n if ($activity->contact_id === null && $activity->lead_id === null) {\n return [];\n }\n\n $params = [\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => implode(' AND ', $filterStatements),\n 'sort' => '-dateLastModified',\n ];\n\n $bhNotes = $this->client->get('search/Note', $params);\n\n $startStamp = $from?->getTimestamp() * 1000;\n $endStamp = $to->getTimestamp() * 1000;\n\n $filteredNotes = array_values(\n array_filter(\n $bhNotes['data'],\n static fn (array $bhNote): bool\n => $bhNote['dateLastModified'] >= $startStamp && $startStamp <= $endStamp,\n ),\n );\n\n return ! empty($filteredNotes) ? array_shift($filteredNotes) : [];\n }\n\n /**\n * Select how to create the date out of the Bullhorn payload.\n * Do not allow dates beyond 9999-12-31 (max mysql DATE)\n */\n private function filterOutOfBoundDates(string $rawDateCandidate): ?Carbon\n {\n if (strlen($rawDateCandidate) > 12) {\n // A unix timestamp represented with more than 12 digits i\n // s definitely including milliseconds\n $dateFormatted = Carbon::createFromTimestampMs($rawDateCandidate);\n } else {\n $dateFormatted = Carbon::createFromTimestamp($rawDateCandidate);\n }\n\n $minDate = Carbon::createFromFormat('Y-m-d', '2000-01-01');\n if ($dateFormatted->lt($minDate)) {\n return null;\n }\n\n $maxDate = Carbon::createFromFormat('Y-m-d', '9999-12-31');\n if ($dateFormatted->gt($maxDate)) {\n $this->logger->warning('[Bullhorn] An out of bound date is provided', [\n 'date' => $dateFormatted,\n 'rawDate' => $rawDateCandidate,\n ]);\n\n return $maxDate;\n }\n\n return $dateFormatted;\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n $note = $this->getRecord('Note', $crmProviderId, ['id', 'isDeleted']);\n\n return ! empty($note) && ($note['isDeleted'] ?? false) === false;\n } catch (HttpNotFoundException|HttpBadRequestException) {\n // Note not found in CRM - this is expected and permanent\n $this->logger->info('[Bullhorn] Note not found during verification', [\n 'note_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Bullhorn;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\BullhornInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\ApplicationException;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\DomainException;\nuse Jiminny\\Exceptions\\HttpBadRequestException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\ServiceUnavailableException;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\UserRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\nuse Ramsey\\Uuid\\Uuid;\n\nclass BullhornService extends BaseService implements\n BullhornInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const string ENTITY_LEAD = 'Candidate';\n private const string ENTITY_OPPORTUNITY = 'JobOrder';\n private const string ENTITY_ACCOUNT = 'ClientCorporation';\n private const string ENTITY_CONTACT = 'ClientContact';\n private const string ENTITY_ACTIVITY = 'Note';\n\n private const array OPPORTUNITY_FIELDS = [\n 'id',\n 'owner',\n 'status',\n 'title',\n 'salary',\n 'salaryUnit',\n 'payRate',\n 'isOpen',\n 'employmentType',\n 'dateClosed',\n 'startDate',\n 'dateLastModified',\n 'dateAdded',\n 'clientCorporation',\n 'correlatedCustomText10', // currency\n ];\n\n private const array TASK_FIELDS = [\n 'id',\n 'comments',\n 'dateAdded',\n 'dateLastModified',\n 'externalID',\n 'isDeleted',\n 'corporateUsers',\n 'clientContacts',\n 'commentingPerson',\n 'candidates',\n 'jobOrder',\n 'minutesSpent',\n 'action',\n ];\n\n private const array LEAD_FIELDS = [\n 'id',\n 'name',\n 'owner',\n 'occupation',\n 'companyName',\n 'companyURL',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'workPhone',\n 'status',\n 'address',\n 'dateAdded',\n 'dateLastModified',\n ];\n\n private const array CONTACT_FIELDS = [\n 'id',\n 'name',\n 'occupation',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'address',\n 'clientCorporation',\n 'dateAdded',\n 'owner',\n ];\n\n private const array ACCOUNT_FIELDS = [\n 'id',\n 'name',\n 'phone',\n 'industryList',\n 'address',\n 'companyURL',\n 'dateAdded',\n ];\n\n public function __construct(\n BullhornClientInterface $client,\n private readonly UserRepository $userRepository,\n private readonly ProspectPhotoPathService $prospectPhotoPathService\n ) {\n parent::__construct();\n\n $this->client = $client;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);\n }\n\n public function getDisplayName(): string\n {\n return 'Bullhorn';\n }\n\n public function createTranscriptNotes(Activity $activity): void\n {\n // Not done until a customer requests it.\n }\n\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n 'task',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))\n );\n\n if (! empty($changedFields)) {\n $fields = implode(',', $newFields);\n Log::debug(\n sprintf(\n '%s fields changed from %s to: %s',\n ucfirst($fieldType),\n $this->profile->{$fieldType . '_fields'},\n $fields,\n ),\n );\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (\\Exception $exception) {\n \\Log::error('No access to ' . $fieldType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n //parent::OBJECT_ACCOUNT,\n //parent::OBJECT_CONTACT,\n //parent::OBJECT_OPPORTUNITY,\n //parent::OBJECT_LEAD,\n ];\n }\n\n protected function getFields(string $crmObject): array\n {\n $fields = [];\n foreach ($this->getObjectFields($crmObject) as $row) {\n $fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];\n }\n\n return $fields;\n }\n\n private function getObjectFields(string $objectType): array\n {\n $entityType = $this->convertObjectTypeToResource($objectType);\n\n return Cache::remember(\n key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,\n ttl: 60 * 60,\n callback: function () use ($entityType) {\n $entity = $this->client->get('meta/' . $entityType, [\n 'fields' => '*',\n ]);\n\n return $entity['fields'];\n },\n );\n }\n\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n $defaultFields = FieldDefinitions::defaultFields();\n\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n\n return $fields;\n }\n\n public function getDefaultActivityField(string $activityType): Field\n {\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'action',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n // We are not yet supporting follow-ups for this system.\n return [];\n }\n\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return $fieldValue;\n }\n\n public function syncField(Field $field): void\n {\n $resource = $this->convertObjectTypeToResource($field->object_type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => $field->crm_provider_id,\n 'meta' => 'full',\n ]);\n\n $bhField = $entity['fields'][0];\n\n $isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);\n $description = null;\n if (empty($bhField['description']) === false) {\n $description = mb_strimwidth($bhField['description'], 0, 191);\n }\n\n $label = 'Unknown';\n if (empty($bhField['label']) === false) {\n $label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);\n }\n\n $field->length = $bhField['maxLength'] ?? null;\n $field->is_mandatory = $isMandatory;\n $field->description = $description;\n $field->label = $label;\n $field->type = $this->convertFieldType(\n $bhField['dataType'] ?? null,\n $bhField['dataSpecialization'] ?? null,\n $bhField['inputType'] ?? null\n );\n\n $field->save();\n\n if (empty($bhField['options']) === false) {\n $values = [];\n\n // Import all values.\n foreach ($bhField['options'] as $i => $option) {\n $values[] = [\n 'value' => $option['value'],\n 'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),\n 'sequence' => $i,\n ];\n }\n\n // Take the existing set of field values.\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n // For all current values, upsert the field.\n $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n $key = array_search($value['value'], $fieldsToPurge, false);\n if ($key !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n }\n }\n\n public function importPicklistValues(Field $field): array\n {\n // Taken care of in syncField.\n return [];\n }\n\n private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string\n {\n if ($type === null) {\n return Field::TYPE_UNSUPPORTED;\n }\n\n $type = strtolower($type);\n $specialization = strtolower($specialization);\n $inputType = strtolower($inputType);\n\n switch ($type) {\n case 'boolean':\n return Field::TYPE_BOOLEAN;\n\n case 'integer':\n switch ($specialization) {\n case 'integer':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'bigdecimal':\n switch ($specialization) {\n case 'money':\n return Field::TYPE_CURRENCY;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'double':\n switch ($specialization) {\n case 'float':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'timestamp':\n switch ($specialization) {\n case 'date':\n return Field::TYPE_DATE;\n case 'time':\n return Field::TYPE_TIME;\n case 'datetime':\n return Field::TYPE_DATETIME;\n default:\n return Field::TYPE_DATE;\n }\n\n // no break\n case 'string':\n switch ($inputType) {\n case 'textarea':\n return Field::TYPE_TEXTAREA;\n case 'select':\n return Field::TYPE_PICKLIST;\n default:\n return Field::TYPE_TEXT;\n }\n\n // no break\n default:\n // This is not actually a supported field.\n return Field::TYPE_UNSUPPORTED;\n }\n }\n\n private function importContact($crmData): Contact\n {\n $account = $mobilePhone = $phone = $email = null;\n if (empty($crmData['clientCorporation']) === false) {\n $account = $this->team\n ->accounts()\n ->where('crm_provider_id', $crmData['clientCorporation']['id'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n }\n\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => $crmData['name'],\n 'email' => $email,\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'title' => $crmData['occupation'],\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Contact::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n if ($crmData['clientCorporation']['id']) {\n $account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n } else {\n // If there is nothing to associate this with, don't import it.\n return null;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $stage = $this->config->stages()\n ->where('crm_provider_id', $crmData['status'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => mb_strimwidth($crmData['title'], 0, 128),\n 'value' => $crmData['salary'] ?? $crmData['payRate'],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),\n 'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),\n 'is_closed' => $crmData['isOpen'] !== true,\n 'is_won' => strtolower($crmData['status']) === 'placed',\n 'stage_id' => $stage->id,\n 'record_type_id' => null,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importAccount($crmData): Account\n {\n $countryCode = $domain = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $name = $crmData['name'] ?? 'Unknown';\n\n if ($crmData['companyURL'] !== null) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => null,\n 'owner_id' => null,\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Account::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'country_code' => $countryCode,\n 'domain' => $domain,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importLead($crmData): ?Lead\n {\n // Get the current stage.\n $stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);\n }\n\n // If we have no way of importing this, just return null :(\n if ($stage === null) {\n return null;\n }\n\n $countryCode = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $mobilePhone = $phone = $email = null;\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $company = 'Unknown';\n if (empty($crmData['companyName']) === false) {\n $companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];\n $company = mb_strimwidth($companyName, 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['companyURL']) === false) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'company' => $company,\n 'domain' => $domain,\n 'name' => mb_strimwidth($crmData['name'], 0, 191),\n 'title' => mb_strimwidth($crmData['occupation'], 0, 128),\n 'email' => mb_strimwidth($email, 0, 80),\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Lead::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'stage_id' => $stage->id,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhContacts = $this->client->get('search/ClientContact', $params);\n\n foreach ($bhContacts['data'] as $bhContact) {\n // Only sync if previously imported.\n if ($this->hasContact($bhContact['id'])) {\n $this->importContact($bhContact);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategies = $strategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n $total = 0;\n $count = 0;\n $offset = 0;\n\n try {\n $bhOpportunities = [];\n foreach ($strategies as $syncStrategy) {\n $opportunitiesData = $syncStrategy->fetchOpportunities($parameters);\n $total = (int) ($opportunitiesData['total'] ?? 0);\n $count = (int) ($opportunitiesData['count'] ?? 0);\n $offset = (int) ($opportunitiesData['start'] ?? 0);\n $bhOpportunities[] = $opportunitiesData['data'] ?? [];\n }\n\n $bhOpportunities = array_merge(...$bhOpportunities);\n\n foreach ($bhOpportunities as $bhOpportunity) {\n $this->importOpportunity($bhOpportunity);\n $syncCount++;\n }\n } catch (\\Exception $exception) {\n $this->logger->info('Failed to sync opportunities', [\n 'params' => $parameters,\n 'exception' => $exception->getMessage(),\n ]);\n }\n\n // only log if there are one sync strategy\n if (count($strategies) === 1 && $total > $count + $offset) {\n $this->logger->info('[Bullhorn] Sync Opportunities - count warning', [\n 'team_id' => $this->team->getId(),\n 'total' => $total,\n 'count' => $count,\n 'offset' => $offset,\n ]);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhAccounts = $this->client->get('search/ClientCorporation', $params);\n\n foreach ($bhAccounts['data'] as $bhAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($bhAccount['id'])) {\n $this->importAccount($bhAccount);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhLeads = $this->client->get('search/Candidate', $params);\n if ($bhLeads === null) {\n return $syncCount;\n }\n\n foreach ($bhLeads['data'] as $bhLead) {\n // Only sync if previously imported.\n if ($this->hasLead($bhLead['id'])) {\n $this->importLead($bhLead);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n\n public function syncContact(string $crmId): ?Contact\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importContact($data['data']);\n }\n\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategy = $strategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n try {\n $data = $strategy->fetchOpportunities(['crm_id' => $crmId]);\n } catch (HttpNotFoundException $exception) {\n $this->logger->info('[Bullhorn] Opportunity not found', [\n 'crm_id' => $crmId,\n 'reason' => $exception->getMessage(),\n ]);\n }\n\n return $this->importOpportunity($data['data'] ?? []);\n }\n\n public function syncAccount(string $crmId): ?Account\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importAccount($data['data']);\n }\n\n public function syncLead(string $crmId): ?Lead\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importLead($data['data']);\n }\n\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $missingStage = null;\n\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n\n foreach ($types as $type) {\n $resource = $this->convertObjectTypeToResource($type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => 'status',\n 'meta' => 'full',\n ]);\n\n $missingStage = null;\n\n if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {\n throw new \\UnexpectedValueException('Invalid response from Bullhorn API');\n }\n\n // Upsert all stages for the team.\n foreach ($entity['fields'][0]['options'] as $i => $option) {\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $option['value'],\n 'type' => $type,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($option['value'], 0, 50),\n 'label' => mb_strimwidth($option['label'], 0, 191),\n 'sequence' => $i,\n 'is_selectable' => 1,\n ]);\n\n if ($missingStageName && $missingStageName === $option['value']) {\n $missingStage = $stage;\n }\n }\n\n if ($missingStageName && $missingStage === null) {\n // If they requested a stage that still doesn't exist, it must be inactive so lazy create it.\n $missingStage = $this->config->stages()->create([\n 'team_id' => $this->team->id,\n 'crm_provider_id' => Uuid::uuid4(),\n 'name' => mb_strimwidth($missingStageName, 0, 50),\n 'label' => mb_strimwidth($missingStageName, 0, 191),\n 'type' => $type,\n 'sequence' => 0,\n 'is_selectable' => 0,\n ]);\n }\n }\n\n return $missingStage;\n }\n\n public function syncOrganization(): void\n {\n // There appears to be nothing we can sync/map to.\n }\n\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $data = \\Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {\n $result = [];\n\n try {\n $objects = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => $count,\n ]);\n } catch (\\GuzzleHttp\\Exception\\ServerException $exception) {\n throw new ServiceUnavailableException($exception->getMessage());\n }\n\n foreach ($objects['data'] as $object) {\n try {\n $prospectType = $this->convertResourceToObjectType($object['entityType']);\n } catch (\\UnexpectedValueException $exception) {\n // We don't support this, so skip it.\n continue;\n }\n\n $record = [\n 'crmId' => $object['entityId'],\n 'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),\n 'prospectType' => $prospectType,\n 'phoneNumbers' => [],\n ];\n\n // Unfortunately we need to go and query each entity itself to get the data we need.\n switch ($object['entityType']) {\n case self::ENTITY_ACCOUNT:\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['industry'] = $entity['industryList'];\n if (empty($entity['phone']) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity['phone'],\n 'nationalFormat' => phone_national(null, $entity['phone']),\n 'type' => 'phone',\n ];\n }\n\n break;\n\n case self::ENTITY_CONTACT:\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n case self::ENTITY_LEAD:\n $bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);\n $entity = $bhData['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['companyName'];\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n default:\n // We are not interested in this entity type so skip it.\n continue 2;\n }\n\n $result[] = $record;\n }\n\n return $result;\n });\n\n return $data;\n }\n\n public function getClient(): BullhornClientInterface\n {\n return $this->client;\n }\n\n private function getFieldsAsString(array $fields)\n {\n return implode(', ', $fields);\n }\n\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),\n ];\n\n $onlyOpen = true;\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort'] = '-dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort'] = '+dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n $onlyOpen = false;\n }\n\n if ($onlyOpen) {\n $where .= ' AND isOpen: true';\n }\n\n $params['query'] = $where;\n\n $bhOpportunities = $this->client->get('search/JobOrder', $params);\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n foreach ($bhOpportunities['data'] as $bhOpportunity) {\n $stage = $this->config\n ->stages()\n ->where('crm_provider_id', $bhOpportunity['status'])\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);\n }\n\n $record = [\n 'crmId' => $bhOpportunity['id'],\n 'name' => $bhOpportunity['title'],\n 'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),\n 'won' => strtolower($bhOpportunity['status']) === 'placed',\n 'closed' => $bhOpportunity['isOpen'] !== true,\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n 'recordType' => [],\n ];\n\n if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = [];\n\n // For now it has not been agreed on how to implement this e.g. appointments or tasks?\n return [];\n\n if ($objectType === 'account' && $opportunityId === null) {\n // You cannot attach tasks to only accounts.\n return [];\n }\n\n // Query should default to any open task.\n $where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;\n\n // If we are also going to check on a specific job order, set that up.\n if ($opportunityId) {\n $where .= ' OR JobOrder: ' . (int) $opportunityId;\n }\n\n $where .= ')';\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => $where,\n ];\n\n $bhTasks = $this->client->get('search/Task', $params);\n\n foreach ($bhTasks['data'] as $bhTask) {\n $data[] = [\n 'crmId' => $bhTask['id'],\n 'subject' => $bhTask['subject'],\n 'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),\n 'type' => null,\n ];\n }\n\n return $data;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * ?Lead,\n * ?Account,\n * ?Opportunity,\n * ?Contact,\n * ?Stage,\n * ?string\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $bhObject = $this->client->get('find', [\n 'query' => $email,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember === false) {\n $bhObject = $this->client->get('find', [\n 'query' => $rawPhoneNumber ?? $phone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n if (empty($bhObject['data'])) {\n $nationalPhone = phone_national(null, $rawPhoneNumber ?? $phone);\n $formattedPhone = ltrim($nationalPhone, '+0');\n $bhObject = $this->client->get('find', [\n 'query' => $formattedPhone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n }\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n return null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 3) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = \\Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n $bhObject = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->team->getId() . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n public function saveActivity(Activity $activity): Activity\n {\n\n if ($activity->hasCrmProviderId()) {\n return $activity;\n }\n\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildNotePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n /**\n * @throws CrmException\n * @throws DomainException\n */\n private function buildNotePayload(Activity $activity): Activity\n {\n if ($activity->hasActivityType() === false) {\n throw new DomainException('[Bullhorn] No activity type assigned');\n }\n\n $action = $this->getCrmType($activity->getActivityType());\n if ($action === null) {\n throw new DomainException('[Bullhorn] No mapped CRM type for \"' . $activity->category->name . '\"');\n }\n\n if ($activity->lead_id === null && $activity->contact_id === null) {\n throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');\n }\n\n $payload = [\n 'comments' => $this->generateActivityDescription($activity),\n 'action' => $action->value,\n 'commentingPerson' => [\n 'id' => (int) $this->profile->crm_provider_id,\n 'type' => 'CorporateUser',\n ],\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n 'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),\n ];\n\n if ($activity->lead_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->lead->crm_provider_id,\n 'type' => 'Candidate',\n ];\n }\n\n if ($activity->contact_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->contact->crm_provider_id,\n 'type' => 'ClientContact',\n ];\n }\n\n if ($activity->opportunity_id) {\n $payload['jobOrders'] = [\n 'replaceAll' => [\n (int) $activity->opportunity->crm_provider_id,\n ],\n ];\n }\n\n $bhActivity = $this->client->put('entity/Note', $payload);\n\n $activity->crm_provider_id = $bhActivity['changedEntityId'];\n $activity->save();\n\n return $activity;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = '';\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: %s</span></p>',\n $activity->to->phone_number,\n );\n }\n $description .= '<p></p>';\n }\n\n if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: %s</span></p>',\n $activity->from->phone_number,\n );\n $description .= '<p></p>';\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span>'\n . '</p>';\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span>'\n . '</p>';\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= sprintf(\n '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . '<a href=\"%s\" target=\"_blank\">'\n . 'Review in Jiminny'\n . '</a>'\n . '️</span>'\n . '</p>',\n $playbackUrl,\n );\n }\n\n if ($activity->isTypeConference()) {\n $description .= '<p><strong>Attendees</strong></p><ul>';\n\n // Only include participants that joined.\n $participants = $activity->participants()->ghost(false)->whereNotNull('enter_time')->get();\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->name) {\n $attendee .= $participant->name;\n if ($participant->phone_number) {\n $attendee .= ' (' . $participant->phone_number . ')';\n } elseif ($participant->email) {\n $attendee .= ' (' . $participant->email . ')';\n }\n } else {\n $attendee .= $participant->phone_number;\n }\n\n if ($participant->is_ghost) {\n $attendee .= ' <strong>coach</coach>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $description .= $attendee . '</li>';\n }\n $description .= '</ul>';\n }\n\n if (count($activity->notes) > 0) {\n $description .= '<p><strong>Notes</strong></p>';\n\n foreach ($activity->notes as $note) {\n $time = ($note->time > 3600) ? gmdate('H:i:s', $note->time) : gmdate('i:s', $note->time);\n $description .= '<p>' . $time . ' ' . $note->note . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n if ($activity->summary) {\n $description .= '<p><strong>Summary</strong></p><p>' . $activity->summary . '</p><p></p>';\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n // Use Rich-text formatting.\n $description = sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>%s</strong></span></p>',\n $activity->title,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->description,\n );\n\n break;\n }\n\n return $description;\n }\n\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // Not yet required by current customers.\n return null;\n }\n\n public function updateStage($crmObject, Stage $stage): void\n {\n $objectId = $crmObject->crm_provider_id;\n\n $this->updateRecord($stage->type, $objectId, ['status' => $stage->crm_provider_id]);\n }\n\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $start = 0;\n $payload = [\n 'fields' => 'id,email',\n 'where' => 'isDeleted=false',\n 'count' => 500,\n ];\n\n $payload['start'] = $start;\n $profiles = $this->client->get('query/CorporateUser', $payload);\n\n foreach ($profiles['data'] as $profile) {\n if (empty($profile['email'])) {\n continue;\n }\n\n $user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);\n\n // Only import profiles for users we have locally.\n if ($user) {\n $profile = $user->crmProfile()->updateOrCreate([\n 'crm_configuration_id' => $this->config->id,\n 'crm_provider_id' => $profile['id'],\n ]);\n\n if ($userToSearch && $userToSearch->id === $user->id) {\n return $profile;\n }\n }\n }\n\n return null;\n }\n\n protected function convertCrmData(array $entities, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n $mappedEntities = [];\n foreach ($entities as $entity) {\n if (in_array($entity['entityType'], [self::ENTITY_LEAD, self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n $mappedEntities[] = $entity;\n }\n }\n\n // If there is only one match, sync the data and return the object(s).\n if (count($mappedEntities) === 1) {\n $entity = $mappedEntities[0];\n\n if ($entity['entityType'] === self::ENTITY_LEAD) {\n $lead = $this->syncLead($entity['entityId']);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } elseif (in_array($entity['entityType'], [self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n if ($entity['entityType'] === self::ENTITY_CONTACT) {\n $contact = $this->syncContact($entity['entityId']);\n $account = $contact->account;\n } else {\n $account = $this->syncAccount($entity['entityId']);\n }\n\n if ($contact?->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $bhOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact?->crm_provider_id,\n $userId,\n );\n\n // Take the first opportunity, which will be ordered as priority based on their settings.\n if (! empty($bhOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($bhOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n } catch (Exception) {\n // Nothing to see here.\n }\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n // There doesn't appear to be a way to deeplink to anything on https://app.bullhornstaffing.com.\n return null;\n }\n\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $this->client->post('entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId, $data);\n }\n\n public function getRecord(string $objectType, string $objectId, array $fields = ['id']): array\n {\n return $this->client->get(\n url: 'entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId,\n data: ['fields' => $this->getFieldsAsString($fields)],\n );\n }\n\n private function convertObjectTypeToResource(string $objectType)\n {\n switch ($objectType) {\n case FieldData::OBJECT_OPPORTUNITY:\n return self::ENTITY_OPPORTUNITY;\n\n case FieldData::OBJECT_CONTACT:\n return self::ENTITY_CONTACT;\n\n case FieldData::OBJECT_LEAD:\n return self::ENTITY_LEAD;\n\n case FieldData::OBJECT_ACCOUNT:\n return self::ENTITY_ACCOUNT;\n\n case FieldData::OBJECT_TASK:\n return self::ENTITY_ACTIVITY;\n\n default:\n throw new \\UnexpectedValueException('Unsupported object type \"' . $objectType . '\"');\n }\n }\n\n private function convertResourceToObjectType(string $resource): string\n {\n switch ($resource) {\n case self::ENTITY_OPPORTUNITY:\n return FieldData::OBJECT_OPPORTUNITY;\n\n case self::ENTITY_CONTACT:\n return FieldData::OBJECT_CONTACT;\n\n case self::ENTITY_LEAD:\n return FieldData::OBJECT_LEAD;\n\n case self::ENTITY_ACCOUNT:\n return FieldData::OBJECT_ACCOUNT;\n\n case self::ENTITY_ACTIVITY:\n return FieldData::OBJECT_TASK;\n\n default:\n throw new \\UnexpectedValueException('Unsupported resource \"' . $resource . '\"');\n }\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n // We need to know when it started to determine when to look for related activity.\n if ($activity->hasActualStartTime() === false) {\n return null;\n }\n\n try {\n $bhNote = $this->fetchRelatedActivity($activity);\n if (empty($bhNote)) {\n $this->logger->info('[Bullhorn] No related activity found', [\n 'activity' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $activityType = $this->getPlaybookCategory($this->getPlaybook($activity->user), $bhNote['action']);\n $comments = $bhNote['comments'] . '<br />//<br />' . $this->generateActivityDescription($activity);\n // Now update the Note to contain our data.\n $payload = [\n 'comments' => $comments,\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n ];\n\n $this->logger->info('[Bullhorn] updating related activity', [\n 'activity' => $activity->getUuid(),\n 'activityType' => $activityType->id ?? null,\n ]);\n\n $this->client->post('entity/Note/' . $bhNote['id'], $payload);\n\n $playbookCategoryId = null;\n if ($activity->getCategory() !== null) {\n $playbookCategoryId = $activity->getCategory()->getId();\n }\n\n // Update our activity to reflect the remote data.\n $activity->update([\n 'crm_provider_id' => $bhNote['id'],\n 'summary' => $bhNote['comments'],\n 'playbook_category_id' => $activityType->id ?? $playbookCategoryId,\n ]);\n\n return $activity;\n } catch (\\Exception $exception) {\n \\Sentry::captureException($exception);\n\n throw $exception;\n }\n }\n\n /**\n * Returns the most recently modified note within time range (if any).\n *\n * @return array A Note record from Bullhorn.\n */\n public function fetchRelatedActivity(Activity $activity): array\n {\n $from = $activity->hasScheduledStartTime()\n ? $activity->getScheduledStartTime()\n : $activity->getActualStartTime();\n $to = $activity->hasActualEndTime()\n ? $activity->getActualEndTime()?->addMinutes(15)\n : $from?->clone()->addMinutes(15);\n\n $filterStatements = [\n 'isDeleted: false',\n '*:* -externalID:[* TO *]', // externalID should be null e.g. we did not already relate it.\n sprintf('commentingPerson: %d', (int) $this->profile->crm_provider_id),\n ];\n\n /**\n * @XXX: Bullhorn does not specify the time zone in their docs. I've found a forum thread in which someone from\n * staff asserts it's UTC, however in my field test I've found it to be GMT-0300 (USA east coast).\n * To make the code immune to such glitches we will add 24h to start/end boundaries and will filter out\n * any excess items in code\n */\n $filterStatements[] = sprintf(\n 'dateLastModified:[%s TO %s]',\n $from?->clone()->subHours(24)->format('YmdHis'),\n $to->clone()->addHours(24)->format('YmdHis'),\n );\n\n if ($activity->lead_id) {\n $filterStatements[] = sprintf('candidateUserID: %d', (int) $activity->lead->crm_provider_id);\n }\n\n if ($activity->contact_id) {\n $filterStatements[] = sprintf('clientContactUserID: %d', (int) $activity->contact->crm_provider_id);\n }\n\n // if there is no contact or lead associated to the activity exit\n if ($activity->contact_id === null && $activity->lead_id === null) {\n return [];\n }\n\n $params = [\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => implode(' AND ', $filterStatements),\n 'sort' => '-dateLastModified',\n ];\n\n $bhNotes = $this->client->get('search/Note', $params);\n\n $startStamp = $from?->getTimestamp() * 1000;\n $endStamp = $to->getTimestamp() * 1000;\n\n $filteredNotes = array_values(\n array_filter(\n $bhNotes['data'],\n static fn (array $bhNote): bool\n => $bhNote['dateLastModified'] >= $startStamp && $startStamp <= $endStamp,\n ),\n );\n\n return ! empty($filteredNotes) ? array_shift($filteredNotes) : [];\n }\n\n /**\n * Select how to create the date out of the Bullhorn payload.\n * Do not allow dates beyond 9999-12-31 (max mysql DATE)\n */\n private function filterOutOfBoundDates(string $rawDateCandidate): ?Carbon\n {\n if (strlen($rawDateCandidate) > 12) {\n // A unix timestamp represented with more than 12 digits i\n // s definitely including milliseconds\n $dateFormatted = Carbon::createFromTimestampMs($rawDateCandidate);\n } else {\n $dateFormatted = Carbon::createFromTimestamp($rawDateCandidate);\n }\n\n $minDate = Carbon::createFromFormat('Y-m-d', '2000-01-01');\n if ($dateFormatted->lt($minDate)) {\n return null;\n }\n\n $maxDate = Carbon::createFromFormat('Y-m-d', '9999-12-31');\n if ($dateFormatted->gt($maxDate)) {\n $this->logger->warning('[Bullhorn] An out of bound date is provided', [\n 'date' => $dateFormatted,\n 'rawDate' => $rawDateCandidate,\n ]);\n\n return $maxDate;\n }\n\n return $dateFormatted;\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n $note = $this->getRecord('Note', $crmProviderId, ['id', 'isDeleted']);\n\n return ! empty($note) && ($note['isDeleted'] ?? false) === false;\n } catch (HttpNotFoundException|HttpBadRequestException) {\n // Note not found in CRM - this is expected and permanent\n $this->logger->info('[Bullhorn] Note not found during verification', [\n 'note_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.85486114,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.87291664,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.9138889,"top":0.31,"width":0.059027776,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.8645833,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.8854167,"top":0.34444445,"width":0.015277778,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.9048611,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"bounds":{"left":0.92569447,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.9458333,"top":0.3422222,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.9611111,"top":0.3422222,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","depth":4,"on_screen":true,"value":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.025,"top":0.06666667,"width":0.050694443,"height":0.034444444},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-3734033779188788614
|
-3409575825370887490
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
73
3
11
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Bullhorn;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\Provider\BullhornInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\ApplicationException;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\DomainException;
use Jiminny\Exceptions\HttpBadRequestException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\ServiceUnavailableException;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\UserRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
use Ramsey\Uuid\Uuid;
class BullhornService extends BaseService implements
BullhornInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const string ENTITY_LEAD = 'Candidate';
private const string ENTITY_OPPORTUNITY = 'JobOrder';
private const string ENTITY_ACCOUNT = 'ClientCorporation';
private const string ENTITY_CONTACT = 'ClientContact';
private const string ENTITY_ACTIVITY = 'Note';
private const array OPPORTUNITY_FIELDS = [
'id',
'owner',
'status',
'title',
'salary',
'salaryUnit',
'payRate',
'isOpen',
'employmentType',
'dateClosed',
'startDate',
'dateLastModified',
'dateAdded',
'clientCorporation',
'correlatedCustomText10', // currency
];
private const array TASK_FIELDS = [
'id',
'comments',
'dateAdded',
'dateLastModified',
'externalID',
'isDeleted',
'corporateUsers',
'clientContacts',
'commentingPerson',
'candidates',
'jobOrder',
'minutesSpent',
'action',
];
private const array LEAD_FIELDS = [
'id',
'name',
'owner',
'occupation',
'companyName',
'companyURL',
'mobile',
'phone',
'phone2',
'phone3',
'workPhone',
'status',
'address',
'dateAdded',
'dateLastModified',
];
private const array CONTACT_FIELDS = [
'id',
'name',
'occupation',
'mobile',
'phone',
'phone2',
'phone3',
'address',
'clientCorporation',
'dateAdded',
'owner',
];
private const array ACCOUNT_FIELDS = [
'id',
'name',
'phone',
'industryList',
'address',
'companyURL',
'dateAdded',
];
public function __construct(
BullhornClientInterface $client,
private readonly UserRepository $userRepository,
private readonly ProspectPhotoPathService $prospectPhotoPathService
) {
parent::__construct();
$this->client = $client;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);
}
public function getDisplayName(): string
{
return 'Bullhorn';
}
public function createTranscriptNotes(Activity $activity): void
{
// Not done until a customer requests it.
}
public function syncProfileFields(): void
{
$fieldTypes = [
'lead',
'account',
'contact',
'opportunity',
'task',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))
);
if (! empty($changedFields)) {
$fields = implode(',', $newFields);
Log::debug(
sprintf(
'%s fields changed from %s to: %s',
ucfirst($fieldType),
$this->profile->{$fieldType . '_fields'},
$fields,
),
);
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (\Exception $exception) {
\Log::error('No access to ' . $fieldType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
$this->profile->save();
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
//parent::OBJECT_ACCOUNT,
//parent::OBJECT_CONTACT,
//parent::OBJECT_OPPORTUNITY,
//parent::OBJECT_LEAD,
];
}
protected function getFields(string $crmObject): array
{
$fields = [];
foreach ($this->getObjectFields($crmObject) as $row) {
$fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];
}
return $fields;
}
private function getObjectFields(string $objectType): array
{
$entityType = $this->convertObjectTypeToResource($objectType);
return Cache::remember(
key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,
ttl: 60 * 60,
callback: function () use ($entityType) {
$entity = $this->client->get('meta/' . $entityType, [
'fields' => '*',
]);
return $entity['fields'];
},
);
}
public function getDefaultFields(string $activityType): array
{
$fields = [];
$defaultFields = FieldDefinitions::defaultFields();
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
return $fields;
}
public function getDefaultActivityField(string $activityType): Field
{
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'action',
'object_type' => $activityType,
])->first();
return $activityField;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
// We are not yet supporting follow-ups for this system.
return [];
}
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return $fieldValue;
}
public function syncField(Field $field): void
{
$resource = $this->convertObjectTypeToResource($field->object_type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => $field->crm_provider_id,
'meta' => 'full',
]);
$bhField = $entity['fields'][0];
$isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);
$description = null;
if (empty($bhField['description']) === false) {
$description = mb_strimwidth($bhField['description'], 0, 191);
}
$label = 'Unknown';
if (empty($bhField['label']) === false) {
$label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);
}
$field->length = $bhField['maxLength'] ?? null;
$field->is_mandatory = $isMandatory;
$field->description = $description;
$field->label = $label;
$field->type = $this->convertFieldType(
$bhField['dataType'] ?? null,
$bhField['dataSpecialization'] ?? null,
$bhField['inputType'] ?? null
);
$field->save();
if (empty($bhField['options']) === false) {
$values = [];
// Import all values.
foreach ($bhField['options'] as $i => $option) {
$values[] = [
'value' => $option['value'],
'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),
'sequence' => $i,
];
}
// Take the existing set of field values.
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
// For all current values, upsert the field.
$field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
$key = array_search($value['value'], $fieldsToPurge, false);
if ($key !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
}
}
public function importPicklistValues(Field $field): array
{
// Taken care of in syncField.
return [];
}
private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string
{
if ($type === null) {
return Field::TYPE_UNSUPPORTED;
}
$type = strtolower($type);
$specialization = strtolower($specialization);
$inputType = strtolower($inputType);
switch ($type) {
case 'boolean':
return Field::TYPE_BOOLEAN;
case 'integer':
switch ($specialization) {
case 'integer':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'bigdecimal':
switch ($specialization) {
case 'money':
return Field::TYPE_CURRENCY;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'double':
switch ($specialization) {
case 'float':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'timestamp':
switch ($specialization) {
case 'date':
return Field::TYPE_DATE;
case 'time':
return Field::TYPE_TIME;
case 'datetime':
return Field::TYPE_DATETIME;
default:
return Field::TYPE_DATE;
}
// no break
case 'string':
switch ($inputType) {
case 'textarea':
return Field::TYPE_TEXTAREA;
case 'select':
return Field::TYPE_PICKLIST;
default:
return Field::TYPE_TEXT;
}
// no break
default:
// This is not actually a supported field.
return Field::TYPE_UNSUPPORTED;
}
}
private function importContact($crmData): Contact
{
$account = $mobilePhone = $phone = $email = null;
if (empty($crmData['clientCorporation']) === false) {
$account = $this->team
->accounts()
->where('crm_provider_id', $crmData['clientCorporation']['id'])
->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
}
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => $crmData['name'],
'email' => $email,
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'title' => $crmData['occupation'],
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Contact::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importOpportunity($crmData): ?Opportunity
{
if ($crmData['clientCorporation']['id']) {
$account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
} else {
// If there is nothing to associate this with, don't import it.
return null;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$stage = $this->config->stages()
->where('crm_provider_id', $crmData['status'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);
}
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => mb_strimwidth($crmData['title'], 0, 128),
'value' => $crmData['salary'] ?? $crmData['payRate'],
'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),
'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),
'is_closed' => $crmData['isOpen'] !== true,
'is_won' => strtolower($crmData['status']) === 'placed',
'stage_id' => $stage->id,
'record_type_id' => null,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importAccount($crmData): Account
{
$countryCode = $domain = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$name = $crmData['name'] ?? 'Unknown';
if ($crmData['companyURL'] !== null) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$data = [
'team_id' => $this->team->id,
'user_id' => null,
'owner_id' => null,
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Account::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'country_code' => $countryCode,
'domain' => $domain,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importLead($crmData): ?Lead
{
// Get the current stage.
$stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);
}
// If we have no way of importing this, just return null :(
if ($stage === null) {
return null;
}
$countryCode = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$mobilePhone = $phone = $email = null;
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$company = 'Unknown';
if (empty($crmData['companyName']) === false) {
$companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];
$company = mb_strimwidth($companyName, 0, 191);
}
$domain = null;
if (empty($crmData['companyURL']) === false) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'company' => $company,
'domain' => $domain,
'name' => mb_strimwidth($crmData['name'], 0, 191),
'title' => mb_strimwidth($crmData['occupation'], 0, 128),
'email' => mb_strimwidth($email, 0, 80),
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Lead::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'stage_id' => $stage->id,
'country_code' => $countryCode,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
/**
* @throws ApplicationException
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhContacts = $this->client->get('search/ClientContact', $params);
foreach ($bhContacts['data'] as $bhContact) {
// Only sync if previously imported.
if ($this->hasContact($bhContact['id'])) {
$this->importContact($bhContact);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategies = $strategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
$total = 0;
$count = 0;
$offset = 0;
try {
$bhOpportunities = [];
foreach ($strategies as $syncStrategy) {
$opportunitiesData = $syncStrategy->fetchOpportunities($parameters);
$total = (int) ($opportunitiesData['total'] ?? 0);
$count = (int) ($opportunitiesData['count'] ?? 0);
$offset = (int) ($opportunitiesData['start'] ?? 0);
$bhOpportunities[] = $opportunitiesData['data'] ?? [];
}
$bhOpportunities = array_merge(...$bhOpportunities);
foreach ($bhOpportunities as $bhOpportunity) {
$this->importOpportunity($bhOpportunity);
$syncCount++;
}
} catch (\Exception $exception) {
$this->logger->info('Failed to sync opportunities', [
'params' => $parameters,
'exception' => $exception->getMessage(),
]);
}
// only log if there are one sync strategy
if (count($strategies) === 1 && $total > $count + $offset) {
$this->logger->info('[Bullhorn] Sync Opportunities - count warning', [
'team_id' => $this->team->getId(),
'total' => $total,
'count' => $count,
'offset' => $offset,
]);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhAccounts = $this->client->get('search/ClientCorporation', $params);
foreach ($bhAccounts['data'] as $bhAccount) {
// Only sync if previously imported.
if ($this->hasAccount($bhAccount['id'])) {
$this->importAccount($bhAccount);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhLeads = $this->client->get('search/Candidate', $params);
if ($bhLeads === null) {
return $syncCount;
}
foreach ($bhLeads['data'] as $bhLead) {
// Only sync if previously imported.
if ($this->hasLead($bhLead['id'])) {
$this->importLead($bhLead);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncContact(string $crmId): ?Contact
{
try {
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importContact($data['data']);
}
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategy = $strategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
try {
$data = $strategy->fetchOpportunities(['crm_id' => $crmId]);
} catch (HttpNotFoundException $exception) {
$this->logger->info('[Bullhorn] Opportunity not found', [
'crm_id' => $crmId,
'reason' => $exception->getMessage(),
]);
}
return $this->importOpportunity($data['data'] ?? []);
}
public function syncAccount(string $crmId): ?Account
{
try {
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importAccount($data['data']);
}
public function syncLead(string $crmId): ?Lead
{
try {
$data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importLead($data['data']);
}
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$missingStage = null;
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
foreach ($types as $type) {
$resource = $this->convertObjectTypeToResource($type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => 'status',
'meta' => 'full',
]);
$missingStage = null;
if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {
throw new \UnexpectedValueException('Invalid response from Bullhorn API');
}
// Upsert all stages for the team.
foreach ($entity['fields'][0]['options'] as $i => $option) {
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $option['value'],
'type' => $type,
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($option['value'], 0, 50),
'label' => mb_strimwidth($option['label'], 0, 191),
'sequence' => $i,
'is_selectable' => 1,
]);
if ($missingStageName && $missingStageName === $option['value']) {
$missingStage = $stage;
}
}
if ($missingStageName && $missingStage === null) {
// If they requested a stage that still doesn't exist, it must be inactive so lazy create it.
$missingStage = $this->config->stages()->create([
'team_id' => $this->team->id,
'crm_provider_id' => Uuid::uuid4(),
'name' => mb_strimwidth($missingStageName, 0, 50),
'label' => mb_strimwidth($missingStageName, 0, 191),
'type' => $type,
'sequence' => 0,
'is_selectable' => 0,
]);
}
}
return $missingStage;
}
public function syncOrganization(): void
{
// There appears to be nothing we can sync/map to.
}
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$data = \Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {
$result = [];
try {
$objects = $this->client->get('find', [
'query' => $name,
'meta' => 'basic',
'countPerEntity' => $count,
]);
} catch (\GuzzleHttp\Exception\ServerException $exception) {
throw new ServiceUnavailableException($exception->getMessage());
}
foreach ($objects['data'] as $object) {
try {
$prospectType = $this->convertResourceToObjectType($object['entityType']);
} catch (\UnexpectedValueException $exception) {
// We don't support this, so skip it.
continue;
}
$record = [
'crmId' => $object['entityId'],
'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),
'prospectType' => $prospectType,
'phoneNumbers' => [],
];
// Unfortunately we need to go and query each entity itself to get the data we need.
switch ($object['entityType']) {
case self::ENTITY_ACCOUNT:
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['industry'] = $entity['industryList'];
if (empty($entity['phone']) === false) {
$record['phoneNumbers'][] = [
'number' => $entity['phone'],
'nationalFormat' => phone_national(null, $entity['phone']),
'type' => 'phone',
];
}
break;
case self::ENTITY_CONTACT:
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
case self::ENTITY_LEAD:
$bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);
$entity = $bhData['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['companyName'];
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
default:
// We are not interested in this entity type so skip it.
continue 2;
}
$result[] = $record;
}
return $result;
});
return $data;
}
public function getClient(): BullhornClientInterface
{
return $this->client;
}
private function getFieldsAsString(array $fields)
{
return implode(', ', $fields);
}
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),
];
$onlyOpen = true;
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort'] = '-dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort'] = '+dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
$onlyOpen = false;
}
if ($onlyOpen) {
$where .= ' AND isOpen: true';
}
$params['query'] = $where;
$bhOpportunities = $this->client->get('search/JobOrder', $params);
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
foreach ($bhOpportunities['data'] as $bhOpportunity) {
$stage = $this->config
->stages()
->where('crm_provider_id', $bhOpportunity['status'])
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);
}
$record = [
'crmId' => $bhOpportunity['id'],
'name' => $bhOpportunity['title'],
'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),
'won' => strtolower($bhOpportunity['status']) === 'placed',
'closed' => $bhOpportunity['isOpen'] !== true,
'stage' => [
'id' => $stage->id_string,
'name' => $stage->name,
],
'recordType' => [],
];
if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = [];
// For now it has not been agreed on how to implement this e.g. appointments or tasks?
return [];
if ($objectType === 'account' && $opportunityId === null) {
// You cannot attach tasks to only accounts.
return [];
}
// Query should default to any open task.
$where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;
// If we are also going to check on a specific job order, set that up.
if ($opportunityId) {
$where .= ' OR JobOrder: ' . (int) $opportunityId;
}
$where .= ')';
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::TASK_FIELDS),
'query' => $where,
];
$bhTasks = $this->client->get('search/Task', $params);
foreach ($bhTasks['data'] as $bhTask) {
$data[] = [
'crmId' => $bhTask['id'],
'subject' => $bhTask['subject'],
'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),
'type' => null,
];
}
return $data;
}
/**
* @url [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] CrmException
* @throws DomainException
*/
private function buildNotePayload(Activity $activity): Activity
{
if ($activity->hasActivityType() === false) {
throw new DomainException('[Bullhorn] No activity type assigned');
}
$action = $this->getCrmType($activity->getActivityType());
if ($action === null) {
throw new DomainException('[Bullhorn] No mapped CRM type for "' . $activity->category->name . '"');
}
if ($activity->lead_id === null && $activity->contact_id === null) {
throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');
}
$payload = [
'comments' => $this->generateActivityDescription($activity),
'action' => $action->value,
'commentingPerson' => [
'id' => (int) $this->profile->crm_provider_id,
'type' => 'CorporateUser',
],
'externalID' => $activity->id_string,
'minutesSpent' => $activity->duration,
'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),
];
if ($activity->lead_id) {
$payload['personReference'] = [
'id' => (int) $activity->lead->crm_provider_id,
'type' => 'Candidate',
];
}
if ($activity->contact_id) {
$payload['personReference'] = [
'id' => (int) $activity->contact->crm_provider_id,
'type' => 'ClientContact',
];
}
if ($activity->opportunity_id) {
$payload['jobOrders'] = [
'replaceAll' => [
(int) $activity->opportunity->crm_provider_id,
],
];
}
$bhActivity = $this->client->put('entity/Note', $payload);
$activity->crm_provider_id = $bhActivity['changedEntityId'];
$activity->save();
return $activity;
}
private function generateActivityDescription(Activity $activity): string
{
$description = '';
switch ($activity->type) {
case Activity::TYPE_SOFTPHONE:
case Activity::TYPE_SOFTPHONE_INBOUND:
case Activity::TYPE_CONFERENCE:
if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
// Dialer calls have no native field for the subject.
if ($activity->title) {
$description .= sprintf(
'<p><span style="font-size: 16px; line-height: 19.2px;">%s</span></p>',
$activity->title,
);
}
// Conference meetings log duration into a distinct field, so log this in the main text.
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Call Duration: %s</span></p>',
$activity->duration_for_humans,
);
// Tell them which number was dialed.
if ($activity->to) {
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Dialed: %s</span></p>',
$activity->to->phone_number,
);
}
$description .= '<p></p>';
}
if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
...
|
45396
|
NULL
|
NULL
|
NULL
|
|
45397
|
1626
|
24
|
2026-05-14T14:34:20.930612+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769260930_m2.jpg...
|
PhpStorm
|
faVsco.js – BullhornService.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
73
3
11
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Bullhorn;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\Provider\BullhornInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\ApplicationException;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\DomainException;
use Jiminny\Exceptions\HttpBadRequestException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\ServiceUnavailableException;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\UserRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
use Ramsey\Uuid\Uuid;
class BullhornService extends BaseService implements
BullhornInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const string ENTITY_LEAD = 'Candidate';
private const string ENTITY_OPPORTUNITY = 'JobOrder';
private const string ENTITY_ACCOUNT = 'ClientCorporation';
private const string ENTITY_CONTACT = 'ClientContact';
private const string ENTITY_ACTIVITY = 'Note';
private const array OPPORTUNITY_FIELDS = [
'id',
'owner',
'status',
'title',
'salary',
'salaryUnit',
'payRate',
'isOpen',
'employmentType',
'dateClosed',
'startDate',
'dateLastModified',
'dateAdded',
'clientCorporation',
'correlatedCustomText10', // currency
];
private const array TASK_FIELDS = [
'id',
'comments',
'dateAdded',
'dateLastModified',
'externalID',
'isDeleted',
'corporateUsers',
'clientContacts',
'commentingPerson',
'candidates',
'jobOrder',
'minutesSpent',
'action',
];
private const array LEAD_FIELDS = [
'id',
'name',
'owner',
'occupation',
'companyName',
'companyURL',
'mobile',
'phone',
'phone2',
'phone3',
'workPhone',
'status',
'address',
'dateAdded',
'dateLastModified',
];
private const array CONTACT_FIELDS = [
'id',
'name',
'occupation',
'mobile',
'phone',
'phone2',
'phone3',
'address',
'clientCorporation',
'dateAdded',
'owner',
];
private const array ACCOUNT_FIELDS = [
'id',
'name',
'phone',
'industryList',
'address',
'companyURL',
'dateAdded',
];
public function __construct(
BullhornClientInterface $client,
private readonly UserRepository $userRepository,
private readonly ProspectPhotoPathService $prospectPhotoPathService
) {
parent::__construct();
$this->client = $client;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);
}
public function getDisplayName(): string
{
return 'Bullhorn';
}
public function createTranscriptNotes(Activity $activity): void
{
// Not done until a customer requests it.
}
public function syncProfileFields(): void
{
$fieldTypes = [
'lead',
'account',
'contact',
'opportunity',
'task',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))
);
if (! empty($changedFields)) {
$fields = implode(',', $newFields);
Log::debug(
sprintf(
'%s fields changed from %s to: %s',
ucfirst($fieldType),
$this->profile->{$fieldType . '_fields'},
$fields,
),
);
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (\Exception $exception) {
\Log::error('No access to ' . $fieldType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
$this->profile->save();
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
//parent::OBJECT_ACCOUNT,
//parent::OBJECT_CONTACT,
//parent::OBJECT_OPPORTUNITY,
//parent::OBJECT_LEAD,
];
}
protected function getFields(string $crmObject): array
{
$fields = [];
foreach ($this->getObjectFields($crmObject) as $row) {
$fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];
}
return $fields;
}
private function getObjectFields(string $objectType): array
{
$entityType = $this->convertObjectTypeToResource($objectType);
return Cache::remember(
key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,
ttl: 60 * 60,
callback: function () use ($entityType) {
$entity = $this->client->get('meta/' . $entityType, [
'fields' => '*',
]);
return $entity['fields'];
},
);
}
public function getDefaultFields(string $activityType): array
{
$fields = [];
$defaultFields = FieldDefinitions::defaultFields();
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
return $fields;
}
public function getDefaultActivityField(string $activityType): Field
{
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'action',
'object_type' => $activityType,
])->first();
return $activityField;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
// We are not yet supporting follow-ups for this system.
return [];
}
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return $fieldValue;
}
public function syncField(Field $field): void
{
$resource = $this->convertObjectTypeToResource($field->object_type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => $field->crm_provider_id,
'meta' => 'full',
]);
$bhField = $entity['fields'][0];
$isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);
$description = null;
if (empty($bhField['description']) === false) {
$description = mb_strimwidth($bhField['description'], 0, 191);
}
$label = 'Unknown';
if (empty($bhField['label']) === false) {
$label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);
}
$field->length = $bhField['maxLength'] ?? null;
$field->is_mandatory = $isMandatory;
$field->description = $description;
$field->label = $label;
$field->type = $this->convertFieldType(
$bhField['dataType'] ?? null,
$bhField['dataSpecialization'] ?? null,
$bhField['inputType'] ?? null
);
$field->save();
if (empty($bhField['options']) === false) {
$values = [];
// Import all values.
foreach ($bhField['options'] as $i => $option) {
$values[] = [
'value' => $option['value'],
'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),
'sequence' => $i,
];
}
// Take the existing set of field values.
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
// For all current values, upsert the field.
$field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
$key = array_search($value['value'], $fieldsToPurge, false);
if ($key !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
}
}
public function importPicklistValues(Field $field): array
{
// Taken care of in syncField.
return [];
}
private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string
{
if ($type === null) {
return Field::TYPE_UNSUPPORTED;
}
$type = strtolower($type);
$specialization = strtolower($specialization);
$inputType = strtolower($inputType);
switch ($type) {
case 'boolean':
return Field::TYPE_BOOLEAN;
case 'integer':
switch ($specialization) {
case 'integer':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'bigdecimal':
switch ($specialization) {
case 'money':
return Field::TYPE_CURRENCY;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'double':
switch ($specialization) {
case 'float':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'timestamp':
switch ($specialization) {
case 'date':
return Field::TYPE_DATE;
case 'time':
return Field::TYPE_TIME;
case 'datetime':
return Field::TYPE_DATETIME;
default:
return Field::TYPE_DATE;
}
// no break
case 'string':
switch ($inputType) {
case 'textarea':
return Field::TYPE_TEXTAREA;
case 'select':
return Field::TYPE_PICKLIST;
default:
return Field::TYPE_TEXT;
}
// no break
default:
// This is not actually a supported field.
return Field::TYPE_UNSUPPORTED;
}
}
private function importContact($crmData): Contact
{
$account = $mobilePhone = $phone = $email = null;
if (empty($crmData['clientCorporation']) === false) {
$account = $this->team
->accounts()
->where('crm_provider_id', $crmData['clientCorporation']['id'])
->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
}
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => $crmData['name'],
'email' => $email,
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'title' => $crmData['occupation'],
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Contact::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importOpportunity($crmData): ?Opportunity
{
if ($crmData['clientCorporation']['id']) {
$account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
} else {
// If there is nothing to associate this with, don't import it.
return null;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$stage = $this->config->stages()
->where('crm_provider_id', $crmData['status'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);
}
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => mb_strimwidth($crmData['title'], 0, 128),
'value' => $crmData['salary'] ?? $crmData['payRate'],
'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),
'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),
'is_closed' => $crmData['isOpen'] !== true,
'is_won' => strtolower($crmData['status']) === 'placed',
'stage_id' => $stage->id,
'record_type_id' => null,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importAccount($crmData): Account
{
$countryCode = $domain = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$name = $crmData['name'] ?? 'Unknown';
if ($crmData['companyURL'] !== null) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$data = [
'team_id' => $this->team->id,
'user_id' => null,
'owner_id' => null,
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Account::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'country_code' => $countryCode,
'domain' => $domain,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importLead($crmData): ?Lead
{
// Get the current stage.
$stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);
}
// If we have no way of importing this, just return null :(
if ($stage === null) {
return null;
}
$countryCode = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$mobilePhone = $phone = $email = null;
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$company = 'Unknown';
if (empty($crmData['companyName']) === false) {
$companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];
$company = mb_strimwidth($companyName, 0, 191);
}
$domain = null;
if (empty($crmData['companyURL']) === false) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'company' => $company,
'domain' => $domain,
'name' => mb_strimwidth($crmData['name'], 0, 191),
'title' => mb_strimwidth($crmData['occupation'], 0, 128),
'email' => mb_strimwidth($email, 0, 80),
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Lead::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'stage_id' => $stage->id,
'country_code' => $countryCode,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
/**
* @throws ApplicationException
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhContacts = $this->client->get('search/ClientContact', $params);
foreach ($bhContacts['data'] as $bhContact) {
// Only sync if previously imported.
if ($this->hasContact($bhContact['id'])) {
$this->importContact($bhContact);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategies = $strategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
$total = 0;
$count = 0;
$offset = 0;
try {
$bhOpportunities = [];
foreach ($strategies as $syncStrategy) {
$opportunitiesData = $syncStrategy->fetchOpportunities($parameters);
$total = (int) ($opportunitiesData['total'] ?? 0);
$count = (int) ($opportunitiesData['count'] ?? 0);
$offset = (int) ($opportunitiesData['start'] ?? 0);
$bhOpportunities[] = $opportunitiesData['data'] ?? [];
}
$bhOpportunities = array_merge(...$bhOpportunities);
foreach ($bhOpportunities as $bhOpportunity) {
$this->importOpportunity($bhOpportunity);
$syncCount++;
}
} catch (\Exception $exception) {
$this->logger->info('Failed to sync opportunities', [
'params' => $parameters,
'exception' => $exception->getMessage(),
]);
}
// only log if there are one sync strategy
if (count($strategies) === 1 && $total > $count + $offset) {
$this->logger->info('[Bullhorn] Sync Opportunities - count warning', [
'team_id' => $this->team->getId(),
'total' => $total,
'count' => $count,
'offset' => $offset,
]);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhAccounts = $this->client->get('search/ClientCorporation', $params);
foreach ($bhAccounts['data'] as $bhAccount) {
// Only sync if previously imported.
if ($this->hasAccount($bhAccount['id'])) {
$this->importAccount($bhAccount);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhLeads = $this->client->get('search/Candidate', $params);
if ($bhLeads === null) {
return $syncCount;
}
foreach ($bhLeads['data'] as $bhLead) {
// Only sync if previously imported.
if ($this->hasLead($bhLead['id'])) {
$this->importLead($bhLead);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncContact(string $crmId): ?Contact
{
try {
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importContact($data['data']);
}
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategy = $strategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
try {
$data = $strategy->fetchOpportunities(['crm_id' => $crmId]);
} catch (HttpNotFoundException $exception) {
$this->logger->info('[Bullhorn] Opportunity not found', [
'crm_id' => $crmId,
'reason' => $exception->getMessage(),
]);
}
return $this->importOpportunity($data['data'] ?? []);
}
public function syncAccount(string $crmId): ?Account
{
try {
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importAccount($data['data']);
}
public function syncLead(string $crmId): ?Lead
{
try {
$data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importLead($data['data']);
}
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$missingStage = null;
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
foreach ($types as $type) {
$resource = $this->convertObjectTypeToResource($type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => 'status',
'meta' => 'full',
]);
$missingStage = null;
if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {
throw new \UnexpectedValueException('Invalid response from Bullhorn API');
}
// Upsert all stages for the team.
foreach ($entity['fields'][0]['options'] as $i => $option) {
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $option['value'],
'type' => $type,
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($option['value'], 0, 50),
'label' => mb_strimwidth($option['label'], 0, 191),
'sequence' => $i,
'is_selectable' => 1,
]);
if ($missingStageName && $missingStageName === $option['value']) {
$missingStage = $stage;
}
}
if ($missingStageName && $missingStage === null) {
// If they requested a stage that still doesn't exist, it must be inactive so lazy create it.
$missingStage = $this->config->stages()->create([
'team_id' => $this->team->id,
'crm_provider_id' => Uuid::uuid4(),
'name' => mb_strimwidth($missingStageName, 0, 50),
'label' => mb_strimwidth($missingStageName, 0, 191),
'type' => $type,
'sequence' => 0,
'is_selectable' => 0,
]);
}
}
return $missingStage;
}
public function syncOrganization(): void
{
// There appears to be nothing we can sync/map to.
}
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$data = \Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {
$result = [];
try {
$objects = $this->client->get('find', [
'query' => $name,
'meta' => 'basic',
'countPerEntity' => $count,
]);
} catch (\GuzzleHttp\Exception\ServerException $exception) {
throw new ServiceUnavailableException($exception->getMessage());
}
foreach ($objects['data'] as $object) {
try {
$prospectType = $this->convertResourceToObjectType($object['entityType']);
} catch (\UnexpectedValueException $exception) {
// We don't support this, so skip it.
continue;
}
$record = [
'crmId' => $object['entityId'],
'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),
'prospectType' => $prospectType,
'phoneNumbers' => [],
];
// Unfortunately we need to go and query each entity itself to get the data we need.
switch ($object['entityType']) {
case self::ENTITY_ACCOUNT:
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['industry'] = $entity['industryList'];
if (empty($entity['phone']) === false) {
$record['phoneNumbers'][] = [
'number' => $entity['phone'],
'nationalFormat' => phone_national(null, $entity['phone']),
'type' => 'phone',
];
}
break;
case self::ENTITY_CONTACT:
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
case self::ENTITY_LEAD:
$bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);
$entity = $bhData['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['companyName'];
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
default:
// We are not interested in this entity type so skip it.
continue 2;
}
$result[] = $record;
}
return $result;
});
return $data;
}
public function getClient(): BullhornClientInterface
{
return $this->client;
}
private function getFieldsAsString(array $fields)
{
return implode(', ', $fields);
}
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),
];
$onlyOpen = true;
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort'] = '-dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort'] = '+dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
$onlyOpen = false;
}
if ($onlyOpen) {
$where .= ' AND isOpen: true';
}
$params['query'] = $where;
$bhOpportunities = $this->client->get('search/JobOrder', $params);
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
foreach ($bhOpportunities['data'] as $bhOpportunity) {
$stage = $this->config
->stages()
->where('crm_provider_id', $bhOpportunity['status'])
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);
}
$record = [
'crmId' => $bhOpportunity['id'],
'name' => $bhOpportunity['title'],
'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),
'won' => strtolower($bhOpportunity['status']) === 'placed',
'closed' => $bhOpportunity['isOpen'] !== true,
'stage' => [
'id' => $stage->id_string,
'name' => $stage->name,
],
'recordType' => [],
];
if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = [];
// For now it has not been agreed on how to implement this e.g. appointments or tasks?
return [];
if ($objectType === 'account' && $opportunityId === null) {
// You cannot attach tasks to only accounts.
return [];
}
// Query should default to any open task.
$where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;
// If we are also going to check on a specific job order, set that up.
if ($opportunityId) {
$where .= ' OR JobOrder: ' . (int) $opportunityId;
}
$where .= ')';
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::TASK_FIELDS),
'query' => $where,
];
$bhTasks = $this->client->get('search/Task', $params);
foreach ($bhTasks['data'] as $bhTask) {
$data[] = [
'crmId' => $bhTask['id'],
'subject' => $bhTask['subject'],
'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),
'type' => null,
];
}
return $data;
}
/**
* @url [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] CrmException
* @throws DomainException
*/
private function buildNotePayload(Activity $activity): Activity
{
if ($activity->hasActivityType() === false) {
throw new DomainException('[Bullhorn] No activity type assigned');
}
$action = $this->getCrmType($activity->getActivityType());
if ($action === null) {
throw new DomainException('[Bullhorn] No mapped CRM type for "' . $activity->category->name . '"');
}
if ($activity->lead_id === null && $activity->contact_id === null) {
throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');
}
$payload = [
'comments' => $this->generateActivityDescription($activity),
'action' => $action->value,
'commentingPerson' => [
'id' => (int) $this->profile->crm_provider_id,
'type' => 'CorporateUser',
],
'externalID' => $activity->id_string,
'minutesSpent' => $activity->duration,
'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),
];
if ($activity->lead_id) {
$payload['personReference'] = [
'id' => (int) $activity->lead->crm_provider_id,
'type' => 'Candidate',
];
}
if ($activity->contact_id) {
$payload['personReference'] = [
'id' => (int) $activity->contact->crm_provider_id,
'type' => 'ClientContact',
];
}
if ($activity->opportunity_id) {
$payload['jobOrders'] = [
'replaceAll' => [
(int) $activity->opportunity->crm_provider_id,
],
];
}
$bhActivity = $this->client->put('entity/Note', $payload);
$activity->crm_provider_id = $bhActivity['changedEntityId'];
$activity->save();
return $activity;
}
private function generateActivityDescription(Activity $activity): string
{
$description = '';
switch ($activity->type) {
case Activity::TYPE_SOFTPHONE:
case Activity::TYPE_SOFTPHONE_INBOUND:
case Activity::TYPE_CONFERENCE:
if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
// Dialer calls have no native field for the subject.
if ($activity->title) {
$description .= sprintf(
'<p><span style="font-size: 16px; line-height: 19.2px;">%s</span></p>',
$activity->title,
);
}
// Conference meetings log duration into a distinct field, so log this in the main text.
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Call Duration: %s</span></p>',
$activity->duration_for_humans,
);
// Tell them which number was dialed.
if ($activity->to) {
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Dialed: %s</span></p>',
$activity->to->phone_number,
);
}
$description .= '<p></p>';
}
if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.66456115,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.67586434,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.6871675,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.7150931,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.72639626,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.73769945,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"73","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"11","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Bullhorn;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\BullhornInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\ApplicationException;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\DomainException;\nuse Jiminny\\Exceptions\\HttpBadRequestException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\ServiceUnavailableException;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\UserRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\nuse Ramsey\\Uuid\\Uuid;\n\nclass BullhornService extends BaseService implements\n BullhornInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const string ENTITY_LEAD = 'Candidate';\n private const string ENTITY_OPPORTUNITY = 'JobOrder';\n private const string ENTITY_ACCOUNT = 'ClientCorporation';\n private const string ENTITY_CONTACT = 'ClientContact';\n private const string ENTITY_ACTIVITY = 'Note';\n\n private const array OPPORTUNITY_FIELDS = [\n 'id',\n 'owner',\n 'status',\n 'title',\n 'salary',\n 'salaryUnit',\n 'payRate',\n 'isOpen',\n 'employmentType',\n 'dateClosed',\n 'startDate',\n 'dateLastModified',\n 'dateAdded',\n 'clientCorporation',\n 'correlatedCustomText10', // currency\n ];\n\n private const array TASK_FIELDS = [\n 'id',\n 'comments',\n 'dateAdded',\n 'dateLastModified',\n 'externalID',\n 'isDeleted',\n 'corporateUsers',\n 'clientContacts',\n 'commentingPerson',\n 'candidates',\n 'jobOrder',\n 'minutesSpent',\n 'action',\n ];\n\n private const array LEAD_FIELDS = [\n 'id',\n 'name',\n 'owner',\n 'occupation',\n 'companyName',\n 'companyURL',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'workPhone',\n 'status',\n 'address',\n 'dateAdded',\n 'dateLastModified',\n ];\n\n private const array CONTACT_FIELDS = [\n 'id',\n 'name',\n 'occupation',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'address',\n 'clientCorporation',\n 'dateAdded',\n 'owner',\n ];\n\n private const array ACCOUNT_FIELDS = [\n 'id',\n 'name',\n 'phone',\n 'industryList',\n 'address',\n 'companyURL',\n 'dateAdded',\n ];\n\n public function __construct(\n BullhornClientInterface $client,\n private readonly UserRepository $userRepository,\n private readonly ProspectPhotoPathService $prospectPhotoPathService\n ) {\n parent::__construct();\n\n $this->client = $client;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);\n }\n\n public function getDisplayName(): string\n {\n return 'Bullhorn';\n }\n\n public function createTranscriptNotes(Activity $activity): void\n {\n // Not done until a customer requests it.\n }\n\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n 'task',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))\n );\n\n if (! empty($changedFields)) {\n $fields = implode(',', $newFields);\n Log::debug(\n sprintf(\n '%s fields changed from %s to: %s',\n ucfirst($fieldType),\n $this->profile->{$fieldType . '_fields'},\n $fields,\n ),\n );\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (\\Exception $exception) {\n \\Log::error('No access to ' . $fieldType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n //parent::OBJECT_ACCOUNT,\n //parent::OBJECT_CONTACT,\n //parent::OBJECT_OPPORTUNITY,\n //parent::OBJECT_LEAD,\n ];\n }\n\n protected function getFields(string $crmObject): array\n {\n $fields = [];\n foreach ($this->getObjectFields($crmObject) as $row) {\n $fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];\n }\n\n return $fields;\n }\n\n private function getObjectFields(string $objectType): array\n {\n $entityType = $this->convertObjectTypeToResource($objectType);\n\n return Cache::remember(\n key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,\n ttl: 60 * 60,\n callback: function () use ($entityType) {\n $entity = $this->client->get('meta/' . $entityType, [\n 'fields' => '*',\n ]);\n\n return $entity['fields'];\n },\n );\n }\n\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n $defaultFields = FieldDefinitions::defaultFields();\n\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n\n return $fields;\n }\n\n public function getDefaultActivityField(string $activityType): Field\n {\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'action',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n // We are not yet supporting follow-ups for this system.\n return [];\n }\n\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return $fieldValue;\n }\n\n public function syncField(Field $field): void\n {\n $resource = $this->convertObjectTypeToResource($field->object_type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => $field->crm_provider_id,\n 'meta' => 'full',\n ]);\n\n $bhField = $entity['fields'][0];\n\n $isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);\n $description = null;\n if (empty($bhField['description']) === false) {\n $description = mb_strimwidth($bhField['description'], 0, 191);\n }\n\n $label = 'Unknown';\n if (empty($bhField['label']) === false) {\n $label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);\n }\n\n $field->length = $bhField['maxLength'] ?? null;\n $field->is_mandatory = $isMandatory;\n $field->description = $description;\n $field->label = $label;\n $field->type = $this->convertFieldType(\n $bhField['dataType'] ?? null,\n $bhField['dataSpecialization'] ?? null,\n $bhField['inputType'] ?? null\n );\n\n $field->save();\n\n if (empty($bhField['options']) === false) {\n $values = [];\n\n // Import all values.\n foreach ($bhField['options'] as $i => $option) {\n $values[] = [\n 'value' => $option['value'],\n 'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),\n 'sequence' => $i,\n ];\n }\n\n // Take the existing set of field values.\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n // For all current values, upsert the field.\n $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n $key = array_search($value['value'], $fieldsToPurge, false);\n if ($key !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n }\n }\n\n public function importPicklistValues(Field $field): array\n {\n // Taken care of in syncField.\n return [];\n }\n\n private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string\n {\n if ($type === null) {\n return Field::TYPE_UNSUPPORTED;\n }\n\n $type = strtolower($type);\n $specialization = strtolower($specialization);\n $inputType = strtolower($inputType);\n\n switch ($type) {\n case 'boolean':\n return Field::TYPE_BOOLEAN;\n\n case 'integer':\n switch ($specialization) {\n case 'integer':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'bigdecimal':\n switch ($specialization) {\n case 'money':\n return Field::TYPE_CURRENCY;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'double':\n switch ($specialization) {\n case 'float':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'timestamp':\n switch ($specialization) {\n case 'date':\n return Field::TYPE_DATE;\n case 'time':\n return Field::TYPE_TIME;\n case 'datetime':\n return Field::TYPE_DATETIME;\n default:\n return Field::TYPE_DATE;\n }\n\n // no break\n case 'string':\n switch ($inputType) {\n case 'textarea':\n return Field::TYPE_TEXTAREA;\n case 'select':\n return Field::TYPE_PICKLIST;\n default:\n return Field::TYPE_TEXT;\n }\n\n // no break\n default:\n // This is not actually a supported field.\n return Field::TYPE_UNSUPPORTED;\n }\n }\n\n private function importContact($crmData): Contact\n {\n $account = $mobilePhone = $phone = $email = null;\n if (empty($crmData['clientCorporation']) === false) {\n $account = $this->team\n ->accounts()\n ->where('crm_provider_id', $crmData['clientCorporation']['id'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n }\n\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => $crmData['name'],\n 'email' => $email,\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'title' => $crmData['occupation'],\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Contact::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n if ($crmData['clientCorporation']['id']) {\n $account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n } else {\n // If there is nothing to associate this with, don't import it.\n return null;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $stage = $this->config->stages()\n ->where('crm_provider_id', $crmData['status'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => mb_strimwidth($crmData['title'], 0, 128),\n 'value' => $crmData['salary'] ?? $crmData['payRate'],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),\n 'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),\n 'is_closed' => $crmData['isOpen'] !== true,\n 'is_won' => strtolower($crmData['status']) === 'placed',\n 'stage_id' => $stage->id,\n 'record_type_id' => null,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importAccount($crmData): Account\n {\n $countryCode = $domain = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $name = $crmData['name'] ?? 'Unknown';\n\n if ($crmData['companyURL'] !== null) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => null,\n 'owner_id' => null,\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Account::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'country_code' => $countryCode,\n 'domain' => $domain,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importLead($crmData): ?Lead\n {\n // Get the current stage.\n $stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);\n }\n\n // If we have no way of importing this, just return null :(\n if ($stage === null) {\n return null;\n }\n\n $countryCode = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $mobilePhone = $phone = $email = null;\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $company = 'Unknown';\n if (empty($crmData['companyName']) === false) {\n $companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];\n $company = mb_strimwidth($companyName, 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['companyURL']) === false) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'company' => $company,\n 'domain' => $domain,\n 'name' => mb_strimwidth($crmData['name'], 0, 191),\n 'title' => mb_strimwidth($crmData['occupation'], 0, 128),\n 'email' => mb_strimwidth($email, 0, 80),\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Lead::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'stage_id' => $stage->id,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhContacts = $this->client->get('search/ClientContact', $params);\n\n foreach ($bhContacts['data'] as $bhContact) {\n // Only sync if previously imported.\n if ($this->hasContact($bhContact['id'])) {\n $this->importContact($bhContact);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategies = $strategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n $total = 0;\n $count = 0;\n $offset = 0;\n\n try {\n $bhOpportunities = [];\n foreach ($strategies as $syncStrategy) {\n $opportunitiesData = $syncStrategy->fetchOpportunities($parameters);\n $total = (int) ($opportunitiesData['total'] ?? 0);\n $count = (int) ($opportunitiesData['count'] ?? 0);\n $offset = (int) ($opportunitiesData['start'] ?? 0);\n $bhOpportunities[] = $opportunitiesData['data'] ?? [];\n }\n\n $bhOpportunities = array_merge(...$bhOpportunities);\n\n foreach ($bhOpportunities as $bhOpportunity) {\n $this->importOpportunity($bhOpportunity);\n $syncCount++;\n }\n } catch (\\Exception $exception) {\n $this->logger->info('Failed to sync opportunities', [\n 'params' => $parameters,\n 'exception' => $exception->getMessage(),\n ]);\n }\n\n // only log if there are one sync strategy\n if (count($strategies) === 1 && $total > $count + $offset) {\n $this->logger->info('[Bullhorn] Sync Opportunities - count warning', [\n 'team_id' => $this->team->getId(),\n 'total' => $total,\n 'count' => $count,\n 'offset' => $offset,\n ]);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhAccounts = $this->client->get('search/ClientCorporation', $params);\n\n foreach ($bhAccounts['data'] as $bhAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($bhAccount['id'])) {\n $this->importAccount($bhAccount);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhLeads = $this->client->get('search/Candidate', $params);\n if ($bhLeads === null) {\n return $syncCount;\n }\n\n foreach ($bhLeads['data'] as $bhLead) {\n // Only sync if previously imported.\n if ($this->hasLead($bhLead['id'])) {\n $this->importLead($bhLead);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n\n public function syncContact(string $crmId): ?Contact\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importContact($data['data']);\n }\n\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategy = $strategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n try {\n $data = $strategy->fetchOpportunities(['crm_id' => $crmId]);\n } catch (HttpNotFoundException $exception) {\n $this->logger->info('[Bullhorn] Opportunity not found', [\n 'crm_id' => $crmId,\n 'reason' => $exception->getMessage(),\n ]);\n }\n\n return $this->importOpportunity($data['data'] ?? []);\n }\n\n public function syncAccount(string $crmId): ?Account\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importAccount($data['data']);\n }\n\n public function syncLead(string $crmId): ?Lead\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importLead($data['data']);\n }\n\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $missingStage = null;\n\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n\n foreach ($types as $type) {\n $resource = $this->convertObjectTypeToResource($type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => 'status',\n 'meta' => 'full',\n ]);\n\n $missingStage = null;\n\n if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {\n throw new \\UnexpectedValueException('Invalid response from Bullhorn API');\n }\n\n // Upsert all stages for the team.\n foreach ($entity['fields'][0]['options'] as $i => $option) {\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $option['value'],\n 'type' => $type,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($option['value'], 0, 50),\n 'label' => mb_strimwidth($option['label'], 0, 191),\n 'sequence' => $i,\n 'is_selectable' => 1,\n ]);\n\n if ($missingStageName && $missingStageName === $option['value']) {\n $missingStage = $stage;\n }\n }\n\n if ($missingStageName && $missingStage === null) {\n // If they requested a stage that still doesn't exist, it must be inactive so lazy create it.\n $missingStage = $this->config->stages()->create([\n 'team_id' => $this->team->id,\n 'crm_provider_id' => Uuid::uuid4(),\n 'name' => mb_strimwidth($missingStageName, 0, 50),\n 'label' => mb_strimwidth($missingStageName, 0, 191),\n 'type' => $type,\n 'sequence' => 0,\n 'is_selectable' => 0,\n ]);\n }\n }\n\n return $missingStage;\n }\n\n public function syncOrganization(): void\n {\n // There appears to be nothing we can sync/map to.\n }\n\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $data = \\Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {\n $result = [];\n\n try {\n $objects = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => $count,\n ]);\n } catch (\\GuzzleHttp\\Exception\\ServerException $exception) {\n throw new ServiceUnavailableException($exception->getMessage());\n }\n\n foreach ($objects['data'] as $object) {\n try {\n $prospectType = $this->convertResourceToObjectType($object['entityType']);\n } catch (\\UnexpectedValueException $exception) {\n // We don't support this, so skip it.\n continue;\n }\n\n $record = [\n 'crmId' => $object['entityId'],\n 'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),\n 'prospectType' => $prospectType,\n 'phoneNumbers' => [],\n ];\n\n // Unfortunately we need to go and query each entity itself to get the data we need.\n switch ($object['entityType']) {\n case self::ENTITY_ACCOUNT:\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['industry'] = $entity['industryList'];\n if (empty($entity['phone']) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity['phone'],\n 'nationalFormat' => phone_national(null, $entity['phone']),\n 'type' => 'phone',\n ];\n }\n\n break;\n\n case self::ENTITY_CONTACT:\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n case self::ENTITY_LEAD:\n $bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);\n $entity = $bhData['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['companyName'];\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n default:\n // We are not interested in this entity type so skip it.\n continue 2;\n }\n\n $result[] = $record;\n }\n\n return $result;\n });\n\n return $data;\n }\n\n public function getClient(): BullhornClientInterface\n {\n return $this->client;\n }\n\n private function getFieldsAsString(array $fields)\n {\n return implode(', ', $fields);\n }\n\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),\n ];\n\n $onlyOpen = true;\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort'] = '-dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort'] = '+dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n $onlyOpen = false;\n }\n\n if ($onlyOpen) {\n $where .= ' AND isOpen: true';\n }\n\n $params['query'] = $where;\n\n $bhOpportunities = $this->client->get('search/JobOrder', $params);\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n foreach ($bhOpportunities['data'] as $bhOpportunity) {\n $stage = $this->config\n ->stages()\n ->where('crm_provider_id', $bhOpportunity['status'])\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);\n }\n\n $record = [\n 'crmId' => $bhOpportunity['id'],\n 'name' => $bhOpportunity['title'],\n 'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),\n 'won' => strtolower($bhOpportunity['status']) === 'placed',\n 'closed' => $bhOpportunity['isOpen'] !== true,\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n 'recordType' => [],\n ];\n\n if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = [];\n\n // For now it has not been agreed on how to implement this e.g. appointments or tasks?\n return [];\n\n if ($objectType === 'account' && $opportunityId === null) {\n // You cannot attach tasks to only accounts.\n return [];\n }\n\n // Query should default to any open task.\n $where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;\n\n // If we are also going to check on a specific job order, set that up.\n if ($opportunityId) {\n $where .= ' OR JobOrder: ' . (int) $opportunityId;\n }\n\n $where .= ')';\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => $where,\n ];\n\n $bhTasks = $this->client->get('search/Task', $params);\n\n foreach ($bhTasks['data'] as $bhTask) {\n $data[] = [\n 'crmId' => $bhTask['id'],\n 'subject' => $bhTask['subject'],\n 'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),\n 'type' => null,\n ];\n }\n\n return $data;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * ?Lead,\n * ?Account,\n * ?Opportunity,\n * ?Contact,\n * ?Stage,\n * ?string\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $bhObject = $this->client->get('find', [\n 'query' => $email,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember === false) {\n $bhObject = $this->client->get('find', [\n 'query' => $rawPhoneNumber ?? $phone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n if (empty($bhObject['data'])) {\n $nationalPhone = phone_national(null, $rawPhoneNumber ?? $phone);\n $formattedPhone = ltrim($nationalPhone, '+0');\n $bhObject = $this->client->get('find', [\n 'query' => $formattedPhone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n }\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n return null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 3) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = \\Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n $bhObject = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->team->getId() . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n public function saveActivity(Activity $activity): Activity\n {\n\n if ($activity->hasCrmProviderId()) {\n return $activity;\n }\n\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildNotePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n /**\n * @throws CrmException\n * @throws DomainException\n */\n private function buildNotePayload(Activity $activity): Activity\n {\n if ($activity->hasActivityType() === false) {\n throw new DomainException('[Bullhorn] No activity type assigned');\n }\n\n $action = $this->getCrmType($activity->getActivityType());\n if ($action === null) {\n throw new DomainException('[Bullhorn] No mapped CRM type for \"' . $activity->category->name . '\"');\n }\n\n if ($activity->lead_id === null && $activity->contact_id === null) {\n throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');\n }\n\n $payload = [\n 'comments' => $this->generateActivityDescription($activity),\n 'action' => $action->value,\n 'commentingPerson' => [\n 'id' => (int) $this->profile->crm_provider_id,\n 'type' => 'CorporateUser',\n ],\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n 'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),\n ];\n\n if ($activity->lead_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->lead->crm_provider_id,\n 'type' => 'Candidate',\n ];\n }\n\n if ($activity->contact_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->contact->crm_provider_id,\n 'type' => 'ClientContact',\n ];\n }\n\n if ($activity->opportunity_id) {\n $payload['jobOrders'] = [\n 'replaceAll' => [\n (int) $activity->opportunity->crm_provider_id,\n ],\n ];\n }\n\n $bhActivity = $this->client->put('entity/Note', $payload);\n\n $activity->crm_provider_id = $bhActivity['changedEntityId'];\n $activity->save();\n\n return $activity;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = '';\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: %s</span></p>',\n $activity->to->phone_number,\n );\n }\n $description .= '<p></p>';\n }\n\n if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: %s</span></p>',\n $activity->from->phone_number,\n );\n $description .= '<p></p>';\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span>'\n . '</p>';\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span>'\n . '</p>';\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= sprintf(\n '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . '<a href=\"%s\" target=\"_blank\">'\n . 'Review in Jiminny'\n . '</a>'\n . '️</span>'\n . '</p>',\n $playbackUrl,\n );\n }\n\n if ($activity->isTypeConference()) {\n $description .= '<p><strong>Attendees</strong></p><ul>';\n\n // Only include participants that joined.\n $participants = $activity->participants()->ghost(false)->whereNotNull('enter_time')->get();\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->name) {\n $attendee .= $participant->name;\n if ($participant->phone_number) {\n $attendee .= ' (' . $participant->phone_number . ')';\n } elseif ($participant->email) {\n $attendee .= ' (' . $participant->email . ')';\n }\n } else {\n $attendee .= $participant->phone_number;\n }\n\n if ($participant->is_ghost) {\n $attendee .= ' <strong>coach</coach>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $description .= $attendee . '</li>';\n }\n $description .= '</ul>';\n }\n\n if (count($activity->notes) > 0) {\n $description .= '<p><strong>Notes</strong></p>';\n\n foreach ($activity->notes as $note) {\n $time = ($note->time > 3600) ? gmdate('H:i:s', $note->time) : gmdate('i:s', $note->time);\n $description .= '<p>' . $time . ' ' . $note->note . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n if ($activity->summary) {\n $description .= '<p><strong>Summary</strong></p><p>' . $activity->summary . '</p><p></p>';\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n // Use Rich-text formatting.\n $description = sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>%s</strong></span></p>',\n $activity->title,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->description,\n );\n\n break;\n }\n\n return $description;\n }\n\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // Not yet required by current customers.\n return null;\n }\n\n public function updateStage($crmObject, Stage $stage): void\n {\n $objectId = $crmObject->crm_provider_id;\n\n $this->updateRecord($stage->type, $objectId, ['status' => $stage->crm_provider_id]);\n }\n\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $start = 0;\n $payload = [\n 'fields' => 'id,email',\n 'where' => 'isDeleted=false',\n 'count' => 500,\n ];\n\n $payload['start'] = $start;\n $profiles = $this->client->get('query/CorporateUser', $payload);\n\n foreach ($profiles['data'] as $profile) {\n if (empty($profile['email'])) {\n continue;\n }\n\n $user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);\n\n // Only import profiles for users we have locally.\n if ($user) {\n $profile = $user->crmProfile()->updateOrCreate([\n 'crm_configuration_id' => $this->config->id,\n 'crm_provider_id' => $profile['id'],\n ]);\n\n if ($userToSearch && $userToSearch->id === $user->id) {\n return $profile;\n }\n }\n }\n\n return null;\n }\n\n protected function convertCrmData(array $entities, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n $mappedEntities = [];\n foreach ($entities as $entity) {\n if (in_array($entity['entityType'], [self::ENTITY_LEAD, self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n $mappedEntities[] = $entity;\n }\n }\n\n // If there is only one match, sync the data and return the object(s).\n if (count($mappedEntities) === 1) {\n $entity = $mappedEntities[0];\n\n if ($entity['entityType'] === self::ENTITY_LEAD) {\n $lead = $this->syncLead($entity['entityId']);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } elseif (in_array($entity['entityType'], [self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n if ($entity['entityType'] === self::ENTITY_CONTACT) {\n $contact = $this->syncContact($entity['entityId']);\n $account = $contact->account;\n } else {\n $account = $this->syncAccount($entity['entityId']);\n }\n\n if ($contact?->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $bhOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact?->crm_provider_id,\n $userId,\n );\n\n // Take the first opportunity, which will be ordered as priority based on their settings.\n if (! empty($bhOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($bhOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n } catch (Exception) {\n // Nothing to see here.\n }\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n // There doesn't appear to be a way to deeplink to anything on https://app.bullhornstaffing.com.\n return null;\n }\n\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $this->client->post('entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId, $data);\n }\n\n public function getRecord(string $objectType, string $objectId, array $fields = ['id']): array\n {\n return $this->client->get(\n url: 'entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId,\n data: ['fields' => $this->getFieldsAsString($fields)],\n );\n }\n\n private function convertObjectTypeToResource(string $objectType)\n {\n switch ($objectType) {\n case FieldData::OBJECT_OPPORTUNITY:\n return self::ENTITY_OPPORTUNITY;\n\n case FieldData::OBJECT_CONTACT:\n return self::ENTITY_CONTACT;\n\n case FieldData::OBJECT_LEAD:\n return self::ENTITY_LEAD;\n\n case FieldData::OBJECT_ACCOUNT:\n return self::ENTITY_ACCOUNT;\n\n case FieldData::OBJECT_TASK:\n return self::ENTITY_ACTIVITY;\n\n default:\n throw new \\UnexpectedValueException('Unsupported object type \"' . $objectType . '\"');\n }\n }\n\n private function convertResourceToObjectType(string $resource): string\n {\n switch ($resource) {\n case self::ENTITY_OPPORTUNITY:\n return FieldData::OBJECT_OPPORTUNITY;\n\n case self::ENTITY_CONTACT:\n return FieldData::OBJECT_CONTACT;\n\n case self::ENTITY_LEAD:\n return FieldData::OBJECT_LEAD;\n\n case self::ENTITY_ACCOUNT:\n return FieldData::OBJECT_ACCOUNT;\n\n case self::ENTITY_ACTIVITY:\n return FieldData::OBJECT_TASK;\n\n default:\n throw new \\UnexpectedValueException('Unsupported resource \"' . $resource . '\"');\n }\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n // We need to know when it started to determine when to look for related activity.\n if ($activity->hasActualStartTime() === false) {\n return null;\n }\n\n try {\n $bhNote = $this->fetchRelatedActivity($activity);\n if (empty($bhNote)) {\n $this->logger->info('[Bullhorn] No related activity found', [\n 'activity' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $activityType = $this->getPlaybookCategory($this->getPlaybook($activity->user), $bhNote['action']);\n $comments = $bhNote['comments'] . '<br />//<br />' . $this->generateActivityDescription($activity);\n // Now update the Note to contain our data.\n $payload = [\n 'comments' => $comments,\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n ];\n\n $this->logger->info('[Bullhorn] updating related activity', [\n 'activity' => $activity->getUuid(),\n 'activityType' => $activityType->id ?? null,\n ]);\n\n $this->client->post('entity/Note/' . $bhNote['id'], $payload);\n\n $playbookCategoryId = null;\n if ($activity->getCategory() !== null) {\n $playbookCategoryId = $activity->getCategory()->getId();\n }\n\n // Update our activity to reflect the remote data.\n $activity->update([\n 'crm_provider_id' => $bhNote['id'],\n 'summary' => $bhNote['comments'],\n 'playbook_category_id' => $activityType->id ?? $playbookCategoryId,\n ]);\n\n return $activity;\n } catch (\\Exception $exception) {\n \\Sentry::captureException($exception);\n\n throw $exception;\n }\n }\n\n /**\n * Returns the most recently modified note within time range (if any).\n *\n * @return array A Note record from Bullhorn.\n */\n public function fetchRelatedActivity(Activity $activity): array\n {\n $from = $activity->hasScheduledStartTime()\n ? $activity->getScheduledStartTime()\n : $activity->getActualStartTime();\n $to = $activity->hasActualEndTime()\n ? $activity->getActualEndTime()?->addMinutes(15)\n : $from?->clone()->addMinutes(15);\n\n $filterStatements = [\n 'isDeleted: false',\n '*:* -externalID:[* TO *]', // externalID should be null e.g. we did not already relate it.\n sprintf('commentingPerson: %d', (int) $this->profile->crm_provider_id),\n ];\n\n /**\n * @XXX: Bullhorn does not specify the time zone in their docs. I've found a forum thread in which someone from\n * staff asserts it's UTC, however in my field test I've found it to be GMT-0300 (USA east coast).\n * To make the code immune to such glitches we will add 24h to start/end boundaries and will filter out\n * any excess items in code\n */\n $filterStatements[] = sprintf(\n 'dateLastModified:[%s TO %s]',\n $from?->clone()->subHours(24)->format('YmdHis'),\n $to->clone()->addHours(24)->format('YmdHis'),\n );\n\n if ($activity->lead_id) {\n $filterStatements[] = sprintf('candidateUserID: %d', (int) $activity->lead->crm_provider_id);\n }\n\n if ($activity->contact_id) {\n $filterStatements[] = sprintf('clientContactUserID: %d', (int) $activity->contact->crm_provider_id);\n }\n\n // if there is no contact or lead associated to the activity exit\n if ($activity->contact_id === null && $activity->lead_id === null) {\n return [];\n }\n\n $params = [\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => implode(' AND ', $filterStatements),\n 'sort' => '-dateLastModified',\n ];\n\n $bhNotes = $this->client->get('search/Note', $params);\n\n $startStamp = $from?->getTimestamp() * 1000;\n $endStamp = $to->getTimestamp() * 1000;\n\n $filteredNotes = array_values(\n array_filter(\n $bhNotes['data'],\n static fn (array $bhNote): bool\n => $bhNote['dateLastModified'] >= $startStamp && $startStamp <= $endStamp,\n ),\n );\n\n return ! empty($filteredNotes) ? array_shift($filteredNotes) : [];\n }\n\n /**\n * Select how to create the date out of the Bullhorn payload.\n * Do not allow dates beyond 9999-12-31 (max mysql DATE)\n */\n private function filterOutOfBoundDates(string $rawDateCandidate): ?Carbon\n {\n if (strlen($rawDateCandidate) > 12) {\n // A unix timestamp represented with more than 12 digits i\n // s definitely including milliseconds\n $dateFormatted = Carbon::createFromTimestampMs($rawDateCandidate);\n } else {\n $dateFormatted = Carbon::createFromTimestamp($rawDateCandidate);\n }\n\n $minDate = Carbon::createFromFormat('Y-m-d', '2000-01-01');\n if ($dateFormatted->lt($minDate)) {\n return null;\n }\n\n $maxDate = Carbon::createFromFormat('Y-m-d', '9999-12-31');\n if ($dateFormatted->gt($maxDate)) {\n $this->logger->warning('[Bullhorn] An out of bound date is provided', [\n 'date' => $dateFormatted,\n 'rawDate' => $rawDateCandidate,\n ]);\n\n return $maxDate;\n }\n\n return $dateFormatted;\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n $note = $this->getRecord('Note', $crmProviderId, ['id', 'isDeleted']);\n\n return ! empty($note) && ($note['isDeleted'] ?? false) === false;\n } catch (HttpNotFoundException|HttpBadRequestException) {\n // Note not found in CRM - this is expected and permanent\n $this->logger->info('[Bullhorn] Note not found during verification', [\n 'note_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Bullhorn;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\BullhornInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\ApplicationException;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\DomainException;\nuse Jiminny\\Exceptions\\HttpBadRequestException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\ServiceUnavailableException;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\UserRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\nuse Ramsey\\Uuid\\Uuid;\n\nclass BullhornService extends BaseService implements\n BullhornInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const string ENTITY_LEAD = 'Candidate';\n private const string ENTITY_OPPORTUNITY = 'JobOrder';\n private const string ENTITY_ACCOUNT = 'ClientCorporation';\n private const string ENTITY_CONTACT = 'ClientContact';\n private const string ENTITY_ACTIVITY = 'Note';\n\n private const array OPPORTUNITY_FIELDS = [\n 'id',\n 'owner',\n 'status',\n 'title',\n 'salary',\n 'salaryUnit',\n 'payRate',\n 'isOpen',\n 'employmentType',\n 'dateClosed',\n 'startDate',\n 'dateLastModified',\n 'dateAdded',\n 'clientCorporation',\n 'correlatedCustomText10', // currency\n ];\n\n private const array TASK_FIELDS = [\n 'id',\n 'comments',\n 'dateAdded',\n 'dateLastModified',\n 'externalID',\n 'isDeleted',\n 'corporateUsers',\n 'clientContacts',\n 'commentingPerson',\n 'candidates',\n 'jobOrder',\n 'minutesSpent',\n 'action',\n ];\n\n private const array LEAD_FIELDS = [\n 'id',\n 'name',\n 'owner',\n 'occupation',\n 'companyName',\n 'companyURL',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'workPhone',\n 'status',\n 'address',\n 'dateAdded',\n 'dateLastModified',\n ];\n\n private const array CONTACT_FIELDS = [\n 'id',\n 'name',\n 'occupation',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'address',\n 'clientCorporation',\n 'dateAdded',\n 'owner',\n ];\n\n private const array ACCOUNT_FIELDS = [\n 'id',\n 'name',\n 'phone',\n 'industryList',\n 'address',\n 'companyURL',\n 'dateAdded',\n ];\n\n public function __construct(\n BullhornClientInterface $client,\n private readonly UserRepository $userRepository,\n private readonly ProspectPhotoPathService $prospectPhotoPathService\n ) {\n parent::__construct();\n\n $this->client = $client;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);\n }\n\n public function getDisplayName(): string\n {\n return 'Bullhorn';\n }\n\n public function createTranscriptNotes(Activity $activity): void\n {\n // Not done until a customer requests it.\n }\n\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n 'task',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))\n );\n\n if (! empty($changedFields)) {\n $fields = implode(',', $newFields);\n Log::debug(\n sprintf(\n '%s fields changed from %s to: %s',\n ucfirst($fieldType),\n $this->profile->{$fieldType . '_fields'},\n $fields,\n ),\n );\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (\\Exception $exception) {\n \\Log::error('No access to ' . $fieldType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n //parent::OBJECT_ACCOUNT,\n //parent::OBJECT_CONTACT,\n //parent::OBJECT_OPPORTUNITY,\n //parent::OBJECT_LEAD,\n ];\n }\n\n protected function getFields(string $crmObject): array\n {\n $fields = [];\n foreach ($this->getObjectFields($crmObject) as $row) {\n $fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];\n }\n\n return $fields;\n }\n\n private function getObjectFields(string $objectType): array\n {\n $entityType = $this->convertObjectTypeToResource($objectType);\n\n return Cache::remember(\n key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,\n ttl: 60 * 60,\n callback: function () use ($entityType) {\n $entity = $this->client->get('meta/' . $entityType, [\n 'fields' => '*',\n ]);\n\n return $entity['fields'];\n },\n );\n }\n\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n $defaultFields = FieldDefinitions::defaultFields();\n\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n\n return $fields;\n }\n\n public function getDefaultActivityField(string $activityType): Field\n {\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'action',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n // We are not yet supporting follow-ups for this system.\n return [];\n }\n\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return $fieldValue;\n }\n\n public function syncField(Field $field): void\n {\n $resource = $this->convertObjectTypeToResource($field->object_type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => $field->crm_provider_id,\n 'meta' => 'full',\n ]);\n\n $bhField = $entity['fields'][0];\n\n $isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);\n $description = null;\n if (empty($bhField['description']) === false) {\n $description = mb_strimwidth($bhField['description'], 0, 191);\n }\n\n $label = 'Unknown';\n if (empty($bhField['label']) === false) {\n $label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);\n }\n\n $field->length = $bhField['maxLength'] ?? null;\n $field->is_mandatory = $isMandatory;\n $field->description = $description;\n $field->label = $label;\n $field->type = $this->convertFieldType(\n $bhField['dataType'] ?? null,\n $bhField['dataSpecialization'] ?? null,\n $bhField['inputType'] ?? null\n );\n\n $field->save();\n\n if (empty($bhField['options']) === false) {\n $values = [];\n\n // Import all values.\n foreach ($bhField['options'] as $i => $option) {\n $values[] = [\n 'value' => $option['value'],\n 'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),\n 'sequence' => $i,\n ];\n }\n\n // Take the existing set of field values.\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n // For all current values, upsert the field.\n $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n $key = array_search($value['value'], $fieldsToPurge, false);\n if ($key !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n }\n }\n\n public function importPicklistValues(Field $field): array\n {\n // Taken care of in syncField.\n return [];\n }\n\n private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string\n {\n if ($type === null) {\n return Field::TYPE_UNSUPPORTED;\n }\n\n $type = strtolower($type);\n $specialization = strtolower($specialization);\n $inputType = strtolower($inputType);\n\n switch ($type) {\n case 'boolean':\n return Field::TYPE_BOOLEAN;\n\n case 'integer':\n switch ($specialization) {\n case 'integer':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'bigdecimal':\n switch ($specialization) {\n case 'money':\n return Field::TYPE_CURRENCY;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'double':\n switch ($specialization) {\n case 'float':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'timestamp':\n switch ($specialization) {\n case 'date':\n return Field::TYPE_DATE;\n case 'time':\n return Field::TYPE_TIME;\n case 'datetime':\n return Field::TYPE_DATETIME;\n default:\n return Field::TYPE_DATE;\n }\n\n // no break\n case 'string':\n switch ($inputType) {\n case 'textarea':\n return Field::TYPE_TEXTAREA;\n case 'select':\n return Field::TYPE_PICKLIST;\n default:\n return Field::TYPE_TEXT;\n }\n\n // no break\n default:\n // This is not actually a supported field.\n return Field::TYPE_UNSUPPORTED;\n }\n }\n\n private function importContact($crmData): Contact\n {\n $account = $mobilePhone = $phone = $email = null;\n if (empty($crmData['clientCorporation']) === false) {\n $account = $this->team\n ->accounts()\n ->where('crm_provider_id', $crmData['clientCorporation']['id'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n }\n\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => $crmData['name'],\n 'email' => $email,\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'title' => $crmData['occupation'],\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Contact::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n if ($crmData['clientCorporation']['id']) {\n $account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n } else {\n // If there is nothing to associate this with, don't import it.\n return null;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $stage = $this->config->stages()\n ->where('crm_provider_id', $crmData['status'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => mb_strimwidth($crmData['title'], 0, 128),\n 'value' => $crmData['salary'] ?? $crmData['payRate'],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),\n 'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),\n 'is_closed' => $crmData['isOpen'] !== true,\n 'is_won' => strtolower($crmData['status']) === 'placed',\n 'stage_id' => $stage->id,\n 'record_type_id' => null,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importAccount($crmData): Account\n {\n $countryCode = $domain = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $name = $crmData['name'] ?? 'Unknown';\n\n if ($crmData['companyURL'] !== null) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => null,\n 'owner_id' => null,\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Account::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'country_code' => $countryCode,\n 'domain' => $domain,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importLead($crmData): ?Lead\n {\n // Get the current stage.\n $stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);\n }\n\n // If we have no way of importing this, just return null :(\n if ($stage === null) {\n return null;\n }\n\n $countryCode = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $mobilePhone = $phone = $email = null;\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $company = 'Unknown';\n if (empty($crmData['companyName']) === false) {\n $companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];\n $company = mb_strimwidth($companyName, 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['companyURL']) === false) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'company' => $company,\n 'domain' => $domain,\n 'name' => mb_strimwidth($crmData['name'], 0, 191),\n 'title' => mb_strimwidth($crmData['occupation'], 0, 128),\n 'email' => mb_strimwidth($email, 0, 80),\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Lead::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'stage_id' => $stage->id,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhContacts = $this->client->get('search/ClientContact', $params);\n\n foreach ($bhContacts['data'] as $bhContact) {\n // Only sync if previously imported.\n if ($this->hasContact($bhContact['id'])) {\n $this->importContact($bhContact);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategies = $strategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n $total = 0;\n $count = 0;\n $offset = 0;\n\n try {\n $bhOpportunities = [];\n foreach ($strategies as $syncStrategy) {\n $opportunitiesData = $syncStrategy->fetchOpportunities($parameters);\n $total = (int) ($opportunitiesData['total'] ?? 0);\n $count = (int) ($opportunitiesData['count'] ?? 0);\n $offset = (int) ($opportunitiesData['start'] ?? 0);\n $bhOpportunities[] = $opportunitiesData['data'] ?? [];\n }\n\n $bhOpportunities = array_merge(...$bhOpportunities);\n\n foreach ($bhOpportunities as $bhOpportunity) {\n $this->importOpportunity($bhOpportunity);\n $syncCount++;\n }\n } catch (\\Exception $exception) {\n $this->logger->info('Failed to sync opportunities', [\n 'params' => $parameters,\n 'exception' => $exception->getMessage(),\n ]);\n }\n\n // only log if there are one sync strategy\n if (count($strategies) === 1 && $total > $count + $offset) {\n $this->logger->info('[Bullhorn] Sync Opportunities - count warning', [\n 'team_id' => $this->team->getId(),\n 'total' => $total,\n 'count' => $count,\n 'offset' => $offset,\n ]);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhAccounts = $this->client->get('search/ClientCorporation', $params);\n\n foreach ($bhAccounts['data'] as $bhAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($bhAccount['id'])) {\n $this->importAccount($bhAccount);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhLeads = $this->client->get('search/Candidate', $params);\n if ($bhLeads === null) {\n return $syncCount;\n }\n\n foreach ($bhLeads['data'] as $bhLead) {\n // Only sync if previously imported.\n if ($this->hasLead($bhLead['id'])) {\n $this->importLead($bhLead);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n\n public function syncContact(string $crmId): ?Contact\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importContact($data['data']);\n }\n\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategy = $strategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n try {\n $data = $strategy->fetchOpportunities(['crm_id' => $crmId]);\n } catch (HttpNotFoundException $exception) {\n $this->logger->info('[Bullhorn] Opportunity not found', [\n 'crm_id' => $crmId,\n 'reason' => $exception->getMessage(),\n ]);\n }\n\n return $this->importOpportunity($data['data'] ?? []);\n }\n\n public function syncAccount(string $crmId): ?Account\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importAccount($data['data']);\n }\n\n public function syncLead(string $crmId): ?Lead\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importLead($data['data']);\n }\n\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $missingStage = null;\n\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n\n foreach ($types as $type) {\n $resource = $this->convertObjectTypeToResource($type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => 'status',\n 'meta' => 'full',\n ]);\n\n $missingStage = null;\n\n if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {\n throw new \\UnexpectedValueException('Invalid response from Bullhorn API');\n }\n\n // Upsert all stages for the team.\n foreach ($entity['fields'][0]['options'] as $i => $option) {\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $option['value'],\n 'type' => $type,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($option['value'], 0, 50),\n 'label' => mb_strimwidth($option['label'], 0, 191),\n 'sequence' => $i,\n 'is_selectable' => 1,\n ]);\n\n if ($missingStageName && $missingStageName === $option['value']) {\n $missingStage = $stage;\n }\n }\n\n if ($missingStageName && $missingStage === null) {\n // If they requested a stage that still doesn't exist, it must be inactive so lazy create it.\n $missingStage = $this->config->stages()->create([\n 'team_id' => $this->team->id,\n 'crm_provider_id' => Uuid::uuid4(),\n 'name' => mb_strimwidth($missingStageName, 0, 50),\n 'label' => mb_strimwidth($missingStageName, 0, 191),\n 'type' => $type,\n 'sequence' => 0,\n 'is_selectable' => 0,\n ]);\n }\n }\n\n return $missingStage;\n }\n\n public function syncOrganization(): void\n {\n // There appears to be nothing we can sync/map to.\n }\n\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $data = \\Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {\n $result = [];\n\n try {\n $objects = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => $count,\n ]);\n } catch (\\GuzzleHttp\\Exception\\ServerException $exception) {\n throw new ServiceUnavailableException($exception->getMessage());\n }\n\n foreach ($objects['data'] as $object) {\n try {\n $prospectType = $this->convertResourceToObjectType($object['entityType']);\n } catch (\\UnexpectedValueException $exception) {\n // We don't support this, so skip it.\n continue;\n }\n\n $record = [\n 'crmId' => $object['entityId'],\n 'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),\n 'prospectType' => $prospectType,\n 'phoneNumbers' => [],\n ];\n\n // Unfortunately we need to go and query each entity itself to get the data we need.\n switch ($object['entityType']) {\n case self::ENTITY_ACCOUNT:\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['industry'] = $entity['industryList'];\n if (empty($entity['phone']) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity['phone'],\n 'nationalFormat' => phone_national(null, $entity['phone']),\n 'type' => 'phone',\n ];\n }\n\n break;\n\n case self::ENTITY_CONTACT:\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n case self::ENTITY_LEAD:\n $bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);\n $entity = $bhData['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['companyName'];\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n default:\n // We are not interested in this entity type so skip it.\n continue 2;\n }\n\n $result[] = $record;\n }\n\n return $result;\n });\n\n return $data;\n }\n\n public function getClient(): BullhornClientInterface\n {\n return $this->client;\n }\n\n private function getFieldsAsString(array $fields)\n {\n return implode(', ', $fields);\n }\n\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),\n ];\n\n $onlyOpen = true;\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort'] = '-dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort'] = '+dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n $onlyOpen = false;\n }\n\n if ($onlyOpen) {\n $where .= ' AND isOpen: true';\n }\n\n $params['query'] = $where;\n\n $bhOpportunities = $this->client->get('search/JobOrder', $params);\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n foreach ($bhOpportunities['data'] as $bhOpportunity) {\n $stage = $this->config\n ->stages()\n ->where('crm_provider_id', $bhOpportunity['status'])\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);\n }\n\n $record = [\n 'crmId' => $bhOpportunity['id'],\n 'name' => $bhOpportunity['title'],\n 'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),\n 'won' => strtolower($bhOpportunity['status']) === 'placed',\n 'closed' => $bhOpportunity['isOpen'] !== true,\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n 'recordType' => [],\n ];\n\n if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = [];\n\n // For now it has not been agreed on how to implement this e.g. appointments or tasks?\n return [];\n\n if ($objectType === 'account' && $opportunityId === null) {\n // You cannot attach tasks to only accounts.\n return [];\n }\n\n // Query should default to any open task.\n $where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;\n\n // If we are also going to check on a specific job order, set that up.\n if ($opportunityId) {\n $where .= ' OR JobOrder: ' . (int) $opportunityId;\n }\n\n $where .= ')';\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => $where,\n ];\n\n $bhTasks = $this->client->get('search/Task', $params);\n\n foreach ($bhTasks['data'] as $bhTask) {\n $data[] = [\n 'crmId' => $bhTask['id'],\n 'subject' => $bhTask['subject'],\n 'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),\n 'type' => null,\n ];\n }\n\n return $data;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * ?Lead,\n * ?Account,\n * ?Opportunity,\n * ?Contact,\n * ?Stage,\n * ?string\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $bhObject = $this->client->get('find', [\n 'query' => $email,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember === false) {\n $bhObject = $this->client->get('find', [\n 'query' => $rawPhoneNumber ?? $phone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n if (empty($bhObject['data'])) {\n $nationalPhone = phone_national(null, $rawPhoneNumber ?? $phone);\n $formattedPhone = ltrim($nationalPhone, '+0');\n $bhObject = $this->client->get('find', [\n 'query' => $formattedPhone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n }\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n return null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 3) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = \\Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n $bhObject = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->team->getId() . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n public function saveActivity(Activity $activity): Activity\n {\n\n if ($activity->hasCrmProviderId()) {\n return $activity;\n }\n\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildNotePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n /**\n * @throws CrmException\n * @throws DomainException\n */\n private function buildNotePayload(Activity $activity): Activity\n {\n if ($activity->hasActivityType() === false) {\n throw new DomainException('[Bullhorn] No activity type assigned');\n }\n\n $action = $this->getCrmType($activity->getActivityType());\n if ($action === null) {\n throw new DomainException('[Bullhorn] No mapped CRM type for \"' . $activity->category->name . '\"');\n }\n\n if ($activity->lead_id === null && $activity->contact_id === null) {\n throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');\n }\n\n $payload = [\n 'comments' => $this->generateActivityDescription($activity),\n 'action' => $action->value,\n 'commentingPerson' => [\n 'id' => (int) $this->profile->crm_provider_id,\n 'type' => 'CorporateUser',\n ],\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n 'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),\n ];\n\n if ($activity->lead_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->lead->crm_provider_id,\n 'type' => 'Candidate',\n ];\n }\n\n if ($activity->contact_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->contact->crm_provider_id,\n 'type' => 'ClientContact',\n ];\n }\n\n if ($activity->opportunity_id) {\n $payload['jobOrders'] = [\n 'replaceAll' => [\n (int) $activity->opportunity->crm_provider_id,\n ],\n ];\n }\n\n $bhActivity = $this->client->put('entity/Note', $payload);\n\n $activity->crm_provider_id = $bhActivity['changedEntityId'];\n $activity->save();\n\n return $activity;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = '';\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: %s</span></p>',\n $activity->to->phone_number,\n );\n }\n $description .= '<p></p>';\n }\n\n if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: %s</span></p>',\n $activity->from->phone_number,\n );\n $description .= '<p></p>';\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span>'\n . '</p>';\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span>'\n . '</p>';\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= sprintf(\n '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . '<a href=\"%s\" target=\"_blank\">'\n . 'Review in Jiminny'\n . '</a>'\n . '️</span>'\n . '</p>',\n $playbackUrl,\n );\n }\n\n if ($activity->isTypeConference()) {\n $description .= '<p><strong>Attendees</strong></p><ul>';\n\n // Only include participants that joined.\n $participants = $activity->participants()->ghost(false)->whereNotNull('enter_time')->get();\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->name) {\n $attendee .= $participant->name;\n if ($participant->phone_number) {\n $attendee .= ' (' . $participant->phone_number . ')';\n } elseif ($participant->email) {\n $attendee .= ' (' . $participant->email . ')';\n }\n } else {\n $attendee .= $participant->phone_number;\n }\n\n if ($participant->is_ghost) {\n $attendee .= ' <strong>coach</coach>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $description .= $attendee . '</li>';\n }\n $description .= '</ul>';\n }\n\n if (count($activity->notes) > 0) {\n $description .= '<p><strong>Notes</strong></p>';\n\n foreach ($activity->notes as $note) {\n $time = ($note->time > 3600) ? gmdate('H:i:s', $note->time) : gmdate('i:s', $note->time);\n $description .= '<p>' . $time . ' ' . $note->note . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n if ($activity->summary) {\n $description .= '<p><strong>Summary</strong></p><p>' . $activity->summary . '</p><p></p>';\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n // Use Rich-text formatting.\n $description = sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>%s</strong></span></p>',\n $activity->title,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->description,\n );\n\n break;\n }\n\n return $description;\n }\n\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // Not yet required by current customers.\n return null;\n }\n\n public function updateStage($crmObject, Stage $stage): void\n {\n $objectId = $crmObject->crm_provider_id;\n\n $this->updateRecord($stage->type, $objectId, ['status' => $stage->crm_provider_id]);\n }\n\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $start = 0;\n $payload = [\n 'fields' => 'id,email',\n 'where' => 'isDeleted=false',\n 'count' => 500,\n ];\n\n $payload['start'] = $start;\n $profiles = $this->client->get('query/CorporateUser', $payload);\n\n foreach ($profiles['data'] as $profile) {\n if (empty($profile['email'])) {\n continue;\n }\n\n $user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);\n\n // Only import profiles for users we have locally.\n if ($user) {\n $profile = $user->crmProfile()->updateOrCreate([\n 'crm_configuration_id' => $this->config->id,\n 'crm_provider_id' => $profile['id'],\n ]);\n\n if ($userToSearch && $userToSearch->id === $user->id) {\n return $profile;\n }\n }\n }\n\n return null;\n }\n\n protected function convertCrmData(array $entities, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n $mappedEntities = [];\n foreach ($entities as $entity) {\n if (in_array($entity['entityType'], [self::ENTITY_LEAD, self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n $mappedEntities[] = $entity;\n }\n }\n\n // If there is only one match, sync the data and return the object(s).\n if (count($mappedEntities) === 1) {\n $entity = $mappedEntities[0];\n\n if ($entity['entityType'] === self::ENTITY_LEAD) {\n $lead = $this->syncLead($entity['entityId']);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } elseif (in_array($entity['entityType'], [self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n if ($entity['entityType'] === self::ENTITY_CONTACT) {\n $contact = $this->syncContact($entity['entityId']);\n $account = $contact->account;\n } else {\n $account = $this->syncAccount($entity['entityId']);\n }\n\n if ($contact?->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $bhOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact?->crm_provider_id,\n $userId,\n );\n\n // Take the first opportunity, which will be ordered as priority based on their settings.\n if (! empty($bhOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($bhOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n } catch (Exception) {\n // Nothing to see here.\n }\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n // There doesn't appear to be a way to deeplink to anything on https://app.bullhornstaffing.com.\n return null;\n }\n\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $this->client->post('entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId, $data);\n }\n\n public function getRecord(string $objectType, string $objectId, array $fields = ['id']): array\n {\n return $this->client->get(\n url: 'entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId,\n data: ['fields' => $this->getFieldsAsString($fields)],\n );\n }\n\n private function convertObjectTypeToResource(string $objectType)\n {\n switch ($objectType) {\n case FieldData::OBJECT_OPPORTUNITY:\n return self::ENTITY_OPPORTUNITY;\n\n case FieldData::OBJECT_CONTACT:\n return self::ENTITY_CONTACT;\n\n case FieldData::OBJECT_LEAD:\n return self::ENTITY_LEAD;\n\n case FieldData::OBJECT_ACCOUNT:\n return self::ENTITY_ACCOUNT;\n\n case FieldData::OBJECT_TASK:\n return self::ENTITY_ACTIVITY;\n\n default:\n throw new \\UnexpectedValueException('Unsupported object type \"' . $objectType . '\"');\n }\n }\n\n private function convertResourceToObjectType(string $resource): string\n {\n switch ($resource) {\n case self::ENTITY_OPPORTUNITY:\n return FieldData::OBJECT_OPPORTUNITY;\n\n case self::ENTITY_CONTACT:\n return FieldData::OBJECT_CONTACT;\n\n case self::ENTITY_LEAD:\n return FieldData::OBJECT_LEAD;\n\n case self::ENTITY_ACCOUNT:\n return FieldData::OBJECT_ACCOUNT;\n\n case self::ENTITY_ACTIVITY:\n return FieldData::OBJECT_TASK;\n\n default:\n throw new \\UnexpectedValueException('Unsupported resource \"' . $resource . '\"');\n }\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n // We need to know when it started to determine when to look for related activity.\n if ($activity->hasActualStartTime() === false) {\n return null;\n }\n\n try {\n $bhNote = $this->fetchRelatedActivity($activity);\n if (empty($bhNote)) {\n $this->logger->info('[Bullhorn] No related activity found', [\n 'activity' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $activityType = $this->getPlaybookCategory($this->getPlaybook($activity->user), $bhNote['action']);\n $comments = $bhNote['comments'] . '<br />//<br />' . $this->generateActivityDescription($activity);\n // Now update the Note to contain our data.\n $payload = [\n 'comments' => $comments,\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n ];\n\n $this->logger->info('[Bullhorn] updating related activity', [\n 'activity' => $activity->getUuid(),\n 'activityType' => $activityType->id ?? null,\n ]);\n\n $this->client->post('entity/Note/' . $bhNote['id'], $payload);\n\n $playbookCategoryId = null;\n if ($activity->getCategory() !== null) {\n $playbookCategoryId = $activity->getCategory()->getId();\n }\n\n // Update our activity to reflect the remote data.\n $activity->update([\n 'crm_provider_id' => $bhNote['id'],\n 'summary' => $bhNote['comments'],\n 'playbook_category_id' => $activityType->id ?? $playbookCategoryId,\n ]);\n\n return $activity;\n } catch (\\Exception $exception) {\n \\Sentry::captureException($exception);\n\n throw $exception;\n }\n }\n\n /**\n * Returns the most recently modified note within time range (if any).\n *\n * @return array A Note record from Bullhorn.\n */\n public function fetchRelatedActivity(Activity $activity): array\n {\n $from = $activity->hasScheduledStartTime()\n ? $activity->getScheduledStartTime()\n : $activity->getActualStartTime();\n $to = $activity->hasActualEndTime()\n ? $activity->getActualEndTime()?->addMinutes(15)\n : $from?->clone()->addMinutes(15);\n\n $filterStatements = [\n 'isDeleted: false',\n '*:* -externalID:[* TO *]', // externalID should be null e.g. we did not already relate it.\n sprintf('commentingPerson: %d', (int) $this->profile->crm_provider_id),\n ];\n\n /**\n * @XXX: Bullhorn does not specify the time zone in their docs. I've found a forum thread in which someone from\n * staff asserts it's UTC, however in my field test I've found it to be GMT-0300 (USA east coast).\n * To make the code immune to such glitches we will add 24h to start/end boundaries and will filter out\n * any excess items in code\n */\n $filterStatements[] = sprintf(\n 'dateLastModified:[%s TO %s]',\n $from?->clone()->subHours(24)->format('YmdHis'),\n $to->clone()->addHours(24)->format('YmdHis'),\n );\n\n if ($activity->lead_id) {\n $filterStatements[] = sprintf('candidateUserID: %d', (int) $activity->lead->crm_provider_id);\n }\n\n if ($activity->contact_id) {\n $filterStatements[] = sprintf('clientContactUserID: %d', (int) $activity->contact->crm_provider_id);\n }\n\n // if there is no contact or lead associated to the activity exit\n if ($activity->contact_id === null && $activity->lead_id === null) {\n return [];\n }\n\n $params = [\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => implode(' AND ', $filterStatements),\n 'sort' => '-dateLastModified',\n ];\n\n $bhNotes = $this->client->get('search/Note', $params);\n\n $startStamp = $from?->getTimestamp() * 1000;\n $endStamp = $to->getTimestamp() * 1000;\n\n $filteredNotes = array_values(\n array_filter(\n $bhNotes['data'],\n static fn (array $bhNote): bool\n => $bhNote['dateLastModified'] >= $startStamp && $startStamp <= $endStamp,\n ),\n );\n\n return ! empty($filteredNotes) ? array_shift($filteredNotes) : [];\n }\n\n /**\n * Select how to create the date out of the Bullhorn payload.\n * Do not allow dates beyond 9999-12-31 (max mysql DATE)\n */\n private function filterOutOfBoundDates(string $rawDateCandidate): ?Carbon\n {\n if (strlen($rawDateCandidate) > 12) {\n // A unix timestamp represented with more than 12 digits i\n // s definitely including milliseconds\n $dateFormatted = Carbon::createFromTimestampMs($rawDateCandidate);\n } else {\n $dateFormatted = Carbon::createFromTimestamp($rawDateCandidate);\n }\n\n $minDate = Carbon::createFromFormat('Y-m-d', '2000-01-01');\n if ($dateFormatted->lt($minDate)) {\n return null;\n }\n\n $maxDate = Carbon::createFromFormat('Y-m-d', '9999-12-31');\n if ($dateFormatted->gt($maxDate)) {\n $this->logger->warning('[Bullhorn] An out of bound date is provided', [\n 'date' => $dateFormatted,\n 'rawDate' => $rawDateCandidate,\n ]);\n\n return $maxDate;\n }\n\n return $dateFormatted;\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n $note = $this->getRecord('Note', $crmProviderId, ['id', 'isDeleted']);\n\n return ! empty($note) && ($note['isDeleted'] ?? false) === false;\n } catch (HttpNotFoundException|HttpBadRequestException) {\n // Note not found in CRM - this is expected and permanent\n $this->logger->info('[Bullhorn] Note not found during verification', [\n 'note_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-3734033779188788614
|
-3409575825370887490
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
73
3
11
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Bullhorn;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\Provider\BullhornInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\ApplicationException;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\DomainException;
use Jiminny\Exceptions\HttpBadRequestException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\ServiceUnavailableException;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\UserRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
use Ramsey\Uuid\Uuid;
class BullhornService extends BaseService implements
BullhornInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const string ENTITY_LEAD = 'Candidate';
private const string ENTITY_OPPORTUNITY = 'JobOrder';
private const string ENTITY_ACCOUNT = 'ClientCorporation';
private const string ENTITY_CONTACT = 'ClientContact';
private const string ENTITY_ACTIVITY = 'Note';
private const array OPPORTUNITY_FIELDS = [
'id',
'owner',
'status',
'title',
'salary',
'salaryUnit',
'payRate',
'isOpen',
'employmentType',
'dateClosed',
'startDate',
'dateLastModified',
'dateAdded',
'clientCorporation',
'correlatedCustomText10', // currency
];
private const array TASK_FIELDS = [
'id',
'comments',
'dateAdded',
'dateLastModified',
'externalID',
'isDeleted',
'corporateUsers',
'clientContacts',
'commentingPerson',
'candidates',
'jobOrder',
'minutesSpent',
'action',
];
private const array LEAD_FIELDS = [
'id',
'name',
'owner',
'occupation',
'companyName',
'companyURL',
'mobile',
'phone',
'phone2',
'phone3',
'workPhone',
'status',
'address',
'dateAdded',
'dateLastModified',
];
private const array CONTACT_FIELDS = [
'id',
'name',
'occupation',
'mobile',
'phone',
'phone2',
'phone3',
'address',
'clientCorporation',
'dateAdded',
'owner',
];
private const array ACCOUNT_FIELDS = [
'id',
'name',
'phone',
'industryList',
'address',
'companyURL',
'dateAdded',
];
public function __construct(
BullhornClientInterface $client,
private readonly UserRepository $userRepository,
private readonly ProspectPhotoPathService $prospectPhotoPathService
) {
parent::__construct();
$this->client = $client;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);
}
public function getDisplayName(): string
{
return 'Bullhorn';
}
public function createTranscriptNotes(Activity $activity): void
{
// Not done until a customer requests it.
}
public function syncProfileFields(): void
{
$fieldTypes = [
'lead',
'account',
'contact',
'opportunity',
'task',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))
);
if (! empty($changedFields)) {
$fields = implode(',', $newFields);
Log::debug(
sprintf(
'%s fields changed from %s to: %s',
ucfirst($fieldType),
$this->profile->{$fieldType . '_fields'},
$fields,
),
);
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (\Exception $exception) {
\Log::error('No access to ' . $fieldType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
$this->profile->save();
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
//parent::OBJECT_ACCOUNT,
//parent::OBJECT_CONTACT,
//parent::OBJECT_OPPORTUNITY,
//parent::OBJECT_LEAD,
];
}
protected function getFields(string $crmObject): array
{
$fields = [];
foreach ($this->getObjectFields($crmObject) as $row) {
$fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];
}
return $fields;
}
private function getObjectFields(string $objectType): array
{
$entityType = $this->convertObjectTypeToResource($objectType);
return Cache::remember(
key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,
ttl: 60 * 60,
callback: function () use ($entityType) {
$entity = $this->client->get('meta/' . $entityType, [
'fields' => '*',
]);
return $entity['fields'];
},
);
}
public function getDefaultFields(string $activityType): array
{
$fields = [];
$defaultFields = FieldDefinitions::defaultFields();
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
return $fields;
}
public function getDefaultActivityField(string $activityType): Field
{
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'action',
'object_type' => $activityType,
])->first();
return $activityField;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
// We are not yet supporting follow-ups for this system.
return [];
}
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return $fieldValue;
}
public function syncField(Field $field): void
{
$resource = $this->convertObjectTypeToResource($field->object_type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => $field->crm_provider_id,
'meta' => 'full',
]);
$bhField = $entity['fields'][0];
$isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);
$description = null;
if (empty($bhField['description']) === false) {
$description = mb_strimwidth($bhField['description'], 0, 191);
}
$label = 'Unknown';
if (empty($bhField['label']) === false) {
$label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);
}
$field->length = $bhField['maxLength'] ?? null;
$field->is_mandatory = $isMandatory;
$field->description = $description;
$field->label = $label;
$field->type = $this->convertFieldType(
$bhField['dataType'] ?? null,
$bhField['dataSpecialization'] ?? null,
$bhField['inputType'] ?? null
);
$field->save();
if (empty($bhField['options']) === false) {
$values = [];
// Import all values.
foreach ($bhField['options'] as $i => $option) {
$values[] = [
'value' => $option['value'],
'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),
'sequence' => $i,
];
}
// Take the existing set of field values.
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
// For all current values, upsert the field.
$field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
$key = array_search($value['value'], $fieldsToPurge, false);
if ($key !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
}
}
public function importPicklistValues(Field $field): array
{
// Taken care of in syncField.
return [];
}
private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string
{
if ($type === null) {
return Field::TYPE_UNSUPPORTED;
}
$type = strtolower($type);
$specialization = strtolower($specialization);
$inputType = strtolower($inputType);
switch ($type) {
case 'boolean':
return Field::TYPE_BOOLEAN;
case 'integer':
switch ($specialization) {
case 'integer':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'bigdecimal':
switch ($specialization) {
case 'money':
return Field::TYPE_CURRENCY;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'double':
switch ($specialization) {
case 'float':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'timestamp':
switch ($specialization) {
case 'date':
return Field::TYPE_DATE;
case 'time':
return Field::TYPE_TIME;
case 'datetime':
return Field::TYPE_DATETIME;
default:
return Field::TYPE_DATE;
}
// no break
case 'string':
switch ($inputType) {
case 'textarea':
return Field::TYPE_TEXTAREA;
case 'select':
return Field::TYPE_PICKLIST;
default:
return Field::TYPE_TEXT;
}
// no break
default:
// This is not actually a supported field.
return Field::TYPE_UNSUPPORTED;
}
}
private function importContact($crmData): Contact
{
$account = $mobilePhone = $phone = $email = null;
if (empty($crmData['clientCorporation']) === false) {
$account = $this->team
->accounts()
->where('crm_provider_id', $crmData['clientCorporation']['id'])
->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
}
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => $crmData['name'],
'email' => $email,
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'title' => $crmData['occupation'],
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Contact::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importOpportunity($crmData): ?Opportunity
{
if ($crmData['clientCorporation']['id']) {
$account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
} else {
// If there is nothing to associate this with, don't import it.
return null;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$stage = $this->config->stages()
->where('crm_provider_id', $crmData['status'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);
}
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => mb_strimwidth($crmData['title'], 0, 128),
'value' => $crmData['salary'] ?? $crmData['payRate'],
'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),
'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),
'is_closed' => $crmData['isOpen'] !== true,
'is_won' => strtolower($crmData['status']) === 'placed',
'stage_id' => $stage->id,
'record_type_id' => null,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importAccount($crmData): Account
{
$countryCode = $domain = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$name = $crmData['name'] ?? 'Unknown';
if ($crmData['companyURL'] !== null) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$data = [
'team_id' => $this->team->id,
'user_id' => null,
'owner_id' => null,
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Account::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'country_code' => $countryCode,
'domain' => $domain,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importLead($crmData): ?Lead
{
// Get the current stage.
$stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);
}
// If we have no way of importing this, just return null :(
if ($stage === null) {
return null;
}
$countryCode = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$mobilePhone = $phone = $email = null;
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$company = 'Unknown';
if (empty($crmData['companyName']) === false) {
$companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];
$company = mb_strimwidth($companyName, 0, 191);
}
$domain = null;
if (empty($crmData['companyURL']) === false) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'company' => $company,
'domain' => $domain,
'name' => mb_strimwidth($crmData['name'], 0, 191),
'title' => mb_strimwidth($crmData['occupation'], 0, 128),
'email' => mb_strimwidth($email, 0, 80),
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Lead::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'stage_id' => $stage->id,
'country_code' => $countryCode,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
/**
* @throws ApplicationException
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhContacts = $this->client->get('search/ClientContact', $params);
foreach ($bhContacts['data'] as $bhContact) {
// Only sync if previously imported.
if ($this->hasContact($bhContact['id'])) {
$this->importContact($bhContact);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategies = $strategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
$total = 0;
$count = 0;
$offset = 0;
try {
$bhOpportunities = [];
foreach ($strategies as $syncStrategy) {
$opportunitiesData = $syncStrategy->fetchOpportunities($parameters);
$total = (int) ($opportunitiesData['total'] ?? 0);
$count = (int) ($opportunitiesData['count'] ?? 0);
$offset = (int) ($opportunitiesData['start'] ?? 0);
$bhOpportunities[] = $opportunitiesData['data'] ?? [];
}
$bhOpportunities = array_merge(...$bhOpportunities);
foreach ($bhOpportunities as $bhOpportunity) {
$this->importOpportunity($bhOpportunity);
$syncCount++;
}
} catch (\Exception $exception) {
$this->logger->info('Failed to sync opportunities', [
'params' => $parameters,
'exception' => $exception->getMessage(),
]);
}
// only log if there are one sync strategy
if (count($strategies) === 1 && $total > $count + $offset) {
$this->logger->info('[Bullhorn] Sync Opportunities - count warning', [
'team_id' => $this->team->getId(),
'total' => $total,
'count' => $count,
'offset' => $offset,
]);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhAccounts = $this->client->get('search/ClientCorporation', $params);
foreach ($bhAccounts['data'] as $bhAccount) {
// Only sync if previously imported.
if ($this->hasAccount($bhAccount['id'])) {
$this->importAccount($bhAccount);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhLeads = $this->client->get('search/Candidate', $params);
if ($bhLeads === null) {
return $syncCount;
}
foreach ($bhLeads['data'] as $bhLead) {
// Only sync if previously imported.
if ($this->hasLead($bhLead['id'])) {
$this->importLead($bhLead);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncContact(string $crmId): ?Contact
{
try {
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importContact($data['data']);
}
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategy = $strategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
try {
$data = $strategy->fetchOpportunities(['crm_id' => $crmId]);
} catch (HttpNotFoundException $exception) {
$this->logger->info('[Bullhorn] Opportunity not found', [
'crm_id' => $crmId,
'reason' => $exception->getMessage(),
]);
}
return $this->importOpportunity($data['data'] ?? []);
}
public function syncAccount(string $crmId): ?Account
{
try {
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importAccount($data['data']);
}
public function syncLead(string $crmId): ?Lead
{
try {
$data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importLead($data['data']);
}
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$missingStage = null;
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
foreach ($types as $type) {
$resource = $this->convertObjectTypeToResource($type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => 'status',
'meta' => 'full',
]);
$missingStage = null;
if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {
throw new \UnexpectedValueException('Invalid response from Bullhorn API');
}
// Upsert all stages for the team.
foreach ($entity['fields'][0]['options'] as $i => $option) {
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $option['value'],
'type' => $type,
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($option['value'], 0, 50),
'label' => mb_strimwidth($option['label'], 0, 191),
'sequence' => $i,
'is_selectable' => 1,
]);
if ($missingStageName && $missingStageName === $option['value']) {
$missingStage = $stage;
}
}
if ($missingStageName && $missingStage === null) {
// If they requested a stage that still doesn't exist, it must be inactive so lazy create it.
$missingStage = $this->config->stages()->create([
'team_id' => $this->team->id,
'crm_provider_id' => Uuid::uuid4(),
'name' => mb_strimwidth($missingStageName, 0, 50),
'label' => mb_strimwidth($missingStageName, 0, 191),
'type' => $type,
'sequence' => 0,
'is_selectable' => 0,
]);
}
}
return $missingStage;
}
public function syncOrganization(): void
{
// There appears to be nothing we can sync/map to.
}
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$data = \Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {
$result = [];
try {
$objects = $this->client->get('find', [
'query' => $name,
'meta' => 'basic',
'countPerEntity' => $count,
]);
} catch (\GuzzleHttp\Exception\ServerException $exception) {
throw new ServiceUnavailableException($exception->getMessage());
}
foreach ($objects['data'] as $object) {
try {
$prospectType = $this->convertResourceToObjectType($object['entityType']);
} catch (\UnexpectedValueException $exception) {
// We don't support this, so skip it.
continue;
}
$record = [
'crmId' => $object['entityId'],
'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),
'prospectType' => $prospectType,
'phoneNumbers' => [],
];
// Unfortunately we need to go and query each entity itself to get the data we need.
switch ($object['entityType']) {
case self::ENTITY_ACCOUNT:
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['industry'] = $entity['industryList'];
if (empty($entity['phone']) === false) {
$record['phoneNumbers'][] = [
'number' => $entity['phone'],
'nationalFormat' => phone_national(null, $entity['phone']),
'type' => 'phone',
];
}
break;
case self::ENTITY_CONTACT:
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
case self::ENTITY_LEAD:
$bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);
$entity = $bhData['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['companyName'];
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
default:
// We are not interested in this entity type so skip it.
continue 2;
}
$result[] = $record;
}
return $result;
});
return $data;
}
public function getClient(): BullhornClientInterface
{
return $this->client;
}
private function getFieldsAsString(array $fields)
{
return implode(', ', $fields);
}
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),
];
$onlyOpen = true;
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort'] = '-dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort'] = '+dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
$onlyOpen = false;
}
if ($onlyOpen) {
$where .= ' AND isOpen: true';
}
$params['query'] = $where;
$bhOpportunities = $this->client->get('search/JobOrder', $params);
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
foreach ($bhOpportunities['data'] as $bhOpportunity) {
$stage = $this->config
->stages()
->where('crm_provider_id', $bhOpportunity['status'])
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);
}
$record = [
'crmId' => $bhOpportunity['id'],
'name' => $bhOpportunity['title'],
'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),
'won' => strtolower($bhOpportunity['status']) === 'placed',
'closed' => $bhOpportunity['isOpen'] !== true,
'stage' => [
'id' => $stage->id_string,
'name' => $stage->name,
],
'recordType' => [],
];
if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = [];
// For now it has not been agreed on how to implement this e.g. appointments or tasks?
return [];
if ($objectType === 'account' && $opportunityId === null) {
// You cannot attach tasks to only accounts.
return [];
}
// Query should default to any open task.
$where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;
// If we are also going to check on a specific job order, set that up.
if ($opportunityId) {
$where .= ' OR JobOrder: ' . (int) $opportunityId;
}
$where .= ')';
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::TASK_FIELDS),
'query' => $where,
];
$bhTasks = $this->client->get('search/Task', $params);
foreach ($bhTasks['data'] as $bhTask) {
$data[] = [
'crmId' => $bhTask['id'],
'subject' => $bhTask['subject'],
'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),
'type' => null,
];
}
return $data;
}
/**
* @url [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] CrmException
* @throws DomainException
*/
private function buildNotePayload(Activity $activity): Activity
{
if ($activity->hasActivityType() === false) {
throw new DomainException('[Bullhorn] No activity type assigned');
}
$action = $this->getCrmType($activity->getActivityType());
if ($action === null) {
throw new DomainException('[Bullhorn] No mapped CRM type for "' . $activity->category->name . '"');
}
if ($activity->lead_id === null && $activity->contact_id === null) {
throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');
}
$payload = [
'comments' => $this->generateActivityDescription($activity),
'action' => $action->value,
'commentingPerson' => [
'id' => (int) $this->profile->crm_provider_id,
'type' => 'CorporateUser',
],
'externalID' => $activity->id_string,
'minutesSpent' => $activity->duration,
'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),
];
if ($activity->lead_id) {
$payload['personReference'] = [
'id' => (int) $activity->lead->crm_provider_id,
'type' => 'Candidate',
];
}
if ($activity->contact_id) {
$payload['personReference'] = [
'id' => (int) $activity->contact->crm_provider_id,
'type' => 'ClientContact',
];
}
if ($activity->opportunity_id) {
$payload['jobOrders'] = [
'replaceAll' => [
(int) $activity->opportunity->crm_provider_id,
],
];
}
$bhActivity = $this->client->put('entity/Note', $payload);
$activity->crm_provider_id = $bhActivity['changedEntityId'];
$activity->save();
return $activity;
}
private function generateActivityDescription(Activity $activity): string
{
$description = '';
switch ($activity->type) {
case Activity::TYPE_SOFTPHONE:
case Activity::TYPE_SOFTPHONE_INBOUND:
case Activity::TYPE_CONFERENCE:
if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
// Dialer calls have no native field for the subject.
if ($activity->title) {
$description .= sprintf(
'<p><span style="font-size: 16px; line-height: 19.2px;">%s</span></p>',
$activity->title,
);
}
// Conference meetings log duration into a distinct field, so log this in the main text.
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Call Duration: %s</span></p>',
$activity->duration_for_humans,
);
// Tell them which number was dialed.
if ($activity->to) {
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Dialed: %s</span></p>',
$activity->to->phone_number,
);
}
$description .= '<p></p>';
}
if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
...
|
45395
|
NULL
|
NULL
|
NULL
|
|
45396
|
1625
|
39
|
2026-05-14T14:34:18.841068+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769258841_m1.jpg...
|
PhpStorm
|
faVsco.js – BullhornService.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit k vProjectvAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phplhlHandleHubspotRateLimitTestv100% СThu 14 May 17:34:18Q© UserAutomatedReportsController.php:- custom.log© BullhornLoginHandler.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php© BullhornLoginHandlerInterfa© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© Salesforce/Service.phpT LogActivityTrait.php© BullhornService.php© BullhornSessionDecorator.plPipedrive/Service.phpClose/Service.phpCopper/Service.phpBullhornService.php XPlainTextDecorateActivity.php© BullhornSessionManager.ph|© ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php= .env.staging18• BullhornSessionManagerinte© FieldDefinitions.phpE.envDetachActivityObject.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpv @ Close> OpportunitySyncStrategy© HubspotPaginationService.phpHandleHubspotRateLimit.phpclass BullhornServiceextends BaseService implements47A8 A73 ×3 X11 ^> O Processor> D ProspectSearchStrategy1337private function buildNotePayload(Activity $activity): Activity> O Translator1338{© Client.php1339© CloseException.php1340if (Sactivity->hasActivityType() === false) {throw new DomainException( message:'[Bullhorn] No activity type assigned');© FieldDefinitions.php1341© FieldValueConverter.php1342© Service.php1343© StandardFieldMetadata.php1344v Copper1345$action = $this->getCrmType($activity->getActivityType());Cascade &8 VlCommand 881if (Saction === null) {throw new DomainException( message:'[Bullhorn] No mapped CRM type for "r• Sactivity->category-># 222> J Apі|1346}> D Exception1347> D OpportunitySyncStrategy1348> D ProspectSearchStrategy1349if (Sactivity->lead_id === null && $activity->contact_id === null) {throw new DomainException( message:'[Bullhorn] Cannot save note without candidate or DM');> C Traits1350}© FieldDefinitions.php1351© FieldValueConverter.php1352© Service.php1353> C CrmObjects|1354D DecorateActivity1355© BaseDecorateActivity.php1356© PlainTextDecorateActivity.pl1357$payload = ['comments' => $this->generateActivityDescription($activity),'action' = Saction->value,'commentingPerson' => ['id' => (int) $this->profile->crm_provider_id,'type' => 'CorporateUser',> C Dummy1358v D Helpers1359T ActivityPlaybookTrait.php1360© Arraylterator.php13611,'externalID' => $activity->id_string,='minutesSpent' => $activity->duration,'dateAdded' => Sactivity->hasActualEndTime() ? Sactivity->getActualEndTime()?-›value0f() : now()=@ CannantionCtotaTrait nhn1362Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W« console [QAI PROD) X4 console [PROD]A console (EU]DGo jiminny084143 ×4 л215|•m_layout_id =2162,1661,66799,66217218219.id = 33;220221223=224id THEN •(own225=226= 227228229-230hubspot':--231232- 233 V234= 11512582;W Windsurf Teams1343:16 (7 chars)UTF-8Ca 4 spaces...
|
NULL
|
-5797654124614868058
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit k vProjectvAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phplhlHandleHubspotRateLimitTestv100% СThu 14 May 17:34:18Q© UserAutomatedReportsController.php:- custom.log© BullhornLoginHandler.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php© BullhornLoginHandlerInterfa© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© Salesforce/Service.phpT LogActivityTrait.php© BullhornService.php© BullhornSessionDecorator.plPipedrive/Service.phpClose/Service.phpCopper/Service.phpBullhornService.php XPlainTextDecorateActivity.php© BullhornSessionManager.ph|© ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php= .env.staging18• BullhornSessionManagerinte© FieldDefinitions.phpE.envDetachActivityObject.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpv @ Close> OpportunitySyncStrategy© HubspotPaginationService.phpHandleHubspotRateLimit.phpclass BullhornServiceextends BaseService implements47A8 A73 ×3 X11 ^> O Processor> D ProspectSearchStrategy1337private function buildNotePayload(Activity $activity): Activity> O Translator1338{© Client.php1339© CloseException.php1340if (Sactivity->hasActivityType() === false) {throw new DomainException( message:'[Bullhorn] No activity type assigned');© FieldDefinitions.php1341© FieldValueConverter.php1342© Service.php1343© StandardFieldMetadata.php1344v Copper1345$action = $this->getCrmType($activity->getActivityType());Cascade &8 VlCommand 881if (Saction === null) {throw new DomainException( message:'[Bullhorn] No mapped CRM type for "r• Sactivity->category-># 222> J Apі|1346}> D Exception1347> D OpportunitySyncStrategy1348> D ProspectSearchStrategy1349if (Sactivity->lead_id === null && $activity->contact_id === null) {throw new DomainException( message:'[Bullhorn] Cannot save note without candidate or DM');> C Traits1350}© FieldDefinitions.php1351© FieldValueConverter.php1352© Service.php1353> C CrmObjects|1354D DecorateActivity1355© BaseDecorateActivity.php1356© PlainTextDecorateActivity.pl1357$payload = ['comments' => $this->generateActivityDescription($activity),'action' = Saction->value,'commentingPerson' => ['id' => (int) $this->profile->crm_provider_id,'type' => 'CorporateUser',> C Dummy1358v D Helpers1359T ActivityPlaybookTrait.php1360© Arraylterator.php13611,'externalID' => $activity->id_string,='minutesSpent' => $activity->duration,'dateAdded' => Sactivity->hasActualEndTime() ? Sactivity->getActualEndTime()?-›value0f() : now()=@ CannantionCtotaTrait nhn1362Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W« console [QAI PROD) X4 console [PROD]A console (EU]DGo jiminny084143 ×4 л215|•m_layout_id =2162,1661,66799,66217218219.id = 33;220221223=224id THEN •(own225=226= 227228229-230hubspot':--231232- 233 V234= 11512582;W Windsurf Teams1343:16 (7 chars)UTF-8Ca 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45395
|
1626
|
23
|
2026-05-14T14:34:16.915847+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769256915_m2.jpg...
|
PhpStorm
|
faVsco.js – BullhornService.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pm~ (Q SearchDate ModifiedYesterdav at 13.36Yesterday at 13:35Yesterday at 13.34Yesterday at 13:34Yesterday at 13:33resterday at 15.5sYesterdav at 13:37Yesterday at 13:32Yesterday at 13.31Yesterday at 13:30Yesterday at 13:30resterday at 15.4gYesterdav at 13:29Yesterday at 13:28Yesterday at 13:28Yesterday at 13:27Yesterday at 13:27resterday at 13.-40Yesterdav at 13:25Yesterday at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13:23Yesterday at 13.21Yesterdav at 13:21Yesterday at 13:20Yesterday at 13:20Yesterday at 13:19Yesterday at 13:19Yesterday at 13.18Vecterdav at 12:17Yesterday at 13:16Yesterdav at 13:16Yesterday at 13:15Yesterday at 13:14Yecterdav at 12:1/Yesterday at 13:13Yesterday at 13.13Yecterdav at 12:12Yesterday at 13:12Yesterday at 13:11Yesterday at 13:10Yesterday at 13:10Yesterday at 13.09Yecterdav at 12:091Yesterday at 13:08Yesterdav at 13:07MPEG-4 movie13 KBMPEG-4 movie16 KB1/ Kb29 KBMPEG-4 movieMPEG-4 movie6 KB12 KBMPE0"4 movie9 K:7 KBMPEG-4 movie8 KB37 KBMP2G-4 movie10 KBMPEG-4 movie7 KBMPEG"4 movie9K:8KBMPEG-4 movie72 KB14 K8|13 KRIMPEG-4 movieMPEG-4 movie9 KB18 KBMPEG-4 movie12 KEMPEG-4 movie10 KBMPEG-4 movie16 KB6 KB1MPEG-4 movie6 KBMPEG-4 movie12 KB23 KBMPEG-4 movie8 KEMPEG-4 movie6 KBMPEG-4 movie6 KBMPEG-4 movie11 K:MPEG-4 movie11 KBMPEG-4 movie34 KBMPEG-4 movie10 KPMPEG-4 movie7 KBMPEG-4 movie5 KBMPEG-4 movie11 KBIMPEG-4 movie26 KBMPEG-4 movie111 KB102 KBRR KRMPEG-4 movieMDEG-A movie59 KB98 KBMPEG-4 movie07 K:MPEG-A movie66 KB MPEG-4 movie44 KB93 KB79 KpMPEG-4 movieMPEG-4 movie58 KBMPEG-4 movie27 KP7 KBMPEG-4 movie12 KB32 K8MPEG-4 movieAl Notes: OffLeave• 0FavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВ148 KB122 KB111 KB94 KBZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.48 GB availabld• Inu 14 Mаy 1/.34.10Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
-484756904054444687
|
NULL
|
click
|
ocr
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pm~ (Q SearchDate ModifiedYesterdav at 13.36Yesterday at 13:35Yesterday at 13.34Yesterday at 13:34Yesterday at 13:33resterday at 15.5sYesterdav at 13:37Yesterday at 13:32Yesterday at 13.31Yesterday at 13:30Yesterday at 13:30resterday at 15.4gYesterdav at 13:29Yesterday at 13:28Yesterday at 13:28Yesterday at 13:27Yesterday at 13:27resterday at 13.-40Yesterdav at 13:25Yesterday at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13:23Yesterday at 13.21Yesterdav at 13:21Yesterday at 13:20Yesterday at 13:20Yesterday at 13:19Yesterday at 13:19Yesterday at 13.18Vecterdav at 12:17Yesterday at 13:16Yesterdav at 13:16Yesterday at 13:15Yesterday at 13:14Yecterdav at 12:1/Yesterday at 13:13Yesterday at 13.13Yecterdav at 12:12Yesterday at 13:12Yesterday at 13:11Yesterday at 13:10Yesterday at 13:10Yesterday at 13.09Yecterdav at 12:091Yesterday at 13:08Yesterdav at 13:07MPEG-4 movie13 KBMPEG-4 movie16 KB1/ Kb29 KBMPEG-4 movieMPEG-4 movie6 KB12 KBMPE0"4 movie9 K:7 KBMPEG-4 movie8 KB37 KBMP2G-4 movie10 KBMPEG-4 movie7 KBMPEG"4 movie9K:8KBMPEG-4 movie72 KB14 K8|13 KRIMPEG-4 movieMPEG-4 movie9 KB18 KBMPEG-4 movie12 KEMPEG-4 movie10 KBMPEG-4 movie16 KB6 KB1MPEG-4 movie6 KBMPEG-4 movie12 KB23 KBMPEG-4 movie8 KEMPEG-4 movie6 KBMPEG-4 movie6 KBMPEG-4 movie11 K:MPEG-4 movie11 KBMPEG-4 movie34 KBMPEG-4 movie10 KPMPEG-4 movie7 KBMPEG-4 movie5 KBMPEG-4 movie11 KBIMPEG-4 movie26 KBMPEG-4 movie111 KB102 KBRR KRMPEG-4 movieMDEG-A movie59 KB98 KBMPEG-4 movie07 K:MPEG-A movie66 KB MPEG-4 movie44 KB93 KB79 KpMPEG-4 movieMPEG-4 movie58 KBMPEG-4 movie27 KP7 KBMPEG-4 movie12 KB32 K8MPEG-4 movieAl Notes: OffLeave• 0FavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВ148 KB122 KB111 KB94 KBZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.48 GB availabld• Inu 14 Mаy 1/.34.10Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45394
|
1625
|
38
|
2026-05-14T14:34:16.940066+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769256940_m1.jpg...
|
PhpStorm
|
faVsco.js – BullhornService.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit k vProject vAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpabl100% СHandleHubspotRateLimitTestvThu 14 May 17:34:16Q© UserAutomatedReportsController.php:- custom.log© BullhornLoginHandler.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php© BullhornLoginHandlerInterfa© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© Salesforce/Service.phpT LogActivityTrait.php© BullhornService.php© BullhornSessionDecorator.plPipedrive/Service.phpClose/Service.phpCopper/Service.phpBullhornService.php XPlainTextDecorateActivity.php© BullhornSessionManager.ph|© ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php= .env.staging18• BullhornSessionManagerinte© FieldDefinitions.phpE.envDetachActivityObject.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpv @ Close> OpportunitySyncStrategy© HubspotPaginationService.php© HandleHubspotRateLimit.phpclass BullhornServiceextends BaseService implements47A8 A73 ×3 X11 ^> O Processor> D ProspectSearchStrategy1337private function buildNotePayload(Activity $activity): Activity> O Translator1338{© Client.php1339© CloseException.php1340if (Sactivity->hasActivityType() === false) {throw new DomainException( message:'[Bullhorn] No activity type assigned');© FieldDefinitions.php1341© FieldValueConverter.php1342© Service.php1343© StandardFieldMetadata.php1344$action = $this->getCrmType(Sactivity->getActivityTypeO):if ($action === null) {v Copper1345throw new DomainException( message:'[Bullhorn] No mapped CRM type for "' . Sactivity->category-># 222> J Apі|1346}> D Exception1347> D OpportunitySyncStrategy1348> D ProspectSearchStrategy1349if (Sactivity->lead_id === null && $activity->contact_id === null) {throw new DomainException( message:'[Bullhorn] Cannot save note without candidate or DM');> C Traits1350}© FieldDefinitions.php1351© FieldValueConverter.php1352© Service.php1353> @ CrmObjects1354D DecorateActivity1355© BaseDecorateActivity.php1356© PlainTextDecorateActivity.pl1357$payload = ['comments' => $this->generateActivityDescription(Sactivity),'action' => Saction->value,'commentingPerson' => ['id' => (int) $this->profile->crm_provider_id,'type' => 'CorporateUser',> C Dummy1358v D Helpers1359T ActivityPlaybookTrait.php1360© Arraylterator.php13611,'externalID' => $activity->id_string,='minutesSpent' => $activity->duration,'dateAdded' > Sactivity->hasActua|LEndTime() ? $actіvity-›getActualEndT¡me()?->valueOf() : now(J=@ CannantionCtotaTrait nhn1362Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W« console [QAI PROD) X4 console [PROD]A console (EU]DGo jiminny084143 ×4 л215|•m_layout_id =2162,1661,66799,66217218219.id = 33;220221223=224id THEN(own= 225=226= 227228229—230hubspot' :-231-232233 V= 11512582;234W Windsurf Teams1361:47UTF-8Ca 4 spaces...
|
NULL
|
6732732307403989637
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit k vProject vAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpabl100% СHandleHubspotRateLimitTestvThu 14 May 17:34:16Q© UserAutomatedReportsController.php:- custom.log© BullhornLoginHandler.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php© BullhornLoginHandlerInterfa© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© Salesforce/Service.phpT LogActivityTrait.php© BullhornService.php© BullhornSessionDecorator.plPipedrive/Service.phpClose/Service.phpCopper/Service.phpBullhornService.php XPlainTextDecorateActivity.php© BullhornSessionManager.ph|© ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php= .env.staging18• BullhornSessionManagerinte© FieldDefinitions.phpE.envDetachActivityObject.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpv @ Close> OpportunitySyncStrategy© HubspotPaginationService.php© HandleHubspotRateLimit.phpclass BullhornServiceextends BaseService implements47A8 A73 ×3 X11 ^> O Processor> D ProspectSearchStrategy1337private function buildNotePayload(Activity $activity): Activity> O Translator1338{© Client.php1339© CloseException.php1340if (Sactivity->hasActivityType() === false) {throw new DomainException( message:'[Bullhorn] No activity type assigned');© FieldDefinitions.php1341© FieldValueConverter.php1342© Service.php1343© StandardFieldMetadata.php1344$action = $this->getCrmType(Sactivity->getActivityTypeO):if ($action === null) {v Copper1345throw new DomainException( message:'[Bullhorn] No mapped CRM type for "' . Sactivity->category-># 222> J Apі|1346}> D Exception1347> D OpportunitySyncStrategy1348> D ProspectSearchStrategy1349if (Sactivity->lead_id === null && $activity->contact_id === null) {throw new DomainException( message:'[Bullhorn] Cannot save note without candidate or DM');> C Traits1350}© FieldDefinitions.php1351© FieldValueConverter.php1352© Service.php1353> @ CrmObjects1354D DecorateActivity1355© BaseDecorateActivity.php1356© PlainTextDecorateActivity.pl1357$payload = ['comments' => $this->generateActivityDescription(Sactivity),'action' => Saction->value,'commentingPerson' => ['id' => (int) $this->profile->crm_provider_id,'type' => 'CorporateUser',> C Dummy1358v D Helpers1359T ActivityPlaybookTrait.php1360© Arraylterator.php13611,'externalID' => $activity->id_string,='minutesSpent' => $activity->duration,'dateAdded' > Sactivity->hasActua|LEndTime() ? $actіvity-›getActualEndT¡me()?->valueOf() : now(J=@ CannantionCtotaTrait nhn1362Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W« console [QAI PROD) X4 console [PROD]A console (EU]DGo jiminny084143 ×4 л215|•m_layout_id =2162,1661,66799,66217218219.id = 33;220221223=224id THEN(own= 225=226= 227228229—230hubspot' :-231-232233 V= 11512582;234W Windsurf Teams1361:47UTF-8Ca 4 spaces...
|
45392
|
NULL
|
NULL
|
NULL
|
|
45393
|
1626
|
22
|
2026-05-14T14:34:11.466116+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769251466_m2.jpg...
|
PhpStorm
|
faVsco.js – BullhornService.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.66456115,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.67586434,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.6871675,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.7150931,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.72639626,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.73769945,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-4027196623176036612
|
-8132283174711358517
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preuiew in sact[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pmv Q SearchDate ModifiedYesterdav at 13.36Yesterday at 13:35Yesterday at 13.34Yesterdav at 13:34Yesterday at 13:33resterday at 15.5sYesterdav at 13:37Yesterday at 13:32Yesterday at 13.31Yesterdav at 13:30Yesterday at 13:30resterday at 15.4gYesterdav at 13:29Yesterday at 13:28Yesterday at 13:28Yesterday at 13:27Yesterdav at 13:27resterday at 13-40Yesterdav at 13:25Yesterday at 13:25Yesterday at 13:24Yesterday at 13:24Voctorday at 12:22Yesterday at 13.21Yesterdav at 13:21Yesterdav at 13:20Yesterday at 13:20Yesterday at 13:19Yesterday at 13:19Yesterday at 13.18Vecterdav at 12:17Yesterday at 13:16Yesterdav at 13:16Yesterday at 13:15Yesterday at 13:14Yecterdav at 12:1/Yesterdav at 13:13Yesterday at 13.13Yecterdav at 12:12Yesterday at 13:12Yesterday at 13:11Yoctorday at 12:10Yesterdav at 13:10Yesterday at 13.09Yecterdav at 12:091Yesterdav at 13:08Yesterdav at 13:07MPEG-4 movie13 KB16 KB1/ Kb29 KE6 KB12 KB9 K:MPEG-4 movieMPEG-4 movieMPEG-4 movieMPE0"4 movie7 KBMDSG-A movid8 KE37 KBMP2G-4 movie10 KB7 KBMPEG-4 movieMPEG"4 movie9K:8 KBMoECA movio72 KB14 K8|MPEG-4 movie13 KRI9 KB18 KBMPEG-1 movidMPEG-4 movie12 KEMPEG-4 movie10 KB16 KBMPEG-4 movie6 KB1MPEG-4 movieMDSG.A movic12 KB23 KBMPEG-4 movie8 KE6 KBMPEG-4 movieMPEG-4 movie6 KBMPEG-4 movie11 K:MPEG-4 movie11 KPMDEC A movid34 KBMPEG-4 movie10 KPMDEG-A movie7 KBMPEG-4 movie5 KBMPEG-4 movie11 KBI26 KB111 KB102 KBMPEG-4 movieMDEC.A movialMPEG-4 movieRR KR59 KB98 KBMDEG-A movieMPEG-4 movie07 K:MPEG-A movie66 KB MPEG-4 movie44 KB93 KB79 KpMPEG-4 movieMDEG.A movio58 KBMPEG-4 movie27 KP7 KBMPEG-4 movie12 KB32 K8MPEG-4 movieAl Notes: OffLeave• • CFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc tolde0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esv1 config.vmlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•AlfredwPmazanoko.imnaoc.YWIfана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentK:PDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.48 GB availabld• Inu 14 Mау 1/•34-17Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 4+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
45391
|
NULL
|
NULL
|
NULL
|
|
45392
|
1625
|
37
|
2026-05-14T14:34:11.453403+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769251453_m1.jpg...
|
PhpStorm
|
faVsco.js – BullhornService.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.6645833,"top":0.027777778,"width":0.15902779,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.82361114,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.8472222,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.87083334,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.9291667,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9527778,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9763889,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-4027196623176036612
|
-8132283174711358517
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit k vlhlHandleHubspotRateLimitTest100% С8• Thu 14 May 17:34:11QProjectv© UserAutomatedReportsController.php:=custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.php© BullhornLoginHandler.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php= laravel.log© BullhornLoginHandlerInterfa© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© Salesforce/Service.phpT LogActivityTrait.phpSF [jiminny@localhost]© BullhornService.php© BullhornSessionDecorator.plPipedrive/Service.phpClose/Service.phpCopper/Service.phpBullhornService.php X© PlainTextDecorateActivity.phpA HS_local [jiminny@localho:W© BullhornSessionManager.ph|© ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php= .env.staging4 console [QAI PROD] X18• BullhornSessionManagerinte© FieldDefinitions.phpE.envDetachActivityObject.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.php© Client.php4 console [PROD]v @ Close> OpportunitySyncStrategy47> O Processor1337> D ProspectSearchStrategy1341© HubspotPaginationService.php© HandleHubspotRateLimit.phpclass BullhornService extends BaseService implementsprivate function buildNotePayload(Activity $activity): Activity}A console (EU]A8 A73 ×3 X11 ^> O Translator1342© Client.php1343© CloseException.php1344$action = $this->getCrmType($activity->getActivityType());if ($action === null) {© FieldDefinitions.php1345© FieldValueConverter.php1346id = 33;© Service.php1347© StandardFieldMetadata.php1348v Copper1349if ($activity->lead_id === null && $activity->contact_id === null) {throw new DomainException( message:'[Bullhorn] Cannot save note without candidate or DM');> C Apі|1350> D Exception1351> D OpportunitySyncStrategy1352> D ProspectSearchStrategy1353> C Traits1354© FieldDefinitions.php1355© FieldValueConverter.php1356© Service.php1357$payload = ['comments' => $this->generateActivityDescription(Sactivity),'action' => $action->value,'commentingPerson' => ['id' = (int) $this->profile->crm_provider_id,'type' => 'CorporateUser',> @ CrmObjects1358D DecorateActivity1359© BaseDecorateActivity.php1360DGo jiminny084143 ×4 л215•m_layout_id =2162,1661,66799,66217218throw new DomainException( message: '[Bullhorn] No mapped CRM type for "* . Sactivity->category->na 219220221=222223=224225=226= 227228229—230_231232233V234id THEN '(ownhubspat":© PlainTextDecorateActivity.pl13611,'externalID' => $activity->id_string,'minutesSpent' => $activity->duration,'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->value0f() : now()->= 11512582;C Dummy1362v D Helpers1363T ActivityPlaybookTrait.php1364© Arraylterator.php1365if (Sactivity->lead_id) {$payload[ 'personReference'] = [==# CannantionCtstaTrait nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams1343:32UTF-8Ca 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45391
|
1626
|
21
|
2026-05-14T14:34:03.763346+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769243763_m2.jpg...
|
PhpStorm
|
faVsco.js – BullhornService.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Jiminny... ~ActivityFilesLater@ jiminny-x-integrat Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pmv Q SearchDate ModifiedYesterdav at 13.3Yesterday at 13:37Yesterday at 13.30Yesterdav at 13:35resterday at 15.34Yesterdav at 13:34Yesterday at 13:33Yesterday at 13.32Yesterdav at 13:39resterday at 15.3Yesterdav at 13:30Yesterday at 13:30Yesterday at 13:29Yesterday at 13:29Yesterday at 13:28resterday at 13-21Yesterdav at 13:27Yesterday at 13:26Yesterday at 13:26Yesterday at 13:25Yesterday at 13.24Yesterdav at 13:22Yesterdav at 13:22resterady al 15.clYesterday at 13:20Yesterday at 13.19Yecterdav at 12:10Yesterdav at 13:18Yesterday at 13.10Yesterdav at 13:17Yesterday at 13:17Yesterday at 13:16Yacterdav at 12:15Yesterday at 13.14Yecterdav at 12:14Yesterday at 13:13Yesterday at 13:12Yoctorday at 12:19Yesterday at 13.11Yecterdav at 12:10Yesterdav at 13:10Yesterdav at 13:0962 K:MPEG-4 movie71 KB23 KBMPEG-4 movieMPEG-4 movieMPEG-4 movie13 KE16 KB17 KB29 K:MPE0"4 movie6 KB12 KBMDSG-A movieMP2G-4 movie7 KBI8 KB37 KB10 KВIMPEG-A movieMPEG"4 movieMPEG-4 movie7 KBMPEG-4 movie8 KB9 KB1MPEG-4 movie8 KR72 KB14 KBMPEG-1 movieMPEG-4 movie13 KEMPEG-4 movie9 KB MPEG-4 movie18 KB12 KB|MPEG-4 movie10 KB16 KB6KBMDEG.A movicMPEG-4 movie6KE12 KBMPEG-4 movieMPEG-4 movie23 KBMPEG-4 movie8 K:MPEG-4 movie6 KBMDECA movid11 KBMPEG-4 movie11 KPMDEG-A movie20 KB34 KB10 K:7 KB5 KB11 KBMPEG-4 movieMDEC.A moviaMPEG-4 movieD6KRMDEG-A movia111 KBMPEG-4 movie102 KEMPEG-4 movie88 KBMPEG-A movie59 KB MPEG-4 movie98 KB97 KBMPEG-4 movieMDEG.A movioGAKP44 KB93 KBMPEG-4 movie78 KPMDEG-A movid50 KBMPEG-4 movie58 KB17 KBMPEG-4 movieAl Notes: OffLeave• • CFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc toldeLocations0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esv1 config.vmlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•AlfredwPmazanoko.imnaoc.YWIfана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentK:PDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.48 GB availabld• Inu 14 Mау 1/.34:02Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 4+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
7335105272412294935
|
NULL
|
click
|
ocr
|
NULL
|
Jiminny... ~ActivityFilesLater@ jiminny-x-integrat Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pmv Q SearchDate ModifiedYesterdav at 13.3Yesterday at 13:37Yesterday at 13.30Yesterdav at 13:35resterday at 15.34Yesterdav at 13:34Yesterday at 13:33Yesterday at 13.32Yesterdav at 13:39resterday at 15.3Yesterdav at 13:30Yesterday at 13:30Yesterday at 13:29Yesterday at 13:29Yesterday at 13:28resterday at 13-21Yesterdav at 13:27Yesterday at 13:26Yesterday at 13:26Yesterday at 13:25Yesterday at 13.24Yesterdav at 13:22Yesterdav at 13:22resterady al 15.clYesterday at 13:20Yesterday at 13.19Yecterdav at 12:10Yesterdav at 13:18Yesterday at 13.10Yesterdav at 13:17Yesterday at 13:17Yesterday at 13:16Yacterdav at 12:15Yesterday at 13.14Yecterdav at 12:14Yesterday at 13:13Yesterday at 13:12Yoctorday at 12:19Yesterday at 13.11Yecterdav at 12:10Yesterdav at 13:10Yesterdav at 13:0962 K:MPEG-4 movie71 KB23 KBMPEG-4 movieMPEG-4 movieMPEG-4 movie13 KE16 KB17 KB29 K:MPE0"4 movie6 KB12 KBMDSG-A movieMP2G-4 movie7 KBI8 KB37 KB10 KВIMPEG-A movieMPEG"4 movieMPEG-4 movie7 KBMPEG-4 movie8 KB9 KB1MPEG-4 movie8 KR72 KB14 KBMPEG-1 movieMPEG-4 movie13 KEMPEG-4 movie9 KB MPEG-4 movie18 KB12 KB|MPEG-4 movie10 KB16 KB6KBMDEG.A movicMPEG-4 movie6KE12 KBMPEG-4 movieMPEG-4 movie23 KBMPEG-4 movie8 K:MPEG-4 movie6 KBMDECA movid11 KBMPEG-4 movie11 KPMDEG-A movie20 KB34 KB10 K:7 KB5 KB11 KBMPEG-4 movieMDEC.A moviaMPEG-4 movieD6KRMDEG-A movia111 KBMPEG-4 movie102 KEMPEG-4 movie88 KBMPEG-A movie59 KB MPEG-4 movie98 KB97 KBMPEG-4 movieMDEG.A movioGAKP44 KB93 KBMPEG-4 movie78 KPMDEG-A movid50 KBMPEG-4 movie58 KB17 KBMPEG-4 movieAl Notes: OffLeave• • CFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc toldeLocations0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esv1 config.vmlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•AlfredwPmazanoko.imnaoc.YWIfана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentK:PDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.48 GB availabld• Inu 14 Mау 1/.34:02Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 4+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45390
|
1625
|
36
|
2026-05-14T14:34:02.329303+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769242329_m1.jpg...
|
PhpStorm
|
faVsco.js – BullhornService.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelplhl100% C•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTest8• Thu 14 May 17:34:02* :QProject v© UserAutomatedReportsController.php:=custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.php© BullhornLoginHandler.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php=laravel.log© BullhornLoginHandlerInterfa© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© Salesforce/Service.phpT LogActivityTrait.phpSF [jiminny@localhost]© BullhornService.php© BullhornSessionDecorator.plPipedrive/Service.phpClose/Service.phpCopper/Service.phpBullhornService.php X© PlainTextDecorateActivity.phpA HS_local [jiminny@localho:W© BullhornSessionManager.ph|© ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php= .env.staging4 console [QAI PROD] X18• BullhornSessionManagerinte© FieldDefinitions.phpE.envDetachActivityObject.phpRematchActivityOnCrmObjectDetach.php© MatchActivityCrmData.php© Client.php4 console [PROD]v @ Close.> OpportunitySyncStrategy© HubspotPaginationService.php© HandleHubspotRateLimit.phpclassBullhornService extends BaseService implementsA console (EU]> O Processor471550A8 A73 ×3 X11 ^> D ProspectSearchStrategy1 usage> O Translator1337private function buildNotePayload(Activity $activity): Activity© Client.php1338© CloseException.php1339© FieldDefinitions.php1340if (Sactivity->hasActivityType() === false) {throw new DomainException( message:'[Bullhorn] No activity type assigned');© FieldValueConverter.phpid = 33;1341© Service.php1342© StandardFieldMetadata.php1343v Copper1344$action = $this->getCrmType($activity->getActivityType());if ($action === null) {> C Apі|1345> D Exception1346> D OpportunitySyncStrategy1347> D ProspectSearchStrategy1348> @ Traits1349if ($activity->lead_id === null && $activity->contact_id === null) {throw new DomainException( message: '[Bullhorn] Cannot save note without candidate or DM'):© FieldDefinitions.php1350}-© FieldValueConverter.php1351© Service.php1352> @ CrmObjects1353D DecorateActivity1354© BaseDecorateActivity.php13551356DGo jiminny084143 ×4 л215|•m_layout_id =2162,1661,66799,66217218219220221=222223throw new DomainException(message:' (Bullhorn] No mapped CRM type for "'* . Sactivity->category->mg224225=226=227228229—230_231232-233 V234id THEN •(ownhubspot':-© PlainTextDecorateActivity.plC Dummy1357$payload = ['comments' => $this-›generateActivityDescription(Sactivity),'action' = $action->value,'commentingPerson' => ['id'=> (int) $this->profile->crm_provider_id,'type' => 'CorporateUser',= 11512582;v D Helpers1358T ActivityPlaybookTrait.php1359© Arraylterator.php1360# CannantionCtstaTrait nhn1,'externalID' = $activity->id_string,'minutesSpent' = $activity->duration,AHnTEARRATWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)AATRATTATCHATMAT T WIATIARCNnAwE)W Windsurf Teams1343:30UTF-8Co 4 spaces...
|
NULL
|
-690484408177067423
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelplhl100% C•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTest8• Thu 14 May 17:34:02* :QProject v© UserAutomatedReportsController.php:=custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.php© BullhornLoginHandler.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php=laravel.log© BullhornLoginHandlerInterfa© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© Salesforce/Service.phpT LogActivityTrait.phpSF [jiminny@localhost]© BullhornService.php© BullhornSessionDecorator.plPipedrive/Service.phpClose/Service.phpCopper/Service.phpBullhornService.php X© PlainTextDecorateActivity.phpA HS_local [jiminny@localho:W© BullhornSessionManager.ph|© ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php= .env.staging4 console [QAI PROD] X18• BullhornSessionManagerinte© FieldDefinitions.phpE.envDetachActivityObject.phpRematchActivityOnCrmObjectDetach.php© MatchActivityCrmData.php© Client.php4 console [PROD]v @ Close.> OpportunitySyncStrategy© HubspotPaginationService.php© HandleHubspotRateLimit.phpclassBullhornService extends BaseService implementsA console (EU]> O Processor471550A8 A73 ×3 X11 ^> D ProspectSearchStrategy1 usage> O Translator1337private function buildNotePayload(Activity $activity): Activity© Client.php1338© CloseException.php1339© FieldDefinitions.php1340if (Sactivity->hasActivityType() === false) {throw new DomainException( message:'[Bullhorn] No activity type assigned');© FieldValueConverter.phpid = 33;1341© Service.php1342© StandardFieldMetadata.php1343v Copper1344$action = $this->getCrmType($activity->getActivityType());if ($action === null) {> C Apі|1345> D Exception1346> D OpportunitySyncStrategy1347> D ProspectSearchStrategy1348> @ Traits1349if ($activity->lead_id === null && $activity->contact_id === null) {throw new DomainException( message: '[Bullhorn] Cannot save note without candidate or DM'):© FieldDefinitions.php1350}-© FieldValueConverter.php1351© Service.php1352> @ CrmObjects1353D DecorateActivity1354© BaseDecorateActivity.php13551356DGo jiminny084143 ×4 л215|•m_layout_id =2162,1661,66799,66217218219220221=222223throw new DomainException(message:' (Bullhorn] No mapped CRM type for "'* . Sactivity->category->mg224225=226=227228229—230_231232-233 V234id THEN •(ownhubspot':-© PlainTextDecorateActivity.plC Dummy1357$payload = ['comments' => $this-›generateActivityDescription(Sactivity),'action' = $action->value,'commentingPerson' => ['id'=> (int) $this->profile->crm_provider_id,'type' => 'CorporateUser',= 11512582;v D Helpers1358T ActivityPlaybookTrait.php1359© Arraylterator.php1360# CannantionCtstaTrait nhn1,'externalID' = $activity->id_string,'minutesSpent' = $activity->duration,AHnTEARRATWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)AATRATTATCHATMAT T WIATIARCNnAwE)W Windsurf Teams1343:30UTF-8Co 4 spaces...
|
45388
|
NULL
|
NULL
|
NULL
|
|
45389
|
1626
|
20
|
2026-05-14T14:34:00.396565+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769240396_m2.jpg...
|
PhpStorm
|
faVsco.js – BullhornService.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.66456115,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.67586434,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.6871675,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.7150931,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.72639626,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.73769945,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
2586234742233688171
|
-7051436856496256053
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pm~ (Q SearchDate ModifiedYesterdav at 13.3Yesterday at 13:37Yesterday at 13.30Yesterday at 13:35resterday at 15.34Yesterdav at 13:34Yesterday at 13:33Yesterday at 13.32Yesterday at 13:32resterday at 15.3Yesterdav at 13:30Yesterday at 13:30Yesterday at 13:29Yesterday at 13:29Yesterday at 13:28resterday at 13-21Yesterdav at 13:27Yesterday at 13:26Yesterday at 13:26Yesterday at 13:25Yesterday at 13.24Yesterdav at 13:22Yesterday at 13:22resterady al 15.clYesterday at 13:20Yesterday at 13.19Yecterdav at 12:10Yesterday at 13:18Yesterday at 13.10Yesterdav at 13:17Yesterday at 13:17Yesterday at 13:16Yacterdav at 12:15Yesterday at 13.14Yecterdav at 12:14Yesterday at 13:13Yesterday at 13:12Yesterday at 13:12Yesterday at 13.11Yecterdav at 12:10Yesterday at 13:10Yesterdav at 13:0962 K:MPEG-4 movie71 KBMPEG-4 movie23 KBMPEG-4 movieMPEG-4 movie13 KE16 KB17 KBMPE0"4 movie29 K:6 KBMPEG-4 movie12 KBMP2G-4 movieMPEG-4 movie7 KBI8 KB37 KBMPEG"4 movie10 KВIMPEG-4 movie7 KBMPEG-4 movie8 KB9 KB1MPEG-4 movie8 KBMPEG-4 movie72 KB14 KBMPEG-4 movie13 KEMPEG-4 movie9 KB MPEG-4 movie18 KB12 KB|MPEG-4 movie10 KBMPEG-4 movie16 KB6KBMPEG-4 movie6KEMPEG-4 movie12 KBMPEG-4 movie23 KBMPEG-4 movie8 K:MPEG-4 movie6 KBMPEG-4 movie11 KBMPEG-4 movie11 KPMPEG-4 movie20 KB34 KB10 K:MPEG-4 movie7KBMPEG-4 movie5 KB11 KBMPEG-4 movieD6KRMDEG-A movia111 KBMPEG-4 movie102 KBMPEG-4 movie88 KBMPEG-A movie59 KB MPEG-4 movie98 KB97 KBGAKPMPEG-4 movieMPEG-4 movie44 KB93 KBMPEG-4 movie78 KPMDEG-A movid50 KBMPEG-4 movie58 KB17 KBMPEG-4 movieAl Notes: OffLeave• 0FavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderLocationsQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zio• Photos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВ148 KB122 KB111 KB94 KBZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.48 GB availabld• Inu 14 Mау 1/•34-00Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
45387
|
NULL
|
NULL
|
NULL
|
|
45388
|
1625
|
35
|
2026-05-14T14:34:00.118762+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769240118_m1.jpg...
|
PhpStorm
|
faVsco.js – BullhornService.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
73
3
11
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Bullhorn;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\Provider\BullhornInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\ApplicationException;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\DomainException;
use Jiminny\Exceptions\HttpBadRequestException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\ServiceUnavailableException;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\UserRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
use Ramsey\Uuid\Uuid;
class BullhornService extends BaseService implements
BullhornInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const string ENTITY_LEAD = 'Candidate';
private const string ENTITY_OPPORTUNITY = 'JobOrder';
private const string ENTITY_ACCOUNT = 'ClientCorporation';
private const string ENTITY_CONTACT = 'ClientContact';
private const string ENTITY_ACTIVITY = 'Note';
private const array OPPORTUNITY_FIELDS = [
'id',
'owner',
'status',
'title',
'salary',
'salaryUnit',
'payRate',
'isOpen',
'employmentType',
'dateClosed',
'startDate',
'dateLastModified',
'dateAdded',
'clientCorporation',
'correlatedCustomText10', // currency
];
private const array TASK_FIELDS = [
'id',
'comments',
'dateAdded',
'dateLastModified',
'externalID',
'isDeleted',
'corporateUsers',
'clientContacts',
'commentingPerson',
'candidates',
'jobOrder',
'minutesSpent',
'action',
];
private const array LEAD_FIELDS = [
'id',
'name',
'owner',
'occupation',
'companyName',
'companyURL',
'mobile',
'phone',
'phone2',
'phone3',
'workPhone',
'status',
'address',
'dateAdded',
'dateLastModified',
];
private const array CONTACT_FIELDS = [
'id',
'name',
'occupation',
'mobile',
'phone',
'phone2',
'phone3',
'address',
'clientCorporation',
'dateAdded',
'owner',
];
private const array ACCOUNT_FIELDS = [
'id',
'name',
'phone',
'industryList',
'address',
'companyURL',
'dateAdded',
];
public function __construct(
BullhornClientInterface $client,
private readonly UserRepository $userRepository,
private readonly ProspectPhotoPathService $prospectPhotoPathService
) {
parent::__construct();
$this->client = $client;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);
}
public function getDisplayName(): string
{
return 'Bullhorn';
}
public function createTranscriptNotes(Activity $activity): void
{
// Not done until a customer requests it.
}
public function syncProfileFields(): void
{
$fieldTypes = [
'lead',
'account',
'contact',
'opportunity',
'task',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))
);
if (! empty($changedFields)) {
$fields = implode(',', $newFields);
Log::debug(
sprintf(
'%s fields changed from %s to: %s',
ucfirst($fieldType),
$this->profile->{$fieldType . '_fields'},
$fields,
),
);
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (\Exception $exception) {
\Log::error('No access to ' . $fieldType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
$this->profile->save();
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
//parent::OBJECT_ACCOUNT,
//parent::OBJECT_CONTACT,
//parent::OBJECT_OPPORTUNITY,
//parent::OBJECT_LEAD,
];
}
protected function getFields(string $crmObject): array
{
$fields = [];
foreach ($this->getObjectFields($crmObject) as $row) {
$fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];
}
return $fields;
}
private function getObjectFields(string $objectType): array
{
$entityType = $this->convertObjectTypeToResource($objectType);
return Cache::remember(
key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,
ttl: 60 * 60,
callback: function () use ($entityType) {
$entity = $this->client->get('meta/' . $entityType, [
'fields' => '*',
]);
return $entity['fields'];
},
);
}
public function getDefaultFields(string $activityType): array
{
$fields = [];
$defaultFields = FieldDefinitions::defaultFields();
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
return $fields;
}
public function getDefaultActivityField(string $activityType): Field
{
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'action',
'object_type' => $activityType,
])->first();
return $activityField;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
// We are not yet supporting follow-ups for this system.
return [];
}
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return $fieldValue;
}
public function syncField(Field $field): void
{
$resource = $this->convertObjectTypeToResource($field->object_type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => $field->crm_provider_id,
'meta' => 'full',
]);
$bhField = $entity['fields'][0];
$isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);
$description = null;
if (empty($bhField['description']) === false) {
$description = mb_strimwidth($bhField['description'], 0, 191);
}
$label = 'Unknown';
if (empty($bhField['label']) === false) {
$label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);
}
$field->length = $bhField['maxLength'] ?? null;
$field->is_mandatory = $isMandatory;
$field->description = $description;
$field->label = $label;
$field->type = $this->convertFieldType(
$bhField['dataType'] ?? null,
$bhField['dataSpecialization'] ?? null,
$bhField['inputType'] ?? null
);
$field->save();
if (empty($bhField['options']) === false) {
$values = [];
// Import all values.
foreach ($bhField['options'] as $i => $option) {
$values[] = [
'value' => $option['value'],
'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),
'sequence' => $i,
];
}
// Take the existing set of field values.
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
// For all current values, upsert the field.
$field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
$key = array_search($value['value'], $fieldsToPurge, false);
if ($key !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
}
}
public function importPicklistValues(Field $field): array
{
// Taken care of in syncField.
return [];
}
private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string
{
if ($type === null) {
return Field::TYPE_UNSUPPORTED;
}
$type = strtolower($type);
$specialization = strtolower($specialization);
$inputType = strtolower($inputType);
switch ($type) {
case 'boolean':
return Field::TYPE_BOOLEAN;
case 'integer':
switch ($specialization) {
case 'integer':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'bigdecimal':
switch ($specialization) {
case 'money':
return Field::TYPE_CURRENCY;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'double':
switch ($specialization) {
case 'float':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'timestamp':
switch ($specialization) {
case 'date':
return Field::TYPE_DATE;
case 'time':
return Field::TYPE_TIME;
case 'datetime':
return Field::TYPE_DATETIME;
default:
return Field::TYPE_DATE;
}
// no break
case 'string':
switch ($inputType) {
case 'textarea':
return Field::TYPE_TEXTAREA;
case 'select':
return Field::TYPE_PICKLIST;
default:
return Field::TYPE_TEXT;
}
// no break
default:
// This is not actually a supported field.
return Field::TYPE_UNSUPPORTED;
}
}
private function importContact($crmData): Contact
{
$account = $mobilePhone = $phone = $email = null;
if (empty($crmData['clientCorporation']) === false) {
$account = $this->team
->accounts()
->where('crm_provider_id', $crmData['clientCorporation']['id'])
->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
}
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => $crmData['name'],
'email' => $email,
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'title' => $crmData['occupation'],
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Contact::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importOpportunity($crmData): ?Opportunity
{
if ($crmData['clientCorporation']['id']) {
$account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
} else {
// If there is nothing to associate this with, don't import it.
return null;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$stage = $this->config->stages()
->where('crm_provider_id', $crmData['status'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);
}
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => mb_strimwidth($crmData['title'], 0, 128),
'value' => $crmData['salary'] ?? $crmData['payRate'],
'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),
'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),
'is_closed' => $crmData['isOpen'] !== true,
'is_won' => strtolower($crmData['status']) === 'placed',
'stage_id' => $stage->id,
'record_type_id' => null,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importAccount($crmData): Account
{
$countryCode = $domain = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$name = $crmData['name'] ?? 'Unknown';
if ($crmData['companyURL'] !== null) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$data = [
'team_id' => $this->team->id,
'user_id' => null,
'owner_id' => null,
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Account::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'country_code' => $countryCode,
'domain' => $domain,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importLead($crmData): ?Lead
{
// Get the current stage.
$stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);
}
// If we have no way of importing this, just return null :(
if ($stage === null) {
return null;
}
$countryCode = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$mobilePhone = $phone = $email = null;
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$company = 'Unknown';
if (empty($crmData['companyName']) === false) {
$companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];
$company = mb_strimwidth($companyName, 0, 191);
}
$domain = null;
if (empty($crmData['companyURL']) === false) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'company' => $company,
'domain' => $domain,
'name' => mb_strimwidth($crmData['name'], 0, 191),
'title' => mb_strimwidth($crmData['occupation'], 0, 128),
'email' => mb_strimwidth($email, 0, 80),
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Lead::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'stage_id' => $stage->id,
'country_code' => $countryCode,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
/**
* @throws ApplicationException
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhContacts = $this->client->get('search/ClientContact', $params);
foreach ($bhContacts['data'] as $bhContact) {
// Only sync if previously imported.
if ($this->hasContact($bhContact['id'])) {
$this->importContact($bhContact);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategies = $strategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
$total = 0;
$count = 0;
$offset = 0;
try {
$bhOpportunities = [];
foreach ($strategies as $syncStrategy) {
$opportunitiesData = $syncStrategy->fetchOpportunities($parameters);
$total = (int) ($opportunitiesData['total'] ?? 0);
$count = (int) ($opportunitiesData['count'] ?? 0);
$offset = (int) ($opportunitiesData['start'] ?? 0);
$bhOpportunities[] = $opportunitiesData['data'] ?? [];
}
$bhOpportunities = array_merge(...$bhOpportunities);
foreach ($bhOpportunities as $bhOpportunity) {
$this->importOpportunity($bhOpportunity);
$syncCount++;
}
} catch (\Exception $exception) {
$this->logger->info('Failed to sync opportunities', [
'params' => $parameters,
'exception' => $exception->getMessage(),
]);
}
// only log if there are one sync strategy
if (count($strategies) === 1 && $total > $count + $offset) {
$this->logger->info('[Bullhorn] Sync Opportunities - count warning', [
'team_id' => $this->team->getId(),
'total' => $total,
'count' => $count,
'offset' => $offset,
]);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhAccounts = $this->client->get('search/ClientCorporation', $params);
foreach ($bhAccounts['data'] as $bhAccount) {
// Only sync if previously imported.
if ($this->hasAccount($bhAccount['id'])) {
$this->importAccount($bhAccount);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhLeads = $this->client->get('search/Candidate', $params);
if ($bhLeads === null) {
return $syncCount;
}
foreach ($bhLeads['data'] as $bhLead) {
// Only sync if previously imported.
if ($this->hasLead($bhLead['id'])) {
$this->importLead($bhLead);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncContact(string $crmId): ?Contact
{
try {
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importContact($data['data']);
}
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategy = $strategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
try {
$data = $strategy->fetchOpportunities(['crm_id' => $crmId]);
} catch (HttpNotFoundException $exception) {
$this->logger->info('[Bullhorn] Opportunity not found', [
'crm_id' => $crmId,
'reason' => $exception->getMessage(),
]);
}
return $this->importOpportunity($data['data'] ?? []);
}
public function syncAccount(string $crmId): ?Account
{
try {
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importAccount($data['data']);
}
public function syncLead(string $crmId): ?Lead
{
try {
$data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importLead($data['data']);
}
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$missingStage = null;
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
foreach ($types as $type) {
$resource = $this->convertObjectTypeToResource($type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => 'status',
'meta' => 'full',
]);
$missingStage = null;
if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {
throw new \UnexpectedValueException('Invalid response from Bullhorn API');
}
// Upsert all stages for the team.
foreach ($entity['fields'][0]['options'] as $i => $option) {
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $option['value'],
'type' => $type,
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($option['value'], 0, 50),
'label' => mb_strimwidth($option['label'], 0, 191),
'sequence' => $i,
'is_selectable' => 1,
]);
if ($missingStageName && $missingStageName === $option['value']) {
$missingStage = $stage;
}
}
if ($missingStageName && $missingStage === null) {
// If they requested a stage that still doesn't exist, it must be inactive so lazy create it.
$missingStage = $this->config->stages()->create([
'team_id' => $this->team->id,
'crm_provider_id' => Uuid::uuid4(),
'name' => mb_strimwidth($missingStageName, 0, 50),
'label' => mb_strimwidth($missingStageName, 0, 191),
'type' => $type,
'sequence' => 0,
'is_selectable' => 0,
]);
}
}
return $missingStage;
}
public function syncOrganization(): void
{
// There appears to be nothing we can sync/map to.
}
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$data = \Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {
$result = [];
try {
$objects = $this->client->get('find', [
'query' => $name,
'meta' => 'basic',
'countPerEntity' => $count,
]);
} catch (\GuzzleHttp\Exception\ServerException $exception) {
throw new ServiceUnavailableException($exception->getMessage());
}
foreach ($objects['data'] as $object) {
try {
$prospectType = $this->convertResourceToObjectType($object['entityType']);
} catch (\UnexpectedValueException $exception) {
// We don't support this, so skip it.
continue;
}
$record = [
'crmId' => $object['entityId'],
'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),
'prospectType' => $prospectType,
'phoneNumbers' => [],
];
// Unfortunately we need to go and query each entity itself to get the data we need.
switch ($object['entityType']) {
case self::ENTITY_ACCOUNT:
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['industry'] = $entity['industryList'];
if (empty($entity['phone']) === false) {
$record['phoneNumbers'][] = [
'number' => $entity['phone'],
'nationalFormat' => phone_national(null, $entity['phone']),
'type' => 'phone',
];
}
break;
case self::ENTITY_CONTACT:
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
case self::ENTITY_LEAD:
$bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);
$entity = $bhData['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['companyName'];
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
default:
// We are not interested in this entity type so skip it.
continue 2;
}
$result[] = $record;
}
return $result;
});
return $data;
}
public function getClient(): BullhornClientInterface
{
return $this->client;
}
private function getFieldsAsString(array $fields)
{
return implode(', ', $fields);
}
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),
];
$onlyOpen = true;
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort'] = '-dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort'] = '+dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
$onlyOpen = false;
}
if ($onlyOpen) {
$where .= ' AND isOpen: true';
}
$params['query'] = $where;
$bhOpportunities = $this->client->get('search/JobOrder', $params);
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
foreach ($bhOpportunities['data'] as $bhOpportunity) {
$stage = $this->config
->stages()
->where('crm_provider_id', $bhOpportunity['status'])
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);
}
$record = [
'crmId' => $bhOpportunity['id'],
'name' => $bhOpportunity['title'],
'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),
'won' => strtolower($bhOpportunity['status']) === 'placed',
'closed' => $bhOpportunity['isOpen'] !== true,
'stage' => [
'id' => $stage->id_string,
'name' => $stage->name,
],
'recordType' => [],
];
if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = [];
// For now it has not been agreed on how to implement this e.g. appointments or tasks?
return [];
if ($objectType === 'account' && $opportunityId === null) {
// You cannot attach tasks to only accounts.
return [];
}
// Query should default to any open task.
$where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;
// If we are also going to check on a specific job order, set that up.
if ($opportunityId) {
$where .= ' OR JobOrder: ' . (int) $opportunityId;
}
$where .= ')';
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::TASK_FIELDS),
'query' => $where,
];
$bhTasks = $this->client->get('search/Task', $params);
foreach ($bhTasks['data'] as $bhTask) {
$data[] = [
'crmId' => $bhTask['id'],
'subject' => $bhTask['subject'],
'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),
'type' => null,
];
}
return $data;
}
/**
* @url [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] CrmException
* @throws DomainException
*/
private function buildNotePayload(Activity $activity): Activity
{
if ($activity->hasActivityType() === false) {
throw new DomainException('[Bullhorn] No activity type assigned');
}
$action = $this->getCrmType($activity->getActivityType());
if ($action === null) {
throw new DomainException('[Bullhorn] No mapped CRM type for "' . $activity->category->name . '"');
}
if ($activity->lead_id === null && $activity->contact_id === null) {
throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');
}
$payload = [
'comments' => $this->generateActivityDescription($activity),
'action' => $action->value,
'commentingPerson' => [
'id' => (int) $this->profile->crm_provider_id,
'type' => 'CorporateUser',
],
'externalID' => $activity->id_string,
'minutesSpent' => $activity->duration,
'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),
];
if ($activity->lead_id) {
$payload['personReference'] = [
'id' => (int) $activity->lead->crm_provider_id,
'type' => 'Candidate',
];
}
if ($activity->contact_id) {
$payload['personReference'] = [
'id' => (int) $activity->contact->crm_provider_id,
'type' => 'ClientContact',
];
}
if ($activity->opportunity_id) {
$payload['jobOrders'] = [
'replaceAll' => [
(int) $activity->opportunity->crm_provider_id,
],
];
}
$bhActivity = $this->client->put('entity/Note', $payload);
$activity->crm_provider_id = $bhActivity['changedEntityId'];
$activity->save();
return $activity;
}
private function generateActivityDescription(Activity $activity): string
{
$description = '';
switch ($activity->type) {
case Activity::TYPE_SOFTPHONE:
case Activity::TYPE_SOFTPHONE_INBOUND:
case Activity::TYPE_CONFERENCE:
if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
// Dialer calls have no native field for the subject.
if ($activity->title) {
$description .= sprintf(
'<p><span style="font-size: 16px; line-height: 19.2px;">%s</span></p>',
$activity->title,
);
}
// Conference meetings log duration into a distinct field, so log this in the main text.
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Call Duration: %s</span></p>',
$activity->duration_for_humans,
);
// Tell them which number was dialed.
if ($activity->to) {
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Dialed: %s</span></p>',
$activity->to->phone_number,
);
}
$description .= '<p></p>';
}
if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.6645833,"top":0.027777778,"width":0.15902779,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.82361114,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.8472222,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.87083334,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.9291667,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9527778,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9763889,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.7326389,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"73","depth":4,"bounds":{"left":0.7534722,"top":0.3122222,"width":0.020833334,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.77847224,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"11","depth":4,"bounds":{"left":0.79930556,"top":0.3122222,"width":0.01875,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.8215278,"top":0.31,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.8368056,"top":0.31,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Bullhorn;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\BullhornInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\ApplicationException;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\DomainException;\nuse Jiminny\\Exceptions\\HttpBadRequestException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\ServiceUnavailableException;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\UserRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\nuse Ramsey\\Uuid\\Uuid;\n\nclass BullhornService extends BaseService implements\n BullhornInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const string ENTITY_LEAD = 'Candidate';\n private const string ENTITY_OPPORTUNITY = 'JobOrder';\n private const string ENTITY_ACCOUNT = 'ClientCorporation';\n private const string ENTITY_CONTACT = 'ClientContact';\n private const string ENTITY_ACTIVITY = 'Note';\n\n private const array OPPORTUNITY_FIELDS = [\n 'id',\n 'owner',\n 'status',\n 'title',\n 'salary',\n 'salaryUnit',\n 'payRate',\n 'isOpen',\n 'employmentType',\n 'dateClosed',\n 'startDate',\n 'dateLastModified',\n 'dateAdded',\n 'clientCorporation',\n 'correlatedCustomText10', // currency\n ];\n\n private const array TASK_FIELDS = [\n 'id',\n 'comments',\n 'dateAdded',\n 'dateLastModified',\n 'externalID',\n 'isDeleted',\n 'corporateUsers',\n 'clientContacts',\n 'commentingPerson',\n 'candidates',\n 'jobOrder',\n 'minutesSpent',\n 'action',\n ];\n\n private const array LEAD_FIELDS = [\n 'id',\n 'name',\n 'owner',\n 'occupation',\n 'companyName',\n 'companyURL',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'workPhone',\n 'status',\n 'address',\n 'dateAdded',\n 'dateLastModified',\n ];\n\n private const array CONTACT_FIELDS = [\n 'id',\n 'name',\n 'occupation',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'address',\n 'clientCorporation',\n 'dateAdded',\n 'owner',\n ];\n\n private const array ACCOUNT_FIELDS = [\n 'id',\n 'name',\n 'phone',\n 'industryList',\n 'address',\n 'companyURL',\n 'dateAdded',\n ];\n\n public function __construct(\n BullhornClientInterface $client,\n private readonly UserRepository $userRepository,\n private readonly ProspectPhotoPathService $prospectPhotoPathService\n ) {\n parent::__construct();\n\n $this->client = $client;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);\n }\n\n public function getDisplayName(): string\n {\n return 'Bullhorn';\n }\n\n public function createTranscriptNotes(Activity $activity): void\n {\n // Not done until a customer requests it.\n }\n\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n 'task',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))\n );\n\n if (! empty($changedFields)) {\n $fields = implode(',', $newFields);\n Log::debug(\n sprintf(\n '%s fields changed from %s to: %s',\n ucfirst($fieldType),\n $this->profile->{$fieldType . '_fields'},\n $fields,\n ),\n );\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (\\Exception $exception) {\n \\Log::error('No access to ' . $fieldType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n //parent::OBJECT_ACCOUNT,\n //parent::OBJECT_CONTACT,\n //parent::OBJECT_OPPORTUNITY,\n //parent::OBJECT_LEAD,\n ];\n }\n\n protected function getFields(string $crmObject): array\n {\n $fields = [];\n foreach ($this->getObjectFields($crmObject) as $row) {\n $fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];\n }\n\n return $fields;\n }\n\n private function getObjectFields(string $objectType): array\n {\n $entityType = $this->convertObjectTypeToResource($objectType);\n\n return Cache::remember(\n key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,\n ttl: 60 * 60,\n callback: function () use ($entityType) {\n $entity = $this->client->get('meta/' . $entityType, [\n 'fields' => '*',\n ]);\n\n return $entity['fields'];\n },\n );\n }\n\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n $defaultFields = FieldDefinitions::defaultFields();\n\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n\n return $fields;\n }\n\n public function getDefaultActivityField(string $activityType): Field\n {\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'action',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n // We are not yet supporting follow-ups for this system.\n return [];\n }\n\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return $fieldValue;\n }\n\n public function syncField(Field $field): void\n {\n $resource = $this->convertObjectTypeToResource($field->object_type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => $field->crm_provider_id,\n 'meta' => 'full',\n ]);\n\n $bhField = $entity['fields'][0];\n\n $isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);\n $description = null;\n if (empty($bhField['description']) === false) {\n $description = mb_strimwidth($bhField['description'], 0, 191);\n }\n\n $label = 'Unknown';\n if (empty($bhField['label']) === false) {\n $label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);\n }\n\n $field->length = $bhField['maxLength'] ?? null;\n $field->is_mandatory = $isMandatory;\n $field->description = $description;\n $field->label = $label;\n $field->type = $this->convertFieldType(\n $bhField['dataType'] ?? null,\n $bhField['dataSpecialization'] ?? null,\n $bhField['inputType'] ?? null\n );\n\n $field->save();\n\n if (empty($bhField['options']) === false) {\n $values = [];\n\n // Import all values.\n foreach ($bhField['options'] as $i => $option) {\n $values[] = [\n 'value' => $option['value'],\n 'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),\n 'sequence' => $i,\n ];\n }\n\n // Take the existing set of field values.\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n // For all current values, upsert the field.\n $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n $key = array_search($value['value'], $fieldsToPurge, false);\n if ($key !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n }\n }\n\n public function importPicklistValues(Field $field): array\n {\n // Taken care of in syncField.\n return [];\n }\n\n private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string\n {\n if ($type === null) {\n return Field::TYPE_UNSUPPORTED;\n }\n\n $type = strtolower($type);\n $specialization = strtolower($specialization);\n $inputType = strtolower($inputType);\n\n switch ($type) {\n case 'boolean':\n return Field::TYPE_BOOLEAN;\n\n case 'integer':\n switch ($specialization) {\n case 'integer':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'bigdecimal':\n switch ($specialization) {\n case 'money':\n return Field::TYPE_CURRENCY;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'double':\n switch ($specialization) {\n case 'float':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'timestamp':\n switch ($specialization) {\n case 'date':\n return Field::TYPE_DATE;\n case 'time':\n return Field::TYPE_TIME;\n case 'datetime':\n return Field::TYPE_DATETIME;\n default:\n return Field::TYPE_DATE;\n }\n\n // no break\n case 'string':\n switch ($inputType) {\n case 'textarea':\n return Field::TYPE_TEXTAREA;\n case 'select':\n return Field::TYPE_PICKLIST;\n default:\n return Field::TYPE_TEXT;\n }\n\n // no break\n default:\n // This is not actually a supported field.\n return Field::TYPE_UNSUPPORTED;\n }\n }\n\n private function importContact($crmData): Contact\n {\n $account = $mobilePhone = $phone = $email = null;\n if (empty($crmData['clientCorporation']) === false) {\n $account = $this->team\n ->accounts()\n ->where('crm_provider_id', $crmData['clientCorporation']['id'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n }\n\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => $crmData['name'],\n 'email' => $email,\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'title' => $crmData['occupation'],\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Contact::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n if ($crmData['clientCorporation']['id']) {\n $account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n } else {\n // If there is nothing to associate this with, don't import it.\n return null;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $stage = $this->config->stages()\n ->where('crm_provider_id', $crmData['status'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => mb_strimwidth($crmData['title'], 0, 128),\n 'value' => $crmData['salary'] ?? $crmData['payRate'],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),\n 'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),\n 'is_closed' => $crmData['isOpen'] !== true,\n 'is_won' => strtolower($crmData['status']) === 'placed',\n 'stage_id' => $stage->id,\n 'record_type_id' => null,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importAccount($crmData): Account\n {\n $countryCode = $domain = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $name = $crmData['name'] ?? 'Unknown';\n\n if ($crmData['companyURL'] !== null) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => null,\n 'owner_id' => null,\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Account::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'country_code' => $countryCode,\n 'domain' => $domain,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importLead($crmData): ?Lead\n {\n // Get the current stage.\n $stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);\n }\n\n // If we have no way of importing this, just return null :(\n if ($stage === null) {\n return null;\n }\n\n $countryCode = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $mobilePhone = $phone = $email = null;\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $company = 'Unknown';\n if (empty($crmData['companyName']) === false) {\n $companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];\n $company = mb_strimwidth($companyName, 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['companyURL']) === false) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'company' => $company,\n 'domain' => $domain,\n 'name' => mb_strimwidth($crmData['name'], 0, 191),\n 'title' => mb_strimwidth($crmData['occupation'], 0, 128),\n 'email' => mb_strimwidth($email, 0, 80),\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Lead::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'stage_id' => $stage->id,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhContacts = $this->client->get('search/ClientContact', $params);\n\n foreach ($bhContacts['data'] as $bhContact) {\n // Only sync if previously imported.\n if ($this->hasContact($bhContact['id'])) {\n $this->importContact($bhContact);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategies = $strategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n $total = 0;\n $count = 0;\n $offset = 0;\n\n try {\n $bhOpportunities = [];\n foreach ($strategies as $syncStrategy) {\n $opportunitiesData = $syncStrategy->fetchOpportunities($parameters);\n $total = (int) ($opportunitiesData['total'] ?? 0);\n $count = (int) ($opportunitiesData['count'] ?? 0);\n $offset = (int) ($opportunitiesData['start'] ?? 0);\n $bhOpportunities[] = $opportunitiesData['data'] ?? [];\n }\n\n $bhOpportunities = array_merge(...$bhOpportunities);\n\n foreach ($bhOpportunities as $bhOpportunity) {\n $this->importOpportunity($bhOpportunity);\n $syncCount++;\n }\n } catch (\\Exception $exception) {\n $this->logger->info('Failed to sync opportunities', [\n 'params' => $parameters,\n 'exception' => $exception->getMessage(),\n ]);\n }\n\n // only log if there are one sync strategy\n if (count($strategies) === 1 && $total > $count + $offset) {\n $this->logger->info('[Bullhorn] Sync Opportunities - count warning', [\n 'team_id' => $this->team->getId(),\n 'total' => $total,\n 'count' => $count,\n 'offset' => $offset,\n ]);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhAccounts = $this->client->get('search/ClientCorporation', $params);\n\n foreach ($bhAccounts['data'] as $bhAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($bhAccount['id'])) {\n $this->importAccount($bhAccount);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhLeads = $this->client->get('search/Candidate', $params);\n if ($bhLeads === null) {\n return $syncCount;\n }\n\n foreach ($bhLeads['data'] as $bhLead) {\n // Only sync if previously imported.\n if ($this->hasLead($bhLead['id'])) {\n $this->importLead($bhLead);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n\n public function syncContact(string $crmId): ?Contact\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importContact($data['data']);\n }\n\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategy = $strategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n try {\n $data = $strategy->fetchOpportunities(['crm_id' => $crmId]);\n } catch (HttpNotFoundException $exception) {\n $this->logger->info('[Bullhorn] Opportunity not found', [\n 'crm_id' => $crmId,\n 'reason' => $exception->getMessage(),\n ]);\n }\n\n return $this->importOpportunity($data['data'] ?? []);\n }\n\n public function syncAccount(string $crmId): ?Account\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importAccount($data['data']);\n }\n\n public function syncLead(string $crmId): ?Lead\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importLead($data['data']);\n }\n\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $missingStage = null;\n\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n\n foreach ($types as $type) {\n $resource = $this->convertObjectTypeToResource($type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => 'status',\n 'meta' => 'full',\n ]);\n\n $missingStage = null;\n\n if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {\n throw new \\UnexpectedValueException('Invalid response from Bullhorn API');\n }\n\n // Upsert all stages for the team.\n foreach ($entity['fields'][0]['options'] as $i => $option) {\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $option['value'],\n 'type' => $type,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($option['value'], 0, 50),\n 'label' => mb_strimwidth($option['label'], 0, 191),\n 'sequence' => $i,\n 'is_selectable' => 1,\n ]);\n\n if ($missingStageName && $missingStageName === $option['value']) {\n $missingStage = $stage;\n }\n }\n\n if ($missingStageName && $missingStage === null) {\n // If they requested a stage that still doesn't exist, it must be inactive so lazy create it.\n $missingStage = $this->config->stages()->create([\n 'team_id' => $this->team->id,\n 'crm_provider_id' => Uuid::uuid4(),\n 'name' => mb_strimwidth($missingStageName, 0, 50),\n 'label' => mb_strimwidth($missingStageName, 0, 191),\n 'type' => $type,\n 'sequence' => 0,\n 'is_selectable' => 0,\n ]);\n }\n }\n\n return $missingStage;\n }\n\n public function syncOrganization(): void\n {\n // There appears to be nothing we can sync/map to.\n }\n\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $data = \\Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {\n $result = [];\n\n try {\n $objects = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => $count,\n ]);\n } catch (\\GuzzleHttp\\Exception\\ServerException $exception) {\n throw new ServiceUnavailableException($exception->getMessage());\n }\n\n foreach ($objects['data'] as $object) {\n try {\n $prospectType = $this->convertResourceToObjectType($object['entityType']);\n } catch (\\UnexpectedValueException $exception) {\n // We don't support this, so skip it.\n continue;\n }\n\n $record = [\n 'crmId' => $object['entityId'],\n 'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),\n 'prospectType' => $prospectType,\n 'phoneNumbers' => [],\n ];\n\n // Unfortunately we need to go and query each entity itself to get the data we need.\n switch ($object['entityType']) {\n case self::ENTITY_ACCOUNT:\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['industry'] = $entity['industryList'];\n if (empty($entity['phone']) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity['phone'],\n 'nationalFormat' => phone_national(null, $entity['phone']),\n 'type' => 'phone',\n ];\n }\n\n break;\n\n case self::ENTITY_CONTACT:\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n case self::ENTITY_LEAD:\n $bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);\n $entity = $bhData['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['companyName'];\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n default:\n // We are not interested in this entity type so skip it.\n continue 2;\n }\n\n $result[] = $record;\n }\n\n return $result;\n });\n\n return $data;\n }\n\n public function getClient(): BullhornClientInterface\n {\n return $this->client;\n }\n\n private function getFieldsAsString(array $fields)\n {\n return implode(', ', $fields);\n }\n\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),\n ];\n\n $onlyOpen = true;\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort'] = '-dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort'] = '+dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n $onlyOpen = false;\n }\n\n if ($onlyOpen) {\n $where .= ' AND isOpen: true';\n }\n\n $params['query'] = $where;\n\n $bhOpportunities = $this->client->get('search/JobOrder', $params);\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n foreach ($bhOpportunities['data'] as $bhOpportunity) {\n $stage = $this->config\n ->stages()\n ->where('crm_provider_id', $bhOpportunity['status'])\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);\n }\n\n $record = [\n 'crmId' => $bhOpportunity['id'],\n 'name' => $bhOpportunity['title'],\n 'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),\n 'won' => strtolower($bhOpportunity['status']) === 'placed',\n 'closed' => $bhOpportunity['isOpen'] !== true,\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n 'recordType' => [],\n ];\n\n if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = [];\n\n // For now it has not been agreed on how to implement this e.g. appointments or tasks?\n return [];\n\n if ($objectType === 'account' && $opportunityId === null) {\n // You cannot attach tasks to only accounts.\n return [];\n }\n\n // Query should default to any open task.\n $where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;\n\n // If we are also going to check on a specific job order, set that up.\n if ($opportunityId) {\n $where .= ' OR JobOrder: ' . (int) $opportunityId;\n }\n\n $where .= ')';\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => $where,\n ];\n\n $bhTasks = $this->client->get('search/Task', $params);\n\n foreach ($bhTasks['data'] as $bhTask) {\n $data[] = [\n 'crmId' => $bhTask['id'],\n 'subject' => $bhTask['subject'],\n 'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),\n 'type' => null,\n ];\n }\n\n return $data;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * ?Lead,\n * ?Account,\n * ?Opportunity,\n * ?Contact,\n * ?Stage,\n * ?string\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $bhObject = $this->client->get('find', [\n 'query' => $email,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember === false) {\n $bhObject = $this->client->get('find', [\n 'query' => $rawPhoneNumber ?? $phone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n if (empty($bhObject['data'])) {\n $nationalPhone = phone_national(null, $rawPhoneNumber ?? $phone);\n $formattedPhone = ltrim($nationalPhone, '+0');\n $bhObject = $this->client->get('find', [\n 'query' => $formattedPhone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n }\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n return null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 3) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = \\Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n $bhObject = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->team->getId() . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n public function saveActivity(Activity $activity): Activity\n {\n\n if ($activity->hasCrmProviderId()) {\n return $activity;\n }\n\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildNotePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n /**\n * @throws CrmException\n * @throws DomainException\n */\n private function buildNotePayload(Activity $activity): Activity\n {\n if ($activity->hasActivityType() === false) {\n throw new DomainException('[Bullhorn] No activity type assigned');\n }\n\n $action = $this->getCrmType($activity->getActivityType());\n if ($action === null) {\n throw new DomainException('[Bullhorn] No mapped CRM type for \"' . $activity->category->name . '\"');\n }\n\n if ($activity->lead_id === null && $activity->contact_id === null) {\n throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');\n }\n\n $payload = [\n 'comments' => $this->generateActivityDescription($activity),\n 'action' => $action->value,\n 'commentingPerson' => [\n 'id' => (int) $this->profile->crm_provider_id,\n 'type' => 'CorporateUser',\n ],\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n 'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),\n ];\n\n if ($activity->lead_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->lead->crm_provider_id,\n 'type' => 'Candidate',\n ];\n }\n\n if ($activity->contact_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->contact->crm_provider_id,\n 'type' => 'ClientContact',\n ];\n }\n\n if ($activity->opportunity_id) {\n $payload['jobOrders'] = [\n 'replaceAll' => [\n (int) $activity->opportunity->crm_provider_id,\n ],\n ];\n }\n\n $bhActivity = $this->client->put('entity/Note', $payload);\n\n $activity->crm_provider_id = $bhActivity['changedEntityId'];\n $activity->save();\n\n return $activity;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = '';\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: %s</span></p>',\n $activity->to->phone_number,\n );\n }\n $description .= '<p></p>';\n }\n\n if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: %s</span></p>',\n $activity->from->phone_number,\n );\n $description .= '<p></p>';\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span>'\n . '</p>';\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span>'\n . '</p>';\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= sprintf(\n '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . '<a href=\"%s\" target=\"_blank\">'\n . 'Review in Jiminny'\n . '</a>'\n . '️</span>'\n . '</p>',\n $playbackUrl,\n );\n }\n\n if ($activity->isTypeConference()) {\n $description .= '<p><strong>Attendees</strong></p><ul>';\n\n // Only include participants that joined.\n $participants = $activity->participants()->ghost(false)->whereNotNull('enter_time')->get();\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->name) {\n $attendee .= $participant->name;\n if ($participant->phone_number) {\n $attendee .= ' (' . $participant->phone_number . ')';\n } elseif ($participant->email) {\n $attendee .= ' (' . $participant->email . ')';\n }\n } else {\n $attendee .= $participant->phone_number;\n }\n\n if ($participant->is_ghost) {\n $attendee .= ' <strong>coach</coach>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $description .= $attendee . '</li>';\n }\n $description .= '</ul>';\n }\n\n if (count($activity->notes) > 0) {\n $description .= '<p><strong>Notes</strong></p>';\n\n foreach ($activity->notes as $note) {\n $time = ($note->time > 3600) ? gmdate('H:i:s', $note->time) : gmdate('i:s', $note->time);\n $description .= '<p>' . $time . ' ' . $note->note . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n if ($activity->summary) {\n $description .= '<p><strong>Summary</strong></p><p>' . $activity->summary . '</p><p></p>';\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n // Use Rich-text formatting.\n $description = sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>%s</strong></span></p>',\n $activity->title,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->description,\n );\n\n break;\n }\n\n return $description;\n }\n\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // Not yet required by current customers.\n return null;\n }\n\n public function updateStage($crmObject, Stage $stage): void\n {\n $objectId = $crmObject->crm_provider_id;\n\n $this->updateRecord($stage->type, $objectId, ['status' => $stage->crm_provider_id]);\n }\n\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $start = 0;\n $payload = [\n 'fields' => 'id,email',\n 'where' => 'isDeleted=false',\n 'count' => 500,\n ];\n\n $payload['start'] = $start;\n $profiles = $this->client->get('query/CorporateUser', $payload);\n\n foreach ($profiles['data'] as $profile) {\n if (empty($profile['email'])) {\n continue;\n }\n\n $user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);\n\n // Only import profiles for users we have locally.\n if ($user) {\n $profile = $user->crmProfile()->updateOrCreate([\n 'crm_configuration_id' => $this->config->id,\n 'crm_provider_id' => $profile['id'],\n ]);\n\n if ($userToSearch && $userToSearch->id === $user->id) {\n return $profile;\n }\n }\n }\n\n return null;\n }\n\n protected function convertCrmData(array $entities, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n $mappedEntities = [];\n foreach ($entities as $entity) {\n if (in_array($entity['entityType'], [self::ENTITY_LEAD, self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n $mappedEntities[] = $entity;\n }\n }\n\n // If there is only one match, sync the data and return the object(s).\n if (count($mappedEntities) === 1) {\n $entity = $mappedEntities[0];\n\n if ($entity['entityType'] === self::ENTITY_LEAD) {\n $lead = $this->syncLead($entity['entityId']);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } elseif (in_array($entity['entityType'], [self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n if ($entity['entityType'] === self::ENTITY_CONTACT) {\n $contact = $this->syncContact($entity['entityId']);\n $account = $contact->account;\n } else {\n $account = $this->syncAccount($entity['entityId']);\n }\n\n if ($contact?->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $bhOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact?->crm_provider_id,\n $userId,\n );\n\n // Take the first opportunity, which will be ordered as priority based on their settings.\n if (! empty($bhOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($bhOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n } catch (Exception) {\n // Nothing to see here.\n }\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n // There doesn't appear to be a way to deeplink to anything on https://app.bullhornstaffing.com.\n return null;\n }\n\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $this->client->post('entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId, $data);\n }\n\n public function getRecord(string $objectType, string $objectId, array $fields = ['id']): array\n {\n return $this->client->get(\n url: 'entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId,\n data: ['fields' => $this->getFieldsAsString($fields)],\n );\n }\n\n private function convertObjectTypeToResource(string $objectType)\n {\n switch ($objectType) {\n case FieldData::OBJECT_OPPORTUNITY:\n return self::ENTITY_OPPORTUNITY;\n\n case FieldData::OBJECT_CONTACT:\n return self::ENTITY_CONTACT;\n\n case FieldData::OBJECT_LEAD:\n return self::ENTITY_LEAD;\n\n case FieldData::OBJECT_ACCOUNT:\n return self::ENTITY_ACCOUNT;\n\n case FieldData::OBJECT_TASK:\n return self::ENTITY_ACTIVITY;\n\n default:\n throw new \\UnexpectedValueException('Unsupported object type \"' . $objectType . '\"');\n }\n }\n\n private function convertResourceToObjectType(string $resource): string\n {\n switch ($resource) {\n case self::ENTITY_OPPORTUNITY:\n return FieldData::OBJECT_OPPORTUNITY;\n\n case self::ENTITY_CONTACT:\n return FieldData::OBJECT_CONTACT;\n\n case self::ENTITY_LEAD:\n return FieldData::OBJECT_LEAD;\n\n case self::ENTITY_ACCOUNT:\n return FieldData::OBJECT_ACCOUNT;\n\n case self::ENTITY_ACTIVITY:\n return FieldData::OBJECT_TASK;\n\n default:\n throw new \\UnexpectedValueException('Unsupported resource \"' . $resource . '\"');\n }\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n // We need to know when it started to determine when to look for related activity.\n if ($activity->hasActualStartTime() === false) {\n return null;\n }\n\n try {\n $bhNote = $this->fetchRelatedActivity($activity);\n if (empty($bhNote)) {\n $this->logger->info('[Bullhorn] No related activity found', [\n 'activity' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $activityType = $this->getPlaybookCategory($this->getPlaybook($activity->user), $bhNote['action']);\n $comments = $bhNote['comments'] . '<br />//<br />' . $this->generateActivityDescription($activity);\n // Now update the Note to contain our data.\n $payload = [\n 'comments' => $comments,\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n ];\n\n $this->logger->info('[Bullhorn] updating related activity', [\n 'activity' => $activity->getUuid(),\n 'activityType' => $activityType->id ?? null,\n ]);\n\n $this->client->post('entity/Note/' . $bhNote['id'], $payload);\n\n $playbookCategoryId = null;\n if ($activity->getCategory() !== null) {\n $playbookCategoryId = $activity->getCategory()->getId();\n }\n\n // Update our activity to reflect the remote data.\n $activity->update([\n 'crm_provider_id' => $bhNote['id'],\n 'summary' => $bhNote['comments'],\n 'playbook_category_id' => $activityType->id ?? $playbookCategoryId,\n ]);\n\n return $activity;\n } catch (\\Exception $exception) {\n \\Sentry::captureException($exception);\n\n throw $exception;\n }\n }\n\n /**\n * Returns the most recently modified note within time range (if any).\n *\n * @return array A Note record from Bullhorn.\n */\n public function fetchRelatedActivity(Activity $activity): array\n {\n $from = $activity->hasScheduledStartTime()\n ? $activity->getScheduledStartTime()\n : $activity->getActualStartTime();\n $to = $activity->hasActualEndTime()\n ? $activity->getActualEndTime()?->addMinutes(15)\n : $from?->clone()->addMinutes(15);\n\n $filterStatements = [\n 'isDeleted: false',\n '*:* -externalID:[* TO *]', // externalID should be null e.g. we did not already relate it.\n sprintf('commentingPerson: %d', (int) $this->profile->crm_provider_id),\n ];\n\n /**\n * @XXX: Bullhorn does not specify the time zone in their docs. I've found a forum thread in which someone from\n * staff asserts it's UTC, however in my field test I've found it to be GMT-0300 (USA east coast).\n * To make the code immune to such glitches we will add 24h to start/end boundaries and will filter out\n * any excess items in code\n */\n $filterStatements[] = sprintf(\n 'dateLastModified:[%s TO %s]',\n $from?->clone()->subHours(24)->format('YmdHis'),\n $to->clone()->addHours(24)->format('YmdHis'),\n );\n\n if ($activity->lead_id) {\n $filterStatements[] = sprintf('candidateUserID: %d', (int) $activity->lead->crm_provider_id);\n }\n\n if ($activity->contact_id) {\n $filterStatements[] = sprintf('clientContactUserID: %d', (int) $activity->contact->crm_provider_id);\n }\n\n // if there is no contact or lead associated to the activity exit\n if ($activity->contact_id === null && $activity->lead_id === null) {\n return [];\n }\n\n $params = [\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => implode(' AND ', $filterStatements),\n 'sort' => '-dateLastModified',\n ];\n\n $bhNotes = $this->client->get('search/Note', $params);\n\n $startStamp = $from?->getTimestamp() * 1000;\n $endStamp = $to->getTimestamp() * 1000;\n\n $filteredNotes = array_values(\n array_filter(\n $bhNotes['data'],\n static fn (array $bhNote): bool\n => $bhNote['dateLastModified'] >= $startStamp && $startStamp <= $endStamp,\n ),\n );\n\n return ! empty($filteredNotes) ? array_shift($filteredNotes) : [];\n }\n\n /**\n * Select how to create the date out of the Bullhorn payload.\n * Do not allow dates beyond 9999-12-31 (max mysql DATE)\n */\n private function filterOutOfBoundDates(string $rawDateCandidate): ?Carbon\n {\n if (strlen($rawDateCandidate) > 12) {\n // A unix timestamp represented with more than 12 digits i\n // s definitely including milliseconds\n $dateFormatted = Carbon::createFromTimestampMs($rawDateCandidate);\n } else {\n $dateFormatted = Carbon::createFromTimestamp($rawDateCandidate);\n }\n\n $minDate = Carbon::createFromFormat('Y-m-d', '2000-01-01');\n if ($dateFormatted->lt($minDate)) {\n return null;\n }\n\n $maxDate = Carbon::createFromFormat('Y-m-d', '9999-12-31');\n if ($dateFormatted->gt($maxDate)) {\n $this->logger->warning('[Bullhorn] An out of bound date is provided', [\n 'date' => $dateFormatted,\n 'rawDate' => $rawDateCandidate,\n ]);\n\n return $maxDate;\n }\n\n return $dateFormatted;\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n $note = $this->getRecord('Note', $crmProviderId, ['id', 'isDeleted']);\n\n return ! empty($note) && ($note['isDeleted'] ?? false) === false;\n } catch (HttpNotFoundException|HttpBadRequestException) {\n // Note not found in CRM - this is expected and permanent\n $this->logger->info('[Bullhorn] Note not found during verification', [\n 'note_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Bullhorn;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\BullhornInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\ApplicationException;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\DomainException;\nuse Jiminny\\Exceptions\\HttpBadRequestException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\ServiceUnavailableException;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\UserRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\nuse Ramsey\\Uuid\\Uuid;\n\nclass BullhornService extends BaseService implements\n BullhornInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const string ENTITY_LEAD = 'Candidate';\n private const string ENTITY_OPPORTUNITY = 'JobOrder';\n private const string ENTITY_ACCOUNT = 'ClientCorporation';\n private const string ENTITY_CONTACT = 'ClientContact';\n private const string ENTITY_ACTIVITY = 'Note';\n\n private const array OPPORTUNITY_FIELDS = [\n 'id',\n 'owner',\n 'status',\n 'title',\n 'salary',\n 'salaryUnit',\n 'payRate',\n 'isOpen',\n 'employmentType',\n 'dateClosed',\n 'startDate',\n 'dateLastModified',\n 'dateAdded',\n 'clientCorporation',\n 'correlatedCustomText10', // currency\n ];\n\n private const array TASK_FIELDS = [\n 'id',\n 'comments',\n 'dateAdded',\n 'dateLastModified',\n 'externalID',\n 'isDeleted',\n 'corporateUsers',\n 'clientContacts',\n 'commentingPerson',\n 'candidates',\n 'jobOrder',\n 'minutesSpent',\n 'action',\n ];\n\n private const array LEAD_FIELDS = [\n 'id',\n 'name',\n 'owner',\n 'occupation',\n 'companyName',\n 'companyURL',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'workPhone',\n 'status',\n 'address',\n 'dateAdded',\n 'dateLastModified',\n ];\n\n private const array CONTACT_FIELDS = [\n 'id',\n 'name',\n 'occupation',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'address',\n 'clientCorporation',\n 'dateAdded',\n 'owner',\n ];\n\n private const array ACCOUNT_FIELDS = [\n 'id',\n 'name',\n 'phone',\n 'industryList',\n 'address',\n 'companyURL',\n 'dateAdded',\n ];\n\n public function __construct(\n BullhornClientInterface $client,\n private readonly UserRepository $userRepository,\n private readonly ProspectPhotoPathService $prospectPhotoPathService\n ) {\n parent::__construct();\n\n $this->client = $client;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);\n }\n\n public function getDisplayName(): string\n {\n return 'Bullhorn';\n }\n\n public function createTranscriptNotes(Activity $activity): void\n {\n // Not done until a customer requests it.\n }\n\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n 'task',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))\n );\n\n if (! empty($changedFields)) {\n $fields = implode(',', $newFields);\n Log::debug(\n sprintf(\n '%s fields changed from %s to: %s',\n ucfirst($fieldType),\n $this->profile->{$fieldType . '_fields'},\n $fields,\n ),\n );\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (\\Exception $exception) {\n \\Log::error('No access to ' . $fieldType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n //parent::OBJECT_ACCOUNT,\n //parent::OBJECT_CONTACT,\n //parent::OBJECT_OPPORTUNITY,\n //parent::OBJECT_LEAD,\n ];\n }\n\n protected function getFields(string $crmObject): array\n {\n $fields = [];\n foreach ($this->getObjectFields($crmObject) as $row) {\n $fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];\n }\n\n return $fields;\n }\n\n private function getObjectFields(string $objectType): array\n {\n $entityType = $this->convertObjectTypeToResource($objectType);\n\n return Cache::remember(\n key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,\n ttl: 60 * 60,\n callback: function () use ($entityType) {\n $entity = $this->client->get('meta/' . $entityType, [\n 'fields' => '*',\n ]);\n\n return $entity['fields'];\n },\n );\n }\n\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n $defaultFields = FieldDefinitions::defaultFields();\n\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n\n return $fields;\n }\n\n public function getDefaultActivityField(string $activityType): Field\n {\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'action',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n // We are not yet supporting follow-ups for this system.\n return [];\n }\n\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return $fieldValue;\n }\n\n public function syncField(Field $field): void\n {\n $resource = $this->convertObjectTypeToResource($field->object_type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => $field->crm_provider_id,\n 'meta' => 'full',\n ]);\n\n $bhField = $entity['fields'][0];\n\n $isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);\n $description = null;\n if (empty($bhField['description']) === false) {\n $description = mb_strimwidth($bhField['description'], 0, 191);\n }\n\n $label = 'Unknown';\n if (empty($bhField['label']) === false) {\n $label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);\n }\n\n $field->length = $bhField['maxLength'] ?? null;\n $field->is_mandatory = $isMandatory;\n $field->description = $description;\n $field->label = $label;\n $field->type = $this->convertFieldType(\n $bhField['dataType'] ?? null,\n $bhField['dataSpecialization'] ?? null,\n $bhField['inputType'] ?? null\n );\n\n $field->save();\n\n if (empty($bhField['options']) === false) {\n $values = [];\n\n // Import all values.\n foreach ($bhField['options'] as $i => $option) {\n $values[] = [\n 'value' => $option['value'],\n 'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),\n 'sequence' => $i,\n ];\n }\n\n // Take the existing set of field values.\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n // For all current values, upsert the field.\n $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n $key = array_search($value['value'], $fieldsToPurge, false);\n if ($key !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n }\n }\n\n public function importPicklistValues(Field $field): array\n {\n // Taken care of in syncField.\n return [];\n }\n\n private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string\n {\n if ($type === null) {\n return Field::TYPE_UNSUPPORTED;\n }\n\n $type = strtolower($type);\n $specialization = strtolower($specialization);\n $inputType = strtolower($inputType);\n\n switch ($type) {\n case 'boolean':\n return Field::TYPE_BOOLEAN;\n\n case 'integer':\n switch ($specialization) {\n case 'integer':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'bigdecimal':\n switch ($specialization) {\n case 'money':\n return Field::TYPE_CURRENCY;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'double':\n switch ($specialization) {\n case 'float':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'timestamp':\n switch ($specialization) {\n case 'date':\n return Field::TYPE_DATE;\n case 'time':\n return Field::TYPE_TIME;\n case 'datetime':\n return Field::TYPE_DATETIME;\n default:\n return Field::TYPE_DATE;\n }\n\n // no break\n case 'string':\n switch ($inputType) {\n case 'textarea':\n return Field::TYPE_TEXTAREA;\n case 'select':\n return Field::TYPE_PICKLIST;\n default:\n return Field::TYPE_TEXT;\n }\n\n // no break\n default:\n // This is not actually a supported field.\n return Field::TYPE_UNSUPPORTED;\n }\n }\n\n private function importContact($crmData): Contact\n {\n $account = $mobilePhone = $phone = $email = null;\n if (empty($crmData['clientCorporation']) === false) {\n $account = $this->team\n ->accounts()\n ->where('crm_provider_id', $crmData['clientCorporation']['id'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n }\n\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => $crmData['name'],\n 'email' => $email,\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'title' => $crmData['occupation'],\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Contact::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n if ($crmData['clientCorporation']['id']) {\n $account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n } else {\n // If there is nothing to associate this with, don't import it.\n return null;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $stage = $this->config->stages()\n ->where('crm_provider_id', $crmData['status'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => mb_strimwidth($crmData['title'], 0, 128),\n 'value' => $crmData['salary'] ?? $crmData['payRate'],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),\n 'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),\n 'is_closed' => $crmData['isOpen'] !== true,\n 'is_won' => strtolower($crmData['status']) === 'placed',\n 'stage_id' => $stage->id,\n 'record_type_id' => null,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importAccount($crmData): Account\n {\n $countryCode = $domain = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $name = $crmData['name'] ?? 'Unknown';\n\n if ($crmData['companyURL'] !== null) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => null,\n 'owner_id' => null,\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Account::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'country_code' => $countryCode,\n 'domain' => $domain,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importLead($crmData): ?Lead\n {\n // Get the current stage.\n $stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);\n }\n\n // If we have no way of importing this, just return null :(\n if ($stage === null) {\n return null;\n }\n\n $countryCode = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $mobilePhone = $phone = $email = null;\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $company = 'Unknown';\n if (empty($crmData['companyName']) === false) {\n $companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];\n $company = mb_strimwidth($companyName, 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['companyURL']) === false) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'company' => $company,\n 'domain' => $domain,\n 'name' => mb_strimwidth($crmData['name'], 0, 191),\n 'title' => mb_strimwidth($crmData['occupation'], 0, 128),\n 'email' => mb_strimwidth($email, 0, 80),\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Lead::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'stage_id' => $stage->id,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhContacts = $this->client->get('search/ClientContact', $params);\n\n foreach ($bhContacts['data'] as $bhContact) {\n // Only sync if previously imported.\n if ($this->hasContact($bhContact['id'])) {\n $this->importContact($bhContact);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategies = $strategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n $total = 0;\n $count = 0;\n $offset = 0;\n\n try {\n $bhOpportunities = [];\n foreach ($strategies as $syncStrategy) {\n $opportunitiesData = $syncStrategy->fetchOpportunities($parameters);\n $total = (int) ($opportunitiesData['total'] ?? 0);\n $count = (int) ($opportunitiesData['count'] ?? 0);\n $offset = (int) ($opportunitiesData['start'] ?? 0);\n $bhOpportunities[] = $opportunitiesData['data'] ?? [];\n }\n\n $bhOpportunities = array_merge(...$bhOpportunities);\n\n foreach ($bhOpportunities as $bhOpportunity) {\n $this->importOpportunity($bhOpportunity);\n $syncCount++;\n }\n } catch (\\Exception $exception) {\n $this->logger->info('Failed to sync opportunities', [\n 'params' => $parameters,\n 'exception' => $exception->getMessage(),\n ]);\n }\n\n // only log if there are one sync strategy\n if (count($strategies) === 1 && $total > $count + $offset) {\n $this->logger->info('[Bullhorn] Sync Opportunities - count warning', [\n 'team_id' => $this->team->getId(),\n 'total' => $total,\n 'count' => $count,\n 'offset' => $offset,\n ]);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhAccounts = $this->client->get('search/ClientCorporation', $params);\n\n foreach ($bhAccounts['data'] as $bhAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($bhAccount['id'])) {\n $this->importAccount($bhAccount);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhLeads = $this->client->get('search/Candidate', $params);\n if ($bhLeads === null) {\n return $syncCount;\n }\n\n foreach ($bhLeads['data'] as $bhLead) {\n // Only sync if previously imported.\n if ($this->hasLead($bhLead['id'])) {\n $this->importLead($bhLead);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n\n public function syncContact(string $crmId): ?Contact\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importContact($data['data']);\n }\n\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategy = $strategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n try {\n $data = $strategy->fetchOpportunities(['crm_id' => $crmId]);\n } catch (HttpNotFoundException $exception) {\n $this->logger->info('[Bullhorn] Opportunity not found', [\n 'crm_id' => $crmId,\n 'reason' => $exception->getMessage(),\n ]);\n }\n\n return $this->importOpportunity($data['data'] ?? []);\n }\n\n public function syncAccount(string $crmId): ?Account\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importAccount($data['data']);\n }\n\n public function syncLead(string $crmId): ?Lead\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importLead($data['data']);\n }\n\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $missingStage = null;\n\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n\n foreach ($types as $type) {\n $resource = $this->convertObjectTypeToResource($type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => 'status',\n 'meta' => 'full',\n ]);\n\n $missingStage = null;\n\n if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {\n throw new \\UnexpectedValueException('Invalid response from Bullhorn API');\n }\n\n // Upsert all stages for the team.\n foreach ($entity['fields'][0]['options'] as $i => $option) {\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $option['value'],\n 'type' => $type,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($option['value'], 0, 50),\n 'label' => mb_strimwidth($option['label'], 0, 191),\n 'sequence' => $i,\n 'is_selectable' => 1,\n ]);\n\n if ($missingStageName && $missingStageName === $option['value']) {\n $missingStage = $stage;\n }\n }\n\n if ($missingStageName && $missingStage === null) {\n // If they requested a stage that still doesn't exist, it must be inactive so lazy create it.\n $missingStage = $this->config->stages()->create([\n 'team_id' => $this->team->id,\n 'crm_provider_id' => Uuid::uuid4(),\n 'name' => mb_strimwidth($missingStageName, 0, 50),\n 'label' => mb_strimwidth($missingStageName, 0, 191),\n 'type' => $type,\n 'sequence' => 0,\n 'is_selectable' => 0,\n ]);\n }\n }\n\n return $missingStage;\n }\n\n public function syncOrganization(): void\n {\n // There appears to be nothing we can sync/map to.\n }\n\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $data = \\Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {\n $result = [];\n\n try {\n $objects = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => $count,\n ]);\n } catch (\\GuzzleHttp\\Exception\\ServerException $exception) {\n throw new ServiceUnavailableException($exception->getMessage());\n }\n\n foreach ($objects['data'] as $object) {\n try {\n $prospectType = $this->convertResourceToObjectType($object['entityType']);\n } catch (\\UnexpectedValueException $exception) {\n // We don't support this, so skip it.\n continue;\n }\n\n $record = [\n 'crmId' => $object['entityId'],\n 'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),\n 'prospectType' => $prospectType,\n 'phoneNumbers' => [],\n ];\n\n // Unfortunately we need to go and query each entity itself to get the data we need.\n switch ($object['entityType']) {\n case self::ENTITY_ACCOUNT:\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['industry'] = $entity['industryList'];\n if (empty($entity['phone']) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity['phone'],\n 'nationalFormat' => phone_national(null, $entity['phone']),\n 'type' => 'phone',\n ];\n }\n\n break;\n\n case self::ENTITY_CONTACT:\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n case self::ENTITY_LEAD:\n $bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);\n $entity = $bhData['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['companyName'];\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n default:\n // We are not interested in this entity type so skip it.\n continue 2;\n }\n\n $result[] = $record;\n }\n\n return $result;\n });\n\n return $data;\n }\n\n public function getClient(): BullhornClientInterface\n {\n return $this->client;\n }\n\n private function getFieldsAsString(array $fields)\n {\n return implode(', ', $fields);\n }\n\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),\n ];\n\n $onlyOpen = true;\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort'] = '-dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort'] = '+dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n $onlyOpen = false;\n }\n\n if ($onlyOpen) {\n $where .= ' AND isOpen: true';\n }\n\n $params['query'] = $where;\n\n $bhOpportunities = $this->client->get('search/JobOrder', $params);\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n foreach ($bhOpportunities['data'] as $bhOpportunity) {\n $stage = $this->config\n ->stages()\n ->where('crm_provider_id', $bhOpportunity['status'])\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);\n }\n\n $record = [\n 'crmId' => $bhOpportunity['id'],\n 'name' => $bhOpportunity['title'],\n 'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),\n 'won' => strtolower($bhOpportunity['status']) === 'placed',\n 'closed' => $bhOpportunity['isOpen'] !== true,\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n 'recordType' => [],\n ];\n\n if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = [];\n\n // For now it has not been agreed on how to implement this e.g. appointments or tasks?\n return [];\n\n if ($objectType === 'account' && $opportunityId === null) {\n // You cannot attach tasks to only accounts.\n return [];\n }\n\n // Query should default to any open task.\n $where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;\n\n // If we are also going to check on a specific job order, set that up.\n if ($opportunityId) {\n $where .= ' OR JobOrder: ' . (int) $opportunityId;\n }\n\n $where .= ')';\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => $where,\n ];\n\n $bhTasks = $this->client->get('search/Task', $params);\n\n foreach ($bhTasks['data'] as $bhTask) {\n $data[] = [\n 'crmId' => $bhTask['id'],\n 'subject' => $bhTask['subject'],\n 'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),\n 'type' => null,\n ];\n }\n\n return $data;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * ?Lead,\n * ?Account,\n * ?Opportunity,\n * ?Contact,\n * ?Stage,\n * ?string\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $bhObject = $this->client->get('find', [\n 'query' => $email,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember === false) {\n $bhObject = $this->client->get('find', [\n 'query' => $rawPhoneNumber ?? $phone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n if (empty($bhObject['data'])) {\n $nationalPhone = phone_national(null, $rawPhoneNumber ?? $phone);\n $formattedPhone = ltrim($nationalPhone, '+0');\n $bhObject = $this->client->get('find', [\n 'query' => $formattedPhone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n }\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n return null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 3) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = \\Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n $bhObject = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->team->getId() . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n public function saveActivity(Activity $activity): Activity\n {\n\n if ($activity->hasCrmProviderId()) {\n return $activity;\n }\n\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildNotePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n /**\n * @throws CrmException\n * @throws DomainException\n */\n private function buildNotePayload(Activity $activity): Activity\n {\n if ($activity->hasActivityType() === false) {\n throw new DomainException('[Bullhorn] No activity type assigned');\n }\n\n $action = $this->getCrmType($activity->getActivityType());\n if ($action === null) {\n throw new DomainException('[Bullhorn] No mapped CRM type for \"' . $activity->category->name . '\"');\n }\n\n if ($activity->lead_id === null && $activity->contact_id === null) {\n throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');\n }\n\n $payload = [\n 'comments' => $this->generateActivityDescription($activity),\n 'action' => $action->value,\n 'commentingPerson' => [\n 'id' => (int) $this->profile->crm_provider_id,\n 'type' => 'CorporateUser',\n ],\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n 'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),\n ];\n\n if ($activity->lead_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->lead->crm_provider_id,\n 'type' => 'Candidate',\n ];\n }\n\n if ($activity->contact_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->contact->crm_provider_id,\n 'type' => 'ClientContact',\n ];\n }\n\n if ($activity->opportunity_id) {\n $payload['jobOrders'] = [\n 'replaceAll' => [\n (int) $activity->opportunity->crm_provider_id,\n ],\n ];\n }\n\n $bhActivity = $this->client->put('entity/Note', $payload);\n\n $activity->crm_provider_id = $bhActivity['changedEntityId'];\n $activity->save();\n\n return $activity;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = '';\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: %s</span></p>',\n $activity->to->phone_number,\n );\n }\n $description .= '<p></p>';\n }\n\n if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: %s</span></p>',\n $activity->from->phone_number,\n );\n $description .= '<p></p>';\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span>'\n . '</p>';\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span>'\n . '</p>';\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= sprintf(\n '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . '<a href=\"%s\" target=\"_blank\">'\n . 'Review in Jiminny'\n . '</a>'\n . '️</span>'\n . '</p>',\n $playbackUrl,\n );\n }\n\n if ($activity->isTypeConference()) {\n $description .= '<p><strong>Attendees</strong></p><ul>';\n\n // Only include participants that joined.\n $participants = $activity->participants()->ghost(false)->whereNotNull('enter_time')->get();\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->name) {\n $attendee .= $participant->name;\n if ($participant->phone_number) {\n $attendee .= ' (' . $participant->phone_number . ')';\n } elseif ($participant->email) {\n $attendee .= ' (' . $participant->email . ')';\n }\n } else {\n $attendee .= $participant->phone_number;\n }\n\n if ($participant->is_ghost) {\n $attendee .= ' <strong>coach</coach>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $description .= $attendee . '</li>';\n }\n $description .= '</ul>';\n }\n\n if (count($activity->notes) > 0) {\n $description .= '<p><strong>Notes</strong></p>';\n\n foreach ($activity->notes as $note) {\n $time = ($note->time > 3600) ? gmdate('H:i:s', $note->time) : gmdate('i:s', $note->time);\n $description .= '<p>' . $time . ' ' . $note->note . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n if ($activity->summary) {\n $description .= '<p><strong>Summary</strong></p><p>' . $activity->summary . '</p><p></p>';\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n // Use Rich-text formatting.\n $description = sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>%s</strong></span></p>',\n $activity->title,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->description,\n );\n\n break;\n }\n\n return $description;\n }\n\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // Not yet required by current customers.\n return null;\n }\n\n public function updateStage($crmObject, Stage $stage): void\n {\n $objectId = $crmObject->crm_provider_id;\n\n $this->updateRecord($stage->type, $objectId, ['status' => $stage->crm_provider_id]);\n }\n\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $start = 0;\n $payload = [\n 'fields' => 'id,email',\n 'where' => 'isDeleted=false',\n 'count' => 500,\n ];\n\n $payload['start'] = $start;\n $profiles = $this->client->get('query/CorporateUser', $payload);\n\n foreach ($profiles['data'] as $profile) {\n if (empty($profile['email'])) {\n continue;\n }\n\n $user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);\n\n // Only import profiles for users we have locally.\n if ($user) {\n $profile = $user->crmProfile()->updateOrCreate([\n 'crm_configuration_id' => $this->config->id,\n 'crm_provider_id' => $profile['id'],\n ]);\n\n if ($userToSearch && $userToSearch->id === $user->id) {\n return $profile;\n }\n }\n }\n\n return null;\n }\n\n protected function convertCrmData(array $entities, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n $mappedEntities = [];\n foreach ($entities as $entity) {\n if (in_array($entity['entityType'], [self::ENTITY_LEAD, self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n $mappedEntities[] = $entity;\n }\n }\n\n // If there is only one match, sync the data and return the object(s).\n if (count($mappedEntities) === 1) {\n $entity = $mappedEntities[0];\n\n if ($entity['entityType'] === self::ENTITY_LEAD) {\n $lead = $this->syncLead($entity['entityId']);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } elseif (in_array($entity['entityType'], [self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n if ($entity['entityType'] === self::ENTITY_CONTACT) {\n $contact = $this->syncContact($entity['entityId']);\n $account = $contact->account;\n } else {\n $account = $this->syncAccount($entity['entityId']);\n }\n\n if ($contact?->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $bhOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact?->crm_provider_id,\n $userId,\n );\n\n // Take the first opportunity, which will be ordered as priority based on their settings.\n if (! empty($bhOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($bhOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n } catch (Exception) {\n // Nothing to see here.\n }\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n // There doesn't appear to be a way to deeplink to anything on https://app.bullhornstaffing.com.\n return null;\n }\n\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $this->client->post('entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId, $data);\n }\n\n public function getRecord(string $objectType, string $objectId, array $fields = ['id']): array\n {\n return $this->client->get(\n url: 'entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId,\n data: ['fields' => $this->getFieldsAsString($fields)],\n );\n }\n\n private function convertObjectTypeToResource(string $objectType)\n {\n switch ($objectType) {\n case FieldData::OBJECT_OPPORTUNITY:\n return self::ENTITY_OPPORTUNITY;\n\n case FieldData::OBJECT_CONTACT:\n return self::ENTITY_CONTACT;\n\n case FieldData::OBJECT_LEAD:\n return self::ENTITY_LEAD;\n\n case FieldData::OBJECT_ACCOUNT:\n return self::ENTITY_ACCOUNT;\n\n case FieldData::OBJECT_TASK:\n return self::ENTITY_ACTIVITY;\n\n default:\n throw new \\UnexpectedValueException('Unsupported object type \"' . $objectType . '\"');\n }\n }\n\n private function convertResourceToObjectType(string $resource): string\n {\n switch ($resource) {\n case self::ENTITY_OPPORTUNITY:\n return FieldData::OBJECT_OPPORTUNITY;\n\n case self::ENTITY_CONTACT:\n return FieldData::OBJECT_CONTACT;\n\n case self::ENTITY_LEAD:\n return FieldData::OBJECT_LEAD;\n\n case self::ENTITY_ACCOUNT:\n return FieldData::OBJECT_ACCOUNT;\n\n case self::ENTITY_ACTIVITY:\n return FieldData::OBJECT_TASK;\n\n default:\n throw new \\UnexpectedValueException('Unsupported resource \"' . $resource . '\"');\n }\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n // We need to know when it started to determine when to look for related activity.\n if ($activity->hasActualStartTime() === false) {\n return null;\n }\n\n try {\n $bhNote = $this->fetchRelatedActivity($activity);\n if (empty($bhNote)) {\n $this->logger->info('[Bullhorn] No related activity found', [\n 'activity' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $activityType = $this->getPlaybookCategory($this->getPlaybook($activity->user), $bhNote['action']);\n $comments = $bhNote['comments'] . '<br />//<br />' . $this->generateActivityDescription($activity);\n // Now update the Note to contain our data.\n $payload = [\n 'comments' => $comments,\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n ];\n\n $this->logger->info('[Bullhorn] updating related activity', [\n 'activity' => $activity->getUuid(),\n 'activityType' => $activityType->id ?? null,\n ]);\n\n $this->client->post('entity/Note/' . $bhNote['id'], $payload);\n\n $playbookCategoryId = null;\n if ($activity->getCategory() !== null) {\n $playbookCategoryId = $activity->getCategory()->getId();\n }\n\n // Update our activity to reflect the remote data.\n $activity->update([\n 'crm_provider_id' => $bhNote['id'],\n 'summary' => $bhNote['comments'],\n 'playbook_category_id' => $activityType->id ?? $playbookCategoryId,\n ]);\n\n return $activity;\n } catch (\\Exception $exception) {\n \\Sentry::captureException($exception);\n\n throw $exception;\n }\n }\n\n /**\n * Returns the most recently modified note within time range (if any).\n *\n * @return array A Note record from Bullhorn.\n */\n public function fetchRelatedActivity(Activity $activity): array\n {\n $from = $activity->hasScheduledStartTime()\n ? $activity->getScheduledStartTime()\n : $activity->getActualStartTime();\n $to = $activity->hasActualEndTime()\n ? $activity->getActualEndTime()?->addMinutes(15)\n : $from?->clone()->addMinutes(15);\n\n $filterStatements = [\n 'isDeleted: false',\n '*:* -externalID:[* TO *]', // externalID should be null e.g. we did not already relate it.\n sprintf('commentingPerson: %d', (int) $this->profile->crm_provider_id),\n ];\n\n /**\n * @XXX: Bullhorn does not specify the time zone in their docs. I've found a forum thread in which someone from\n * staff asserts it's UTC, however in my field test I've found it to be GMT-0300 (USA east coast).\n * To make the code immune to such glitches we will add 24h to start/end boundaries and will filter out\n * any excess items in code\n */\n $filterStatements[] = sprintf(\n 'dateLastModified:[%s TO %s]',\n $from?->clone()->subHours(24)->format('YmdHis'),\n $to->clone()->addHours(24)->format('YmdHis'),\n );\n\n if ($activity->lead_id) {\n $filterStatements[] = sprintf('candidateUserID: %d', (int) $activity->lead->crm_provider_id);\n }\n\n if ($activity->contact_id) {\n $filterStatements[] = sprintf('clientContactUserID: %d', (int) $activity->contact->crm_provider_id);\n }\n\n // if there is no contact or lead associated to the activity exit\n if ($activity->contact_id === null && $activity->lead_id === null) {\n return [];\n }\n\n $params = [\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => implode(' AND ', $filterStatements),\n 'sort' => '-dateLastModified',\n ];\n\n $bhNotes = $this->client->get('search/Note', $params);\n\n $startStamp = $from?->getTimestamp() * 1000;\n $endStamp = $to->getTimestamp() * 1000;\n\n $filteredNotes = array_values(\n array_filter(\n $bhNotes['data'],\n static fn (array $bhNote): bool\n => $bhNote['dateLastModified'] >= $startStamp && $startStamp <= $endStamp,\n ),\n );\n\n return ! empty($filteredNotes) ? array_shift($filteredNotes) : [];\n }\n\n /**\n * Select how to create the date out of the Bullhorn payload.\n * Do not allow dates beyond 9999-12-31 (max mysql DATE)\n */\n private function filterOutOfBoundDates(string $rawDateCandidate): ?Carbon\n {\n if (strlen($rawDateCandidate) > 12) {\n // A unix timestamp represented with more than 12 digits i\n // s definitely including milliseconds\n $dateFormatted = Carbon::createFromTimestampMs($rawDateCandidate);\n } else {\n $dateFormatted = Carbon::createFromTimestamp($rawDateCandidate);\n }\n\n $minDate = Carbon::createFromFormat('Y-m-d', '2000-01-01');\n if ($dateFormatted->lt($minDate)) {\n return null;\n }\n\n $maxDate = Carbon::createFromFormat('Y-m-d', '9999-12-31');\n if ($dateFormatted->gt($maxDate)) {\n $this->logger->warning('[Bullhorn] An out of bound date is provided', [\n 'date' => $dateFormatted,\n 'rawDate' => $rawDateCandidate,\n ]);\n\n return $maxDate;\n }\n\n return $dateFormatted;\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n $note = $this->getRecord('Note', $crmProviderId, ['id', 'isDeleted']);\n\n return ! empty($note) && ($note['isDeleted'] ?? false) === false;\n } catch (HttpNotFoundException|HttpBadRequestException) {\n // Note not found in CRM - this is expected and permanent\n $this->logger->info('[Bullhorn] Note not found during verification', [\n 'note_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false}]...
|
-3734033779188788614
|
-3409575825370887490
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
73
3
11
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Bullhorn;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\Provider\BullhornInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\ApplicationException;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\DomainException;
use Jiminny\Exceptions\HttpBadRequestException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\ServiceUnavailableException;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\UserRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
use Ramsey\Uuid\Uuid;
class BullhornService extends BaseService implements
BullhornInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const string ENTITY_LEAD = 'Candidate';
private const string ENTITY_OPPORTUNITY = 'JobOrder';
private const string ENTITY_ACCOUNT = 'ClientCorporation';
private const string ENTITY_CONTACT = 'ClientContact';
private const string ENTITY_ACTIVITY = 'Note';
private const array OPPORTUNITY_FIELDS = [
'id',
'owner',
'status',
'title',
'salary',
'salaryUnit',
'payRate',
'isOpen',
'employmentType',
'dateClosed',
'startDate',
'dateLastModified',
'dateAdded',
'clientCorporation',
'correlatedCustomText10', // currency
];
private const array TASK_FIELDS = [
'id',
'comments',
'dateAdded',
'dateLastModified',
'externalID',
'isDeleted',
'corporateUsers',
'clientContacts',
'commentingPerson',
'candidates',
'jobOrder',
'minutesSpent',
'action',
];
private const array LEAD_FIELDS = [
'id',
'name',
'owner',
'occupation',
'companyName',
'companyURL',
'mobile',
'phone',
'phone2',
'phone3',
'workPhone',
'status',
'address',
'dateAdded',
'dateLastModified',
];
private const array CONTACT_FIELDS = [
'id',
'name',
'occupation',
'mobile',
'phone',
'phone2',
'phone3',
'address',
'clientCorporation',
'dateAdded',
'owner',
];
private const array ACCOUNT_FIELDS = [
'id',
'name',
'phone',
'industryList',
'address',
'companyURL',
'dateAdded',
];
public function __construct(
BullhornClientInterface $client,
private readonly UserRepository $userRepository,
private readonly ProspectPhotoPathService $prospectPhotoPathService
) {
parent::__construct();
$this->client = $client;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);
}
public function getDisplayName(): string
{
return 'Bullhorn';
}
public function createTranscriptNotes(Activity $activity): void
{
// Not done until a customer requests it.
}
public function syncProfileFields(): void
{
$fieldTypes = [
'lead',
'account',
'contact',
'opportunity',
'task',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))
);
if (! empty($changedFields)) {
$fields = implode(',', $newFields);
Log::debug(
sprintf(
'%s fields changed from %s to: %s',
ucfirst($fieldType),
$this->profile->{$fieldType . '_fields'},
$fields,
),
);
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (\Exception $exception) {
\Log::error('No access to ' . $fieldType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
$this->profile->save();
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
//parent::OBJECT_ACCOUNT,
//parent::OBJECT_CONTACT,
//parent::OBJECT_OPPORTUNITY,
//parent::OBJECT_LEAD,
];
}
protected function getFields(string $crmObject): array
{
$fields = [];
foreach ($this->getObjectFields($crmObject) as $row) {
$fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];
}
return $fields;
}
private function getObjectFields(string $objectType): array
{
$entityType = $this->convertObjectTypeToResource($objectType);
return Cache::remember(
key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,
ttl: 60 * 60,
callback: function () use ($entityType) {
$entity = $this->client->get('meta/' . $entityType, [
'fields' => '*',
]);
return $entity['fields'];
},
);
}
public function getDefaultFields(string $activityType): array
{
$fields = [];
$defaultFields = FieldDefinitions::defaultFields();
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
return $fields;
}
public function getDefaultActivityField(string $activityType): Field
{
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'action',
'object_type' => $activityType,
])->first();
return $activityField;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
// We are not yet supporting follow-ups for this system.
return [];
}
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return $fieldValue;
}
public function syncField(Field $field): void
{
$resource = $this->convertObjectTypeToResource($field->object_type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => $field->crm_provider_id,
'meta' => 'full',
]);
$bhField = $entity['fields'][0];
$isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);
$description = null;
if (empty($bhField['description']) === false) {
$description = mb_strimwidth($bhField['description'], 0, 191);
}
$label = 'Unknown';
if (empty($bhField['label']) === false) {
$label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);
}
$field->length = $bhField['maxLength'] ?? null;
$field->is_mandatory = $isMandatory;
$field->description = $description;
$field->label = $label;
$field->type = $this->convertFieldType(
$bhField['dataType'] ?? null,
$bhField['dataSpecialization'] ?? null,
$bhField['inputType'] ?? null
);
$field->save();
if (empty($bhField['options']) === false) {
$values = [];
// Import all values.
foreach ($bhField['options'] as $i => $option) {
$values[] = [
'value' => $option['value'],
'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),
'sequence' => $i,
];
}
// Take the existing set of field values.
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
// For all current values, upsert the field.
$field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
$key = array_search($value['value'], $fieldsToPurge, false);
if ($key !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
}
}
public function importPicklistValues(Field $field): array
{
// Taken care of in syncField.
return [];
}
private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string
{
if ($type === null) {
return Field::TYPE_UNSUPPORTED;
}
$type = strtolower($type);
$specialization = strtolower($specialization);
$inputType = strtolower($inputType);
switch ($type) {
case 'boolean':
return Field::TYPE_BOOLEAN;
case 'integer':
switch ($specialization) {
case 'integer':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'bigdecimal':
switch ($specialization) {
case 'money':
return Field::TYPE_CURRENCY;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'double':
switch ($specialization) {
case 'float':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'timestamp':
switch ($specialization) {
case 'date':
return Field::TYPE_DATE;
case 'time':
return Field::TYPE_TIME;
case 'datetime':
return Field::TYPE_DATETIME;
default:
return Field::TYPE_DATE;
}
// no break
case 'string':
switch ($inputType) {
case 'textarea':
return Field::TYPE_TEXTAREA;
case 'select':
return Field::TYPE_PICKLIST;
default:
return Field::TYPE_TEXT;
}
// no break
default:
// This is not actually a supported field.
return Field::TYPE_UNSUPPORTED;
}
}
private function importContact($crmData): Contact
{
$account = $mobilePhone = $phone = $email = null;
if (empty($crmData['clientCorporation']) === false) {
$account = $this->team
->accounts()
->where('crm_provider_id', $crmData['clientCorporation']['id'])
->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
}
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => $crmData['name'],
'email' => $email,
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'title' => $crmData['occupation'],
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Contact::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importOpportunity($crmData): ?Opportunity
{
if ($crmData['clientCorporation']['id']) {
$account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
} else {
// If there is nothing to associate this with, don't import it.
return null;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$stage = $this->config->stages()
->where('crm_provider_id', $crmData['status'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);
}
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => mb_strimwidth($crmData['title'], 0, 128),
'value' => $crmData['salary'] ?? $crmData['payRate'],
'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),
'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),
'is_closed' => $crmData['isOpen'] !== true,
'is_won' => strtolower($crmData['status']) === 'placed',
'stage_id' => $stage->id,
'record_type_id' => null,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importAccount($crmData): Account
{
$countryCode = $domain = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$name = $crmData['name'] ?? 'Unknown';
if ($crmData['companyURL'] !== null) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$data = [
'team_id' => $this->team->id,
'user_id' => null,
'owner_id' => null,
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Account::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'country_code' => $countryCode,
'domain' => $domain,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importLead($crmData): ?Lead
{
// Get the current stage.
$stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);
}
// If we have no way of importing this, just return null :(
if ($stage === null) {
return null;
}
$countryCode = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$mobilePhone = $phone = $email = null;
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$company = 'Unknown';
if (empty($crmData['companyName']) === false) {
$companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];
$company = mb_strimwidth($companyName, 0, 191);
}
$domain = null;
if (empty($crmData['companyURL']) === false) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'company' => $company,
'domain' => $domain,
'name' => mb_strimwidth($crmData['name'], 0, 191),
'title' => mb_strimwidth($crmData['occupation'], 0, 128),
'email' => mb_strimwidth($email, 0, 80),
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Lead::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'stage_id' => $stage->id,
'country_code' => $countryCode,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
/**
* @throws ApplicationException
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhContacts = $this->client->get('search/ClientContact', $params);
foreach ($bhContacts['data'] as $bhContact) {
// Only sync if previously imported.
if ($this->hasContact($bhContact['id'])) {
$this->importContact($bhContact);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategies = $strategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
$total = 0;
$count = 0;
$offset = 0;
try {
$bhOpportunities = [];
foreach ($strategies as $syncStrategy) {
$opportunitiesData = $syncStrategy->fetchOpportunities($parameters);
$total = (int) ($opportunitiesData['total'] ?? 0);
$count = (int) ($opportunitiesData['count'] ?? 0);
$offset = (int) ($opportunitiesData['start'] ?? 0);
$bhOpportunities[] = $opportunitiesData['data'] ?? [];
}
$bhOpportunities = array_merge(...$bhOpportunities);
foreach ($bhOpportunities as $bhOpportunity) {
$this->importOpportunity($bhOpportunity);
$syncCount++;
}
} catch (\Exception $exception) {
$this->logger->info('Failed to sync opportunities', [
'params' => $parameters,
'exception' => $exception->getMessage(),
]);
}
// only log if there are one sync strategy
if (count($strategies) === 1 && $total > $count + $offset) {
$this->logger->info('[Bullhorn] Sync Opportunities - count warning', [
'team_id' => $this->team->getId(),
'total' => $total,
'count' => $count,
'offset' => $offset,
]);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhAccounts = $this->client->get('search/ClientCorporation', $params);
foreach ($bhAccounts['data'] as $bhAccount) {
// Only sync if previously imported.
if ($this->hasAccount($bhAccount['id'])) {
$this->importAccount($bhAccount);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhLeads = $this->client->get('search/Candidate', $params);
if ($bhLeads === null) {
return $syncCount;
}
foreach ($bhLeads['data'] as $bhLead) {
// Only sync if previously imported.
if ($this->hasLead($bhLead['id'])) {
$this->importLead($bhLead);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncContact(string $crmId): ?Contact
{
try {
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importContact($data['data']);
}
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategy = $strategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
try {
$data = $strategy->fetchOpportunities(['crm_id' => $crmId]);
} catch (HttpNotFoundException $exception) {
$this->logger->info('[Bullhorn] Opportunity not found', [
'crm_id' => $crmId,
'reason' => $exception->getMessage(),
]);
}
return $this->importOpportunity($data['data'] ?? []);
}
public function syncAccount(string $crmId): ?Account
{
try {
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importAccount($data['data']);
}
public function syncLead(string $crmId): ?Lead
{
try {
$data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importLead($data['data']);
}
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$missingStage = null;
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
foreach ($types as $type) {
$resource = $this->convertObjectTypeToResource($type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => 'status',
'meta' => 'full',
]);
$missingStage = null;
if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {
throw new \UnexpectedValueException('Invalid response from Bullhorn API');
}
// Upsert all stages for the team.
foreach ($entity['fields'][0]['options'] as $i => $option) {
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $option['value'],
'type' => $type,
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($option['value'], 0, 50),
'label' => mb_strimwidth($option['label'], 0, 191),
'sequence' => $i,
'is_selectable' => 1,
]);
if ($missingStageName && $missingStageName === $option['value']) {
$missingStage = $stage;
}
}
if ($missingStageName && $missingStage === null) {
// If they requested a stage that still doesn't exist, it must be inactive so lazy create it.
$missingStage = $this->config->stages()->create([
'team_id' => $this->team->id,
'crm_provider_id' => Uuid::uuid4(),
'name' => mb_strimwidth($missingStageName, 0, 50),
'label' => mb_strimwidth($missingStageName, 0, 191),
'type' => $type,
'sequence' => 0,
'is_selectable' => 0,
]);
}
}
return $missingStage;
}
public function syncOrganization(): void
{
// There appears to be nothing we can sync/map to.
}
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$data = \Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {
$result = [];
try {
$objects = $this->client->get('find', [
'query' => $name,
'meta' => 'basic',
'countPerEntity' => $count,
]);
} catch (\GuzzleHttp\Exception\ServerException $exception) {
throw new ServiceUnavailableException($exception->getMessage());
}
foreach ($objects['data'] as $object) {
try {
$prospectType = $this->convertResourceToObjectType($object['entityType']);
} catch (\UnexpectedValueException $exception) {
// We don't support this, so skip it.
continue;
}
$record = [
'crmId' => $object['entityId'],
'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),
'prospectType' => $prospectType,
'phoneNumbers' => [],
];
// Unfortunately we need to go and query each entity itself to get the data we need.
switch ($object['entityType']) {
case self::ENTITY_ACCOUNT:
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['industry'] = $entity['industryList'];
if (empty($entity['phone']) === false) {
$record['phoneNumbers'][] = [
'number' => $entity['phone'],
'nationalFormat' => phone_national(null, $entity['phone']),
'type' => 'phone',
];
}
break;
case self::ENTITY_CONTACT:
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
case self::ENTITY_LEAD:
$bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);
$entity = $bhData['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['companyName'];
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
default:
// We are not interested in this entity type so skip it.
continue 2;
}
$result[] = $record;
}
return $result;
});
return $data;
}
public function getClient(): BullhornClientInterface
{
return $this->client;
}
private function getFieldsAsString(array $fields)
{
return implode(', ', $fields);
}
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),
];
$onlyOpen = true;
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort'] = '-dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort'] = '+dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
$onlyOpen = false;
}
if ($onlyOpen) {
$where .= ' AND isOpen: true';
}
$params['query'] = $where;
$bhOpportunities = $this->client->get('search/JobOrder', $params);
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
foreach ($bhOpportunities['data'] as $bhOpportunity) {
$stage = $this->config
->stages()
->where('crm_provider_id', $bhOpportunity['status'])
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);
}
$record = [
'crmId' => $bhOpportunity['id'],
'name' => $bhOpportunity['title'],
'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),
'won' => strtolower($bhOpportunity['status']) === 'placed',
'closed' => $bhOpportunity['isOpen'] !== true,
'stage' => [
'id' => $stage->id_string,
'name' => $stage->name,
],
'recordType' => [],
];
if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = [];
// For now it has not been agreed on how to implement this e.g. appointments or tasks?
return [];
if ($objectType === 'account' && $opportunityId === null) {
// You cannot attach tasks to only accounts.
return [];
}
// Query should default to any open task.
$where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;
// If we are also going to check on a specific job order, set that up.
if ($opportunityId) {
$where .= ' OR JobOrder: ' . (int) $opportunityId;
}
$where .= ')';
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::TASK_FIELDS),
'query' => $where,
];
$bhTasks = $this->client->get('search/Task', $params);
foreach ($bhTasks['data'] as $bhTask) {
$data[] = [
'crmId' => $bhTask['id'],
'subject' => $bhTask['subject'],
'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),
'type' => null,
];
}
return $data;
}
/**
* @url [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] CrmException
* @throws DomainException
*/
private function buildNotePayload(Activity $activity): Activity
{
if ($activity->hasActivityType() === false) {
throw new DomainException('[Bullhorn] No activity type assigned');
}
$action = $this->getCrmType($activity->getActivityType());
if ($action === null) {
throw new DomainException('[Bullhorn] No mapped CRM type for "' . $activity->category->name . '"');
}
if ($activity->lead_id === null && $activity->contact_id === null) {
throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');
}
$payload = [
'comments' => $this->generateActivityDescription($activity),
'action' => $action->value,
'commentingPerson' => [
'id' => (int) $this->profile->crm_provider_id,
'type' => 'CorporateUser',
],
'externalID' => $activity->id_string,
'minutesSpent' => $activity->duration,
'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),
];
if ($activity->lead_id) {
$payload['personReference'] = [
'id' => (int) $activity->lead->crm_provider_id,
'type' => 'Candidate',
];
}
if ($activity->contact_id) {
$payload['personReference'] = [
'id' => (int) $activity->contact->crm_provider_id,
'type' => 'ClientContact',
];
}
if ($activity->opportunity_id) {
$payload['jobOrders'] = [
'replaceAll' => [
(int) $activity->opportunity->crm_provider_id,
],
];
}
$bhActivity = $this->client->put('entity/Note', $payload);
$activity->crm_provider_id = $bhActivity['changedEntityId'];
$activity->save();
return $activity;
}
private function generateActivityDescription(Activity $activity): string
{
$description = '';
switch ($activity->type) {
case Activity::TYPE_SOFTPHONE:
case Activity::TYPE_SOFTPHONE_INBOUND:
case Activity::TYPE_CONFERENCE:
if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
// Dialer calls have no native field for the subject.
if ($activity->title) {
$description .= sprintf(
'<p><span style="font-size: 16px; line-height: 19.2px;">%s</span></p>',
$activity->title,
);
}
// Conference meetings log duration into a distinct field, so log this in the main text.
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Call Duration: %s</span></p>',
$activity->duration_for_humans,
);
// Tell them which number was dialed.
if ($activity->to) {
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Dialed: %s</span></p>',
$activity->to->phone_number,
);
}
$description .= '<p></p>';
}
if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45387
|
1626
|
19
|
2026-05-14T14:33:55.707307+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769235707_m2.jpg...
|
PhpStorm
|
faVsco.js – BullhornService.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pm~ (Q SearchDate ModifiedYesterdav at 13.3Yesterday at 13:37Yesterday at 13.30Yesterday at 13:35resterday at 15.34Yesterdav at 13:34Yesterday at 13:33Yesterday at 13.32Yesterday at 13:32resterday at 15.3Yesterdav at 13:30Yesterday at 13:30Yesterday at 13:29Yesterday at 13:29Yesterday at 13:28resterday at 13-21Yesterdav at 13:27Yesterday at 13:26Yesterday at 13:26Yesterday at 13:25Yesterday at 13.24Yesterdav at 13:22Yesterday at 13:22resterady al 15.clYesterday at 13:20Yesterday at 13.19Yecterdav at 12:10Yesterday at 13:18Yesterday at 13.10Yesterdav at 13:17Yesterday at 13:17Yesterday at 13:16Yacterdav at 12:15Yesterday at 13.14Yecterdav at 12:14Yesterday at 13:13Yesterday at 13:12Yesterday at 13:12Yesterday at 13.11Yecterdav at 12:10Yesterday at 13:10Yesterdav at 13:0962 K:MPEG-4 movie71 KBMPEG-4 movie23 KBMPEG-4 movieMPEG-4 movie13 KE16 KB17 KBMPE0"4 movie29 K:6 KBMPEG-4 movie12 KBMP2G-4 movieMPEG-4 movie7 KBI8 KB37 KBMPEG"4 movie10 KВIMPEG-4 movie7 KBMPEG-4 movie8 KB9 KB1MPEG-4 movie8 KBMPEG-4 movie72 KB14 KBMPEG-4 movie13 KEMPEG-4 movie9 KB MPEG-4 movie18 KB12 KB|MPEG-4 movie10 KBMPEG-4 movie16 KB6KBMPEG-4 movie6KEMPEG-4 movie12 KBMPEG-4 movie23 KBMPEG-4 movie8 K:MPEG-4 movie6 KBMPEG-4 movie11 KBMPEG-4 movie11 KPMPEG-4 movie20 KB34 KB10 K:MPEG-4 movie7KBMPEG-4 movie5 KB11 KBMPEG-4 movieD6KRMDEG-A movia111 KBMPEG-4 movie102 KBMPEG-4 movie88 KBMPEG-A movie59 KB MPEG-4 movie98 KB97 KBGAKPMPEG-4 movieMPEG-4 movie44 KB93 KBMPEG-4 movie78 KPMDEG-A movid50 KBMPEG-4 movie58 KB17 KBMPEG-4 movieAl Notes: OffLeave• 0FavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderLocationsQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zio• Photos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВZIP archivel148 KBZIP archive122 KBXML document111 KBAlfred...ferences94 KBPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.48 GB availabld• Inu 14 May 1/•33.02Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
-6348758399068430483
|
NULL
|
click
|
ocr
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pm~ (Q SearchDate ModifiedYesterdav at 13.3Yesterday at 13:37Yesterday at 13.30Yesterday at 13:35resterday at 15.34Yesterdav at 13:34Yesterday at 13:33Yesterday at 13.32Yesterday at 13:32resterday at 15.3Yesterdav at 13:30Yesterday at 13:30Yesterday at 13:29Yesterday at 13:29Yesterday at 13:28resterday at 13-21Yesterdav at 13:27Yesterday at 13:26Yesterday at 13:26Yesterday at 13:25Yesterday at 13.24Yesterdav at 13:22Yesterday at 13:22resterady al 15.clYesterday at 13:20Yesterday at 13.19Yecterdav at 12:10Yesterday at 13:18Yesterday at 13.10Yesterdav at 13:17Yesterday at 13:17Yesterday at 13:16Yacterdav at 12:15Yesterday at 13.14Yecterdav at 12:14Yesterday at 13:13Yesterday at 13:12Yesterday at 13:12Yesterday at 13.11Yecterdav at 12:10Yesterday at 13:10Yesterdav at 13:0962 K:MPEG-4 movie71 KBMPEG-4 movie23 KBMPEG-4 movieMPEG-4 movie13 KE16 KB17 KBMPE0"4 movie29 K:6 KBMPEG-4 movie12 KBMP2G-4 movieMPEG-4 movie7 KBI8 KB37 KBMPEG"4 movie10 KВIMPEG-4 movie7 KBMPEG-4 movie8 KB9 KB1MPEG-4 movie8 KBMPEG-4 movie72 KB14 KBMPEG-4 movie13 KEMPEG-4 movie9 KB MPEG-4 movie18 KB12 KB|MPEG-4 movie10 KBMPEG-4 movie16 KB6KBMPEG-4 movie6KEMPEG-4 movie12 KBMPEG-4 movie23 KBMPEG-4 movie8 K:MPEG-4 movie6 KBMPEG-4 movie11 KBMPEG-4 movie11 KPMPEG-4 movie20 KB34 KB10 K:MPEG-4 movie7KBMPEG-4 movie5 KB11 KBMPEG-4 movieD6KRMDEG-A movia111 KBMPEG-4 movie102 KBMPEG-4 movie88 KBMPEG-A movie59 KB MPEG-4 movie98 KB97 KBGAKPMPEG-4 movieMPEG-4 movie44 KB93 KBMPEG-4 movie78 KPMDEG-A movid50 KBMPEG-4 movie58 KB17 KBMPEG-4 movieAl Notes: OffLeave• 0FavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderLocationsQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zio• Photos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВZIP archivel148 KBZIP archive122 KBXML document111 KBAlfred...ferences94 KBPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.48 GB availabld• Inu 14 May 1/•33.02Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45386
|
1625
|
34
|
2026-05-14T14:33:55.707319+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769235707_m1.jpg...
|
PhpStorm
|
faVsco.js – BullhornService.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit k vlhl100% CHandleHubspotRateLimitTest v8• Thu 14 May 17:33:55* :QProject v© UserAutomatedReportsController.php:=custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.php© BullhornLoginHandler.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php=laravel.log© BullhornLoginHandlerInterfa© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© Salesforce/Service.phpT LogActivityTrait.phpSF [jiminny@localhost]© BullhornService.php© BullhornSessionDecorator.plPipedrive/Service.phpClose/Service.phpCopper/Service.phpBullhornService.php X© PlainTextDecorateActivity.phpA HS_local [jiminny@localho:W© BullhornSessionManager.ph|© ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php= .env.staging4 console [QAI PROD] X18® BullhornSessionManagerinte© FieldDefinitions.phpE.envDetachActivityObject.phpRematchActivityOnCrmObjectDetach.php© MatchActivityCrmData.php© Client.php4 console [PROD]v @ Close> OpportunitySyncStrategy> O Processor> D ProspectSearchStrategy> O Translator© HubspotPaginationService.php© HandleHubspotRateLimit.phpclass BullhornService extends BaseService implementspublic function saveActivity(Activity $activity): Activityreturn sactivity:}A console (EU]© Client.php© CloseException.php© FieldDefinitions.php© FieldValueConverter.php© Service.php A8 A73 X1 X10 ^© StandardFieldMetadata.php/*** Othrows CrmException* Othrows DomainException*/1 usage.id = 33;v Copper1337private function puildNotePayload(Activity $activity): Activity> J Apі|1338> D Exception1339> D OpportunitySyncStrategy1340if (Sactivity->hasActivityType() === false) {throw new DomainException( message: '[Bullhorn] No activity type assigned');> D ProspectSearchStrategy1341> @ Traits1342© FieldDefinitions.php1343© FieldValueConverter.php1344Saction = Sthis->getCrmType(Sactivity->getActivityType());if ($action === null) {© Service.php1345> @ CrmObjects1346D DecorateActivity1347© BaseDecorateActivity.php1348DGo jiminny084143 ×4 л215•m_layout_id =2162,1661,66799,66217218219220221=222223:224225226= 227228229230throw new DomainException( message:'[Bullhorn] No mapped CRM type for "' . $activity->category->na2311 232233v234id THEN '(ownhubspot':-= 11512582;© PlainTextDecorateActivity.pl1349if ($activity->lead_id === null && $activity->contact_id === null) {throw new DomainException( message:'[Bullhorn] Cannot save note without candidate or DM');C Dummy1350}-v D Helpers1351T ActivityPlaybookTrait.php1352© Arraylterator.php1353$payload = ['comments'=> $this->generateActivityDescription(Sactivity),# CannantionCtstaTrait nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams1337:22UTF-8Ca 4 spaces...
|
NULL
|
-2345985353863117101
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit k vlhl100% CHandleHubspotRateLimitTest v8• Thu 14 May 17:33:55* :QProject v© UserAutomatedReportsController.php:=custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.php© BullhornLoginHandler.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php=laravel.log© BullhornLoginHandlerInterfa© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© Salesforce/Service.phpT LogActivityTrait.phpSF [jiminny@localhost]© BullhornService.php© BullhornSessionDecorator.plPipedrive/Service.phpClose/Service.phpCopper/Service.phpBullhornService.php X© PlainTextDecorateActivity.phpA HS_local [jiminny@localho:W© BullhornSessionManager.ph|© ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php= .env.staging4 console [QAI PROD] X18® BullhornSessionManagerinte© FieldDefinitions.phpE.envDetachActivityObject.phpRematchActivityOnCrmObjectDetach.php© MatchActivityCrmData.php© Client.php4 console [PROD]v @ Close> OpportunitySyncStrategy> O Processor> D ProspectSearchStrategy> O Translator© HubspotPaginationService.php© HandleHubspotRateLimit.phpclass BullhornService extends BaseService implementspublic function saveActivity(Activity $activity): Activityreturn sactivity:}A console (EU]© Client.php© CloseException.php© FieldDefinitions.php© FieldValueConverter.php© Service.php A8 A73 X1 X10 ^© StandardFieldMetadata.php/*** Othrows CrmException* Othrows DomainException*/1 usage.id = 33;v Copper1337private function puildNotePayload(Activity $activity): Activity> J Apі|1338> D Exception1339> D OpportunitySyncStrategy1340if (Sactivity->hasActivityType() === false) {throw new DomainException( message: '[Bullhorn] No activity type assigned');> D ProspectSearchStrategy1341> @ Traits1342© FieldDefinitions.php1343© FieldValueConverter.php1344Saction = Sthis->getCrmType(Sactivity->getActivityType());if ($action === null) {© Service.php1345> @ CrmObjects1346D DecorateActivity1347© BaseDecorateActivity.php1348DGo jiminny084143 ×4 л215•m_layout_id =2162,1661,66799,66217218219220221=222223:224225226= 227228229230throw new DomainException( message:'[Bullhorn] No mapped CRM type for "' . $activity->category->na2311 232233v234id THEN '(ownhubspot':-= 11512582;© PlainTextDecorateActivity.pl1349if ($activity->lead_id === null && $activity->contact_id === null) {throw new DomainException( message:'[Bullhorn] Cannot save note without candidate or DM');C Dummy1350}-v D Helpers1351T ActivityPlaybookTrait.php1352© Arraylterator.php1353$payload = ['comments'=> $this->generateActivityDescription(Sactivity),# CannantionCtstaTrait nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams1337:22UTF-8Ca 4 spaces...
|
45385
|
NULL
|
NULL
|
NULL
|
|
45385
|
1625
|
33
|
2026-05-14T14:33:52.539527+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769232539_m1.jpg...
|
PhpStorm
|
faVsco.js – BullhornService.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
2
13
3
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Bullhorn;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\Provider\BullhornInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\ApplicationException;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\DomainException;
use Jiminny\Exceptions\HttpBadRequestException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\ServiceUnavailableException;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\UserRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
use Ramsey\Uuid\Uuid;
class BullhornService extends BaseService implements
BullhornInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const string ENTITY_LEAD = 'Candidate';
private const string ENTITY_OPPORTUNITY = 'JobOrder';
private const string ENTITY_ACCOUNT = 'ClientCorporation';
private const string ENTITY_CONTACT = 'ClientContact';
private const string ENTITY_ACTIVITY = 'Note';
private const array OPPORTUNITY_FIELDS = [
'id',
'owner',
'status',
'title',
'salary',
'salaryUnit',
'payRate',
'isOpen',
'employmentType',
'dateClosed',
'startDate',
'dateLastModified',
'dateAdded',
'clientCorporation',
'correlatedCustomText10', // currency
];
private const array TASK_FIELDS = [
'id',
'comments',
'dateAdded',
'dateLastModified',
'externalID',
'isDeleted',
'corporateUsers',
'clientContacts',
'commentingPerson',
'candidates',
'jobOrder',
'minutesSpent',
'action',
];
private const array LEAD_FIELDS = [
'id',
'name',
'owner',
'occupation',
'companyName',
'companyURL',
'mobile',
'phone',
'phone2',
'phone3',
'workPhone',
'status',
'address',
'dateAdded',
'dateLastModified',
];
private const array CONTACT_FIELDS = [
'id',
'name',
'occupation',
'mobile',
'phone',
'phone2',
'phone3',
'address',
'clientCorporation',
'dateAdded',
'owner',
];
private const array ACCOUNT_FIELDS = [
'id',
'name',
'phone',
'industryList',
'address',
'companyURL',
'dateAdded',
];
public function __construct(
BullhornClientInterface $client,
private readonly UserRepository $userRepository,
private readonly ProspectPhotoPathService $prospectPhotoPathService
) {
parent::__construct();
$this->client = $client;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);
}
public function getDisplayName(): string
{
return 'Bullhorn';
}
public function createTranscriptNotes(Activity $activity): void
{
// Not done until a customer requests it.
}
public function syncProfileFields(): void
{
$fieldTypes = [
'lead',
'account',
'contact',
'opportunity',
'task',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))
);
if (! empty($changedFields)) {
$fields = implode(',', $newFields);
Log::debug(
sprintf(
'%s fields changed from %s to: %s',
ucfirst($fieldType),
$this->profile->{$fieldType . '_fields'},
$fields,
),
);
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (\Exception $exception) {
\Log::error('No access to ' . $fieldType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
$this->profile->save();
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
//parent::OBJECT_ACCOUNT,
//parent::OBJECT_CONTACT,
//parent::OBJECT_OPPORTUNITY,
//parent::OBJECT_LEAD,
];
}
protected function getFields(string $crmObject): array
{
$fields = [];
foreach ($this->getObjectFields($crmObject) as $row) {
$fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];
}
return $fields;
}
private function getObjectFields(string $objectType): array
{
$entityType = $this->convertObjectTypeToResource($objectType);
return Cache::remember(
key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,
ttl: 60 * 60,
callback: function () use ($entityType) {
$entity = $this->client->get('meta/' . $entityType, [
'fields' => '*',
]);
return $entity['fields'];
},
);
}
public function getDefaultFields(string $activityType): array
{
$fields = [];
$defaultFields = FieldDefinitions::defaultFields();
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
return $fields;
}
public function getDefaultActivityField(string $activityType): Field
{
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'action',
'object_type' => $activityType,
])->first();
return $activityField;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
// We are not yet supporting follow-ups for this system.
return [];
}
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return $fieldValue;
}
public function syncField(Field $field): void
{
$resource = $this->convertObjectTypeToResource($field->object_type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => $field->crm_provider_id,
'meta' => 'full',
]);
$bhField = $entity['fields'][0];
$isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);
$description = null;
if (empty($bhField['description']) === false) {
$description = mb_strimwidth($bhField['description'], 0, 191);
}
$label = 'Unknown';
if (empty($bhField['label']) === false) {
$label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);
}
$field->length = $bhField['maxLength'] ?? null;
$field->is_mandatory = $isMandatory;
$field->description = $description;
$field->label = $label;
$field->type = $this->convertFieldType(
$bhField['dataType'] ?? null,
$bhField['dataSpecialization'] ?? null,
$bhField['inputType'] ?? null
);
$field->save();
if (empty($bhField['options']) === false) {
$values = [];
// Import all values.
foreach ($bhField['options'] as $i => $option) {
$values[] = [
'value' => $option['value'],
'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),
'sequence' => $i,
];
}
// Take the existing set of field values.
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
// For all current values, upsert the field.
$field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
$key = array_search($value['value'], $fieldsToPurge, false);
if ($key !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
}
}
public function importPicklistValues(Field $field): array
{
// Taken care of in syncField.
return [];
}
private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string
{
if ($type === null) {
return Field::TYPE_UNSUPPORTED;
}
$type = strtolower($type);
$specialization = strtolower($specialization);
$inputType = strtolower($inputType);
switch ($type) {
case 'boolean':
return Field::TYPE_BOOLEAN;
case 'integer':
switch ($specialization) {
case 'integer':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'bigdecimal':
switch ($specialization) {
case 'money':
return Field::TYPE_CURRENCY;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'double':
switch ($specialization) {
case 'float':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'timestamp':
switch ($specialization) {
case 'date':
return Field::TYPE_DATE;
case 'time':
return Field::TYPE_TIME;
case 'datetime':
return Field::TYPE_DATETIME;
default:
return Field::TYPE_DATE;
}
// no break
case 'string':
switch ($inputType) {
case 'textarea':
return Field::TYPE_TEXTAREA;
case 'select':
return Field::TYPE_PICKLIST;
default:
return Field::TYPE_TEXT;
}
// no break
default:
// This is not actually a supported field.
return Field::TYPE_UNSUPPORTED;
}
}
private function importContact($crmData): Contact
{
$account = $mobilePhone = $phone = $email = null;
if (empty($crmData['clientCorporation']) === false) {
$account = $this->team
->accounts()
->where('crm_provider_id', $crmData['clientCorporation']['id'])
->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
}
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => $crmData['name'],
'email' => $email,
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'title' => $crmData['occupation'],
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Contact::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importOpportunity($crmData): ?Opportunity
{
if ($crmData['clientCorporation']['id']) {
$account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
} else {
// If there is nothing to associate this with, don't import it.
return null;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$stage = $this->config->stages()
->where('crm_provider_id', $crmData['status'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);
}
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => mb_strimwidth($crmData['title'], 0, 128),
'value' => $crmData['salary'] ?? $crmData['payRate'],
'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),
'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),
'is_closed' => $crmData['isOpen'] !== true,
'is_won' => strtolower($crmData['status']) === 'placed',
'stage_id' => $stage->id,
'record_type_id' => null,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importAccount($crmData): Account
{
$countryCode = $domain = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$name = $crmData['name'] ?? 'Unknown';
if ($crmData['companyURL'] !== null) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$data = [
'team_id' => $this->team->id,
'user_id' => null,
'owner_id' => null,
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Account::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'country_code' => $countryCode,
'domain' => $domain,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importLead($crmData): ?Lead
{
// Get the current stage.
$stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);
}
// If we have no way of importing this, just return null :(
if ($stage === null) {
return null;
}
$countryCode = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$mobilePhone = $phone = $email = null;
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$company = 'Unknown';
if (empty($crmData['companyName']) === false) {
$companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];
$company = mb_strimwidth($companyName, 0, 191);
}
$domain = null;
if (empty($crmData['companyURL']) === false) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'company' => $company,
'domain' => $domain,
'name' => mb_strimwidth($crmData['name'], 0, 191),
'title' => mb_strimwidth($crmData['occupation'], 0, 128),
'email' => mb_strimwidth($email, 0, 80),
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Lead::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'stage_id' => $stage->id,
'country_code' => $countryCode,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
/**
* @throws ApplicationException
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhContacts = $this->client->get('search/ClientContact', $params);
foreach ($bhContacts['data'] as $bhContact) {
// Only sync if previously imported.
if ($this->hasContact($bhContact['id'])) {
$this->importContact($bhContact);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategies = $strategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
$total = 0;
$count = 0;
$offset = 0;
try {
$bhOpportunities = [];
foreach ($strategies as $syncStrategy) {
$opportunitiesData = $syncStrategy->fetchOpportunities($parameters);
$total = (int) ($opportunitiesData['total'] ?? 0);
$count = (int) ($opportunitiesData['count'] ?? 0);
$offset = (int) ($opportunitiesData['start'] ?? 0);
$bhOpportunities[] = $opportunitiesData['data'] ?? [];
}
$bhOpportunities = array_merge(...$bhOpportunities);
foreach ($bhOpportunities as $bhOpportunity) {
$this->importOpportunity($bhOpportunity);
$syncCount++;
}
} catch (\Exception $exception) {
$this->logger->info('Failed to sync opportunities', [
'params' => $parameters,
'exception' => $exception->getMessage(),
]);
}
// only log if there are one sync strategy
if (count($strategies) === 1 && $total > $count + $offset) {
$this->logger->info('[Bullhorn] Sync Opportunities - count warning', [
'team_id' => $this->team->getId(),
'total' => $total,
'count' => $count,
'offset' => $offset,
]);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhAccounts = $this->client->get('search/ClientCorporation', $params);
foreach ($bhAccounts['data'] as $bhAccount) {
// Only sync if previously imported.
if ($this->hasAccount($bhAccount['id'])) {
$this->importAccount($bhAccount);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhLeads = $this->client->get('search/Candidate', $params);
if ($bhLeads === null) {
return $syncCount;
}
foreach ($bhLeads['data'] as $bhLead) {
// Only sync if previously imported.
if ($this->hasLead($bhLead['id'])) {
$this->importLead($bhLead);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncContact(string $crmId): ?Contact
{
try {
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importContact($data['data']);
}
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategy = $strategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
try {
$data = $strategy->fetchOpportunities(['crm_id' => $crmId]);
} catch (HttpNotFoundException $exception) {
$this->logger->info('[Bullhorn] Opportunity not found', [
'crm_id' => $crmId,
'reason' => $exception->getMessage(),
]);
}
return $this->importOpportunity($data['data'] ?? []);
}
public function syncAccount(string $crmId): ?Account
{
try {
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importAccount($data['data']);
}
public function syncLead(string $crmId): ?Lead
{
try {
$data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importLead($data['data']);
}
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$missingStage = null;
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
foreach ($types as $type) {
$resource = $this->convertObjectTypeToResource($type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => 'status',
'meta' => 'full',
]);
$missingStage = null;
if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {
throw new \UnexpectedValueException('Invalid response from Bullhorn API');
}
// Upsert all stages for the team.
foreach ($entity['fields'][0]['options'] as $i => $option) {
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $option['value'],
'type' => $type,
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($option['value'], 0, 50),
'label' => mb_strimwidth($option['label'], 0, 191),
'sequence' => $i,
'is_selectable' => 1,
]);
if ($missingStageName && $missingStageName === $option['value']) {
$missingStage = $stage;
}
}
if ($missingStageName && $missingStage === null) {
// If they requested a stage that still doesn't exist, it must be inactive so lazy create it.
$missingStage = $this->config->stages()->create([
'team_id' => $this->team->id,
'crm_provider_id' => Uuid::uuid4(),
'name' => mb_strimwidth($missingStageName, 0, 50),
'label' => mb_strimwidth($missingStageName, 0, 191),
'type' => $type,
'sequence' => 0,
'is_selectable' => 0,
]);
}
}
return $missingStage;
}
public function syncOrganization(): void
{
// There appears to be nothing we can sync/map to.
}
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$data = \Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {
$result = [];
try {
$objects = $this->client->get('find', [
'query' => $name,
'meta' => 'basic',
'countPerEntity' => $count,
]);
} catch (\GuzzleHttp\Exception\ServerException $exception) {
throw new ServiceUnavailableException($exception->getMessage());
}
foreach ($objects['data'] as $object) {
try {
$prospectType = $this->convertResourceToObjectType($object['entityType']);
} catch (\UnexpectedValueException $exception) {
// We don't support this, so skip it.
continue;
}
$record = [
'crmId' => $object['entityId'],
'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),
'prospectType' => $prospectType,
'phoneNumbers' => [],
];
// Unfortunately we need to go and query each entity itself to get the data we need.
switch ($object['entityType']) {
case self::ENTITY_ACCOUNT:
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['industry'] = $entity['industryList'];
if (empty($entity['phone']) === false) {
$record['phoneNumbers'][] = [
'number' => $entity['phone'],
'nationalFormat' => phone_national(null, $entity['phone']),
'type' => 'phone',
];
}
break;
case self::ENTITY_CONTACT:
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
case self::ENTITY_LEAD:
$bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);
$entity = $bhData['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['companyName'];
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
default:
// We are not interested in this entity type so skip it.
continue 2;
}
$result[] = $record;
}
return $result;
});
return $data;
}
public function getClient(): BullhornClientInterface
{
return $this->client;
}
private function getFieldsAsString(array $fields)
{
return implode(', ', $fields);
}
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),
];
$onlyOpen = true;
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort'] = '-dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort'] = '+dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
$onlyOpen = false;
}
if ($onlyOpen) {
$where .= ' AND isOpen: true';
}
$params['query'] = $where;
$bhOpportunities = $this->client->get('search/JobOrder', $params);
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
foreach ($bhOpportunities['data'] as $bhOpportunity) {
$stage = $this->config
->stages()
->where('crm_provider_id', $bhOpportunity['status'])
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);
}
$record = [
'crmId' => $bhOpportunity['id'],
'name' => $bhOpportunity['title'],
'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),
'won' => strtolower($bhOpportunity['status']) === 'placed',
'closed' => $bhOpportunity['isOpen'] !== true,
'stage' => [
'id' => $stage->id_string,
'name' => $stage->name,
],
'recordType' => [],
];
if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = [];
// For now it has not been agreed on how to implement this e.g. appointments or tasks?
return [];
if ($objectType === 'account' && $opportunityId === null) {
// You cannot attach tasks to only accounts.
return [];
}
// Query should default to any open task.
$where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;
// If we are also going to check on a specific job order, set that up.
if ($opportunityId) {
$where .= ' OR JobOrder: ' . (int) $opportunityId;
}
$where .= ')';
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::TASK_FIELDS),
'query' => $where,
];
$bhTasks = $this->client->get('search/Task', $params);
foreach ($bhTasks['data'] as $bhTask) {
$data[] = [
'crmId' => $bhTask['id'],
'subject' => $bhTask['subject'],
'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),
'type' => null,
];
}
return $data;
}
/**
* @url [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] CrmException
* @throws DomainException
*/
private function buildNotePayload(Activity $activity): Activity
{
if ($activity->hasActivityType() === false) {
throw new DomainException('[Bullhorn] No activity type assigned');
}
$action = $this->getCrmType($activity->getActivityType());
if ($action === null) {
throw new DomainException('[Bullhorn] No mapped CRM type for "' . $activity->category->name . '"');
}
if ($activity->lead_id === null && $activity->contact_id === null) {
throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');
}
$payload = [
'comments' => $this->generateActivityDescription($activity),
'action' => $action->value,
'commentingPerson' => [
'id' => (int) $this->profile->crm_provider_id,
'type' => 'CorporateUser',
],
'externalID' => $activity->id_string,
'minutesSpent' => $activity->duration,
'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),
];
if ($activity->lead_id) {
$payload['personReference'] = [
'id' => (int) $activity->lead->crm_provider_id,
'type' => 'Candidate',
];
}
if ($activity->contact_id) {
$payload['personReference'] = [
'id' => (int) $activity->contact->crm_provider_id,
'type' => 'ClientContact',
];
}
if ($activity->opportunity_id) {
$payload['jobOrders'] = [
'replaceAll' => [
(int) $activity->opportunity->crm_provider_id,
],
];
}
$bhActivity = $this->client->put('entity/Note', $payload);
$activity->crm_provider_id = $bhActivity['changedEntityId'];
$activity->save();
return $activity;
}
private function generateActivityDescription(Activity $activity): string
{
$description = '';
switch ($activity->type) {
case Activity::TYPE_SOFTPHONE:
case Activity::TYPE_SOFTPHONE_INBOUND:
case Activity::TYPE_CONFERENCE:
if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
// Dialer calls have no native field for the subject.
if ($activity->title) {
$description .= sprintf(
'<p><span style="font-size: 16px; line-height: 19.2px;">%s</span></p>',
$activity->title,
);
}
// Conference meetings log duration into a distinct field, so log this in the main text.
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Call Duration: %s</span></p>',
$activity->duration_for_humans,
);
// Tell them which number was dialed.
if ($activity->to) {
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Dialed: %s</span></p>',
$activity->to->phone_number,
);
}
$description .= '<p></p>';
}
if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.6645833,"top":0.027777778,"width":0.15902779,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.82361114,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.8472222,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.87083334,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.9291667,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9527778,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9763889,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"2","depth":4,"bounds":{"left":0.75625,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"13","depth":4,"bounds":{"left":0.77708334,"top":0.3122222,"width":0.02013889,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.80138886,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.8215278,"top":0.31,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.8368056,"top":0.31,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Bullhorn;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\BullhornInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\ApplicationException;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\DomainException;\nuse Jiminny\\Exceptions\\HttpBadRequestException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\ServiceUnavailableException;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\UserRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\nuse Ramsey\\Uuid\\Uuid;\n\nclass BullhornService extends BaseService implements\n BullhornInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const string ENTITY_LEAD = 'Candidate';\n private const string ENTITY_OPPORTUNITY = 'JobOrder';\n private const string ENTITY_ACCOUNT = 'ClientCorporation';\n private const string ENTITY_CONTACT = 'ClientContact';\n private const string ENTITY_ACTIVITY = 'Note';\n\n private const array OPPORTUNITY_FIELDS = [\n 'id',\n 'owner',\n 'status',\n 'title',\n 'salary',\n 'salaryUnit',\n 'payRate',\n 'isOpen',\n 'employmentType',\n 'dateClosed',\n 'startDate',\n 'dateLastModified',\n 'dateAdded',\n 'clientCorporation',\n 'correlatedCustomText10', // currency\n ];\n\n private const array TASK_FIELDS = [\n 'id',\n 'comments',\n 'dateAdded',\n 'dateLastModified',\n 'externalID',\n 'isDeleted',\n 'corporateUsers',\n 'clientContacts',\n 'commentingPerson',\n 'candidates',\n 'jobOrder',\n 'minutesSpent',\n 'action',\n ];\n\n private const array LEAD_FIELDS = [\n 'id',\n 'name',\n 'owner',\n 'occupation',\n 'companyName',\n 'companyURL',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'workPhone',\n 'status',\n 'address',\n 'dateAdded',\n 'dateLastModified',\n ];\n\n private const array CONTACT_FIELDS = [\n 'id',\n 'name',\n 'occupation',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'address',\n 'clientCorporation',\n 'dateAdded',\n 'owner',\n ];\n\n private const array ACCOUNT_FIELDS = [\n 'id',\n 'name',\n 'phone',\n 'industryList',\n 'address',\n 'companyURL',\n 'dateAdded',\n ];\n\n public function __construct(\n BullhornClientInterface $client,\n private readonly UserRepository $userRepository,\n private readonly ProspectPhotoPathService $prospectPhotoPathService\n ) {\n parent::__construct();\n\n $this->client = $client;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);\n }\n\n public function getDisplayName(): string\n {\n return 'Bullhorn';\n }\n\n public function createTranscriptNotes(Activity $activity): void\n {\n // Not done until a customer requests it.\n }\n\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n 'task',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))\n );\n\n if (! empty($changedFields)) {\n $fields = implode(',', $newFields);\n Log::debug(\n sprintf(\n '%s fields changed from %s to: %s',\n ucfirst($fieldType),\n $this->profile->{$fieldType . '_fields'},\n $fields,\n ),\n );\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (\\Exception $exception) {\n \\Log::error('No access to ' . $fieldType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n //parent::OBJECT_ACCOUNT,\n //parent::OBJECT_CONTACT,\n //parent::OBJECT_OPPORTUNITY,\n //parent::OBJECT_LEAD,\n ];\n }\n\n protected function getFields(string $crmObject): array\n {\n $fields = [];\n foreach ($this->getObjectFields($crmObject) as $row) {\n $fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];\n }\n\n return $fields;\n }\n\n private function getObjectFields(string $objectType): array\n {\n $entityType = $this->convertObjectTypeToResource($objectType);\n\n return Cache::remember(\n key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,\n ttl: 60 * 60,\n callback: function () use ($entityType) {\n $entity = $this->client->get('meta/' . $entityType, [\n 'fields' => '*',\n ]);\n\n return $entity['fields'];\n },\n );\n }\n\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n $defaultFields = FieldDefinitions::defaultFields();\n\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n\n return $fields;\n }\n\n public function getDefaultActivityField(string $activityType): Field\n {\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'action',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n // We are not yet supporting follow-ups for this system.\n return [];\n }\n\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return $fieldValue;\n }\n\n public function syncField(Field $field): void\n {\n $resource = $this->convertObjectTypeToResource($field->object_type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => $field->crm_provider_id,\n 'meta' => 'full',\n ]);\n\n $bhField = $entity['fields'][0];\n\n $isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);\n $description = null;\n if (empty($bhField['description']) === false) {\n $description = mb_strimwidth($bhField['description'], 0, 191);\n }\n\n $label = 'Unknown';\n if (empty($bhField['label']) === false) {\n $label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);\n }\n\n $field->length = $bhField['maxLength'] ?? null;\n $field->is_mandatory = $isMandatory;\n $field->description = $description;\n $field->label = $label;\n $field->type = $this->convertFieldType(\n $bhField['dataType'] ?? null,\n $bhField['dataSpecialization'] ?? null,\n $bhField['inputType'] ?? null\n );\n\n $field->save();\n\n if (empty($bhField['options']) === false) {\n $values = [];\n\n // Import all values.\n foreach ($bhField['options'] as $i => $option) {\n $values[] = [\n 'value' => $option['value'],\n 'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),\n 'sequence' => $i,\n ];\n }\n\n // Take the existing set of field values.\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n // For all current values, upsert the field.\n $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n $key = array_search($value['value'], $fieldsToPurge, false);\n if ($key !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n }\n }\n\n public function importPicklistValues(Field $field): array\n {\n // Taken care of in syncField.\n return [];\n }\n\n private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string\n {\n if ($type === null) {\n return Field::TYPE_UNSUPPORTED;\n }\n\n $type = strtolower($type);\n $specialization = strtolower($specialization);\n $inputType = strtolower($inputType);\n\n switch ($type) {\n case 'boolean':\n return Field::TYPE_BOOLEAN;\n\n case 'integer':\n switch ($specialization) {\n case 'integer':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'bigdecimal':\n switch ($specialization) {\n case 'money':\n return Field::TYPE_CURRENCY;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'double':\n switch ($specialization) {\n case 'float':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'timestamp':\n switch ($specialization) {\n case 'date':\n return Field::TYPE_DATE;\n case 'time':\n return Field::TYPE_TIME;\n case 'datetime':\n return Field::TYPE_DATETIME;\n default:\n return Field::TYPE_DATE;\n }\n\n // no break\n case 'string':\n switch ($inputType) {\n case 'textarea':\n return Field::TYPE_TEXTAREA;\n case 'select':\n return Field::TYPE_PICKLIST;\n default:\n return Field::TYPE_TEXT;\n }\n\n // no break\n default:\n // This is not actually a supported field.\n return Field::TYPE_UNSUPPORTED;\n }\n }\n\n private function importContact($crmData): Contact\n {\n $account = $mobilePhone = $phone = $email = null;\n if (empty($crmData['clientCorporation']) === false) {\n $account = $this->team\n ->accounts()\n ->where('crm_provider_id', $crmData['clientCorporation']['id'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n }\n\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => $crmData['name'],\n 'email' => $email,\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'title' => $crmData['occupation'],\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Contact::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n if ($crmData['clientCorporation']['id']) {\n $account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n } else {\n // If there is nothing to associate this with, don't import it.\n return null;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $stage = $this->config->stages()\n ->where('crm_provider_id', $crmData['status'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => mb_strimwidth($crmData['title'], 0, 128),\n 'value' => $crmData['salary'] ?? $crmData['payRate'],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),\n 'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),\n 'is_closed' => $crmData['isOpen'] !== true,\n 'is_won' => strtolower($crmData['status']) === 'placed',\n 'stage_id' => $stage->id,\n 'record_type_id' => null,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importAccount($crmData): Account\n {\n $countryCode = $domain = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $name = $crmData['name'] ?? 'Unknown';\n\n if ($crmData['companyURL'] !== null) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => null,\n 'owner_id' => null,\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Account::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'country_code' => $countryCode,\n 'domain' => $domain,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importLead($crmData): ?Lead\n {\n // Get the current stage.\n $stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);\n }\n\n // If we have no way of importing this, just return null :(\n if ($stage === null) {\n return null;\n }\n\n $countryCode = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $mobilePhone = $phone = $email = null;\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $company = 'Unknown';\n if (empty($crmData['companyName']) === false) {\n $companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];\n $company = mb_strimwidth($companyName, 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['companyURL']) === false) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'company' => $company,\n 'domain' => $domain,\n 'name' => mb_strimwidth($crmData['name'], 0, 191),\n 'title' => mb_strimwidth($crmData['occupation'], 0, 128),\n 'email' => mb_strimwidth($email, 0, 80),\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Lead::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'stage_id' => $stage->id,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhContacts = $this->client->get('search/ClientContact', $params);\n\n foreach ($bhContacts['data'] as $bhContact) {\n // Only sync if previously imported.\n if ($this->hasContact($bhContact['id'])) {\n $this->importContact($bhContact);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategies = $strategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n $total = 0;\n $count = 0;\n $offset = 0;\n\n try {\n $bhOpportunities = [];\n foreach ($strategies as $syncStrategy) {\n $opportunitiesData = $syncStrategy->fetchOpportunities($parameters);\n $total = (int) ($opportunitiesData['total'] ?? 0);\n $count = (int) ($opportunitiesData['count'] ?? 0);\n $offset = (int) ($opportunitiesData['start'] ?? 0);\n $bhOpportunities[] = $opportunitiesData['data'] ?? [];\n }\n\n $bhOpportunities = array_merge(...$bhOpportunities);\n\n foreach ($bhOpportunities as $bhOpportunity) {\n $this->importOpportunity($bhOpportunity);\n $syncCount++;\n }\n } catch (\\Exception $exception) {\n $this->logger->info('Failed to sync opportunities', [\n 'params' => $parameters,\n 'exception' => $exception->getMessage(),\n ]);\n }\n\n // only log if there are one sync strategy\n if (count($strategies) === 1 && $total > $count + $offset) {\n $this->logger->info('[Bullhorn] Sync Opportunities - count warning', [\n 'team_id' => $this->team->getId(),\n 'total' => $total,\n 'count' => $count,\n 'offset' => $offset,\n ]);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhAccounts = $this->client->get('search/ClientCorporation', $params);\n\n foreach ($bhAccounts['data'] as $bhAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($bhAccount['id'])) {\n $this->importAccount($bhAccount);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhLeads = $this->client->get('search/Candidate', $params);\n if ($bhLeads === null) {\n return $syncCount;\n }\n\n foreach ($bhLeads['data'] as $bhLead) {\n // Only sync if previously imported.\n if ($this->hasLead($bhLead['id'])) {\n $this->importLead($bhLead);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n\n public function syncContact(string $crmId): ?Contact\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importContact($data['data']);\n }\n\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategy = $strategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n try {\n $data = $strategy->fetchOpportunities(['crm_id' => $crmId]);\n } catch (HttpNotFoundException $exception) {\n $this->logger->info('[Bullhorn] Opportunity not found', [\n 'crm_id' => $crmId,\n 'reason' => $exception->getMessage(),\n ]);\n }\n\n return $this->importOpportunity($data['data'] ?? []);\n }\n\n public function syncAccount(string $crmId): ?Account\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importAccount($data['data']);\n }\n\n public function syncLead(string $crmId): ?Lead\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importLead($data['data']);\n }\n\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $missingStage = null;\n\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n\n foreach ($types as $type) {\n $resource = $this->convertObjectTypeToResource($type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => 'status',\n 'meta' => 'full',\n ]);\n\n $missingStage = null;\n\n if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {\n throw new \\UnexpectedValueException('Invalid response from Bullhorn API');\n }\n\n // Upsert all stages for the team.\n foreach ($entity['fields'][0]['options'] as $i => $option) {\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $option['value'],\n 'type' => $type,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($option['value'], 0, 50),\n 'label' => mb_strimwidth($option['label'], 0, 191),\n 'sequence' => $i,\n 'is_selectable' => 1,\n ]);\n\n if ($missingStageName && $missingStageName === $option['value']) {\n $missingStage = $stage;\n }\n }\n\n if ($missingStageName && $missingStage === null) {\n // If they requested a stage that still doesn't exist, it must be inactive so lazy create it.\n $missingStage = $this->config->stages()->create([\n 'team_id' => $this->team->id,\n 'crm_provider_id' => Uuid::uuid4(),\n 'name' => mb_strimwidth($missingStageName, 0, 50),\n 'label' => mb_strimwidth($missingStageName, 0, 191),\n 'type' => $type,\n 'sequence' => 0,\n 'is_selectable' => 0,\n ]);\n }\n }\n\n return $missingStage;\n }\n\n public function syncOrganization(): void\n {\n // There appears to be nothing we can sync/map to.\n }\n\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $data = \\Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {\n $result = [];\n\n try {\n $objects = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => $count,\n ]);\n } catch (\\GuzzleHttp\\Exception\\ServerException $exception) {\n throw new ServiceUnavailableException($exception->getMessage());\n }\n\n foreach ($objects['data'] as $object) {\n try {\n $prospectType = $this->convertResourceToObjectType($object['entityType']);\n } catch (\\UnexpectedValueException $exception) {\n // We don't support this, so skip it.\n continue;\n }\n\n $record = [\n 'crmId' => $object['entityId'],\n 'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),\n 'prospectType' => $prospectType,\n 'phoneNumbers' => [],\n ];\n\n // Unfortunately we need to go and query each entity itself to get the data we need.\n switch ($object['entityType']) {\n case self::ENTITY_ACCOUNT:\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['industry'] = $entity['industryList'];\n if (empty($entity['phone']) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity['phone'],\n 'nationalFormat' => phone_national(null, $entity['phone']),\n 'type' => 'phone',\n ];\n }\n\n break;\n\n case self::ENTITY_CONTACT:\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n case self::ENTITY_LEAD:\n $bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);\n $entity = $bhData['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['companyName'];\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n default:\n // We are not interested in this entity type so skip it.\n continue 2;\n }\n\n $result[] = $record;\n }\n\n return $result;\n });\n\n return $data;\n }\n\n public function getClient(): BullhornClientInterface\n {\n return $this->client;\n }\n\n private function getFieldsAsString(array $fields)\n {\n return implode(', ', $fields);\n }\n\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),\n ];\n\n $onlyOpen = true;\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort'] = '-dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort'] = '+dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n $onlyOpen = false;\n }\n\n if ($onlyOpen) {\n $where .= ' AND isOpen: true';\n }\n\n $params['query'] = $where;\n\n $bhOpportunities = $this->client->get('search/JobOrder', $params);\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n foreach ($bhOpportunities['data'] as $bhOpportunity) {\n $stage = $this->config\n ->stages()\n ->where('crm_provider_id', $bhOpportunity['status'])\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);\n }\n\n $record = [\n 'crmId' => $bhOpportunity['id'],\n 'name' => $bhOpportunity['title'],\n 'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),\n 'won' => strtolower($bhOpportunity['status']) === 'placed',\n 'closed' => $bhOpportunity['isOpen'] !== true,\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n 'recordType' => [],\n ];\n\n if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = [];\n\n // For now it has not been agreed on how to implement this e.g. appointments or tasks?\n return [];\n\n if ($objectType === 'account' && $opportunityId === null) {\n // You cannot attach tasks to only accounts.\n return [];\n }\n\n // Query should default to any open task.\n $where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;\n\n // If we are also going to check on a specific job order, set that up.\n if ($opportunityId) {\n $where .= ' OR JobOrder: ' . (int) $opportunityId;\n }\n\n $where .= ')';\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => $where,\n ];\n\n $bhTasks = $this->client->get('search/Task', $params);\n\n foreach ($bhTasks['data'] as $bhTask) {\n $data[] = [\n 'crmId' => $bhTask['id'],\n 'subject' => $bhTask['subject'],\n 'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),\n 'type' => null,\n ];\n }\n\n return $data;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * ?Lead,\n * ?Account,\n * ?Opportunity,\n * ?Contact,\n * ?Stage,\n * ?string\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $bhObject = $this->client->get('find', [\n 'query' => $email,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember === false) {\n $bhObject = $this->client->get('find', [\n 'query' => $rawPhoneNumber ?? $phone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n if (empty($bhObject['data'])) {\n $nationalPhone = phone_national(null, $rawPhoneNumber ?? $phone);\n $formattedPhone = ltrim($nationalPhone, '+0');\n $bhObject = $this->client->get('find', [\n 'query' => $formattedPhone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n }\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n return null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 3) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = \\Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n $bhObject = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->team->getId() . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n public function saveActivity(Activity $activity): Activity\n {\n\n if ($activity->hasCrmProviderId()) {\n return $activity;\n }\n\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildNotePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n /**\n * @throws CrmException\n * @throws DomainException\n */\n private function buildNotePayload(Activity $activity): Activity\n {\n if ($activity->hasActivityType() === false) {\n throw new DomainException('[Bullhorn] No activity type assigned');\n }\n\n $action = $this->getCrmType($activity->getActivityType());\n if ($action === null) {\n throw new DomainException('[Bullhorn] No mapped CRM type for \"' . $activity->category->name . '\"');\n }\n\n if ($activity->lead_id === null && $activity->contact_id === null) {\n throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');\n }\n\n $payload = [\n 'comments' => $this->generateActivityDescription($activity),\n 'action' => $action->value,\n 'commentingPerson' => [\n 'id' => (int) $this->profile->crm_provider_id,\n 'type' => 'CorporateUser',\n ],\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n 'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),\n ];\n\n if ($activity->lead_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->lead->crm_provider_id,\n 'type' => 'Candidate',\n ];\n }\n\n if ($activity->contact_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->contact->crm_provider_id,\n 'type' => 'ClientContact',\n ];\n }\n\n if ($activity->opportunity_id) {\n $payload['jobOrders'] = [\n 'replaceAll' => [\n (int) $activity->opportunity->crm_provider_id,\n ],\n ];\n }\n\n $bhActivity = $this->client->put('entity/Note', $payload);\n\n $activity->crm_provider_id = $bhActivity['changedEntityId'];\n $activity->save();\n\n return $activity;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = '';\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: %s</span></p>',\n $activity->to->phone_number,\n );\n }\n $description .= '<p></p>';\n }\n\n if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: %s</span></p>',\n $activity->from->phone_number,\n );\n $description .= '<p></p>';\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span>'\n . '</p>';\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span>'\n . '</p>';\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= sprintf(\n '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . '<a href=\"%s\" target=\"_blank\">'\n . 'Review in Jiminny'\n . '</a>'\n . '️</span>'\n . '</p>',\n $playbackUrl,\n );\n }\n\n if ($activity->isTypeConference()) {\n $description .= '<p><strong>Attendees</strong></p><ul>';\n\n // Only include participants that joined.\n $participants = $activity->participants()->ghost(false)->whereNotNull('enter_time')->get();\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->name) {\n $attendee .= $participant->name;\n if ($participant->phone_number) {\n $attendee .= ' (' . $participant->phone_number . ')';\n } elseif ($participant->email) {\n $attendee .= ' (' . $participant->email . ')';\n }\n } else {\n $attendee .= $participant->phone_number;\n }\n\n if ($participant->is_ghost) {\n $attendee .= ' <strong>coach</coach>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $description .= $attendee . '</li>';\n }\n $description .= '</ul>';\n }\n\n if (count($activity->notes) > 0) {\n $description .= '<p><strong>Notes</strong></p>';\n\n foreach ($activity->notes as $note) {\n $time = ($note->time > 3600) ? gmdate('H:i:s', $note->time) : gmdate('i:s', $note->time);\n $description .= '<p>' . $time . ' ' . $note->note . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n if ($activity->summary) {\n $description .= '<p><strong>Summary</strong></p><p>' . $activity->summary . '</p><p></p>';\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n // Use Rich-text formatting.\n $description = sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>%s</strong></span></p>',\n $activity->title,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->description,\n );\n\n break;\n }\n\n return $description;\n }\n\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // Not yet required by current customers.\n return null;\n }\n\n public function updateStage($crmObject, Stage $stage): void\n {\n $objectId = $crmObject->crm_provider_id;\n\n $this->updateRecord($stage->type, $objectId, ['status' => $stage->crm_provider_id]);\n }\n\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $start = 0;\n $payload = [\n 'fields' => 'id,email',\n 'where' => 'isDeleted=false',\n 'count' => 500,\n ];\n\n $payload['start'] = $start;\n $profiles = $this->client->get('query/CorporateUser', $payload);\n\n foreach ($profiles['data'] as $profile) {\n if (empty($profile['email'])) {\n continue;\n }\n\n $user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);\n\n // Only import profiles for users we have locally.\n if ($user) {\n $profile = $user->crmProfile()->updateOrCreate([\n 'crm_configuration_id' => $this->config->id,\n 'crm_provider_id' => $profile['id'],\n ]);\n\n if ($userToSearch && $userToSearch->id === $user->id) {\n return $profile;\n }\n }\n }\n\n return null;\n }\n\n protected function convertCrmData(array $entities, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n $mappedEntities = [];\n foreach ($entities as $entity) {\n if (in_array($entity['entityType'], [self::ENTITY_LEAD, self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n $mappedEntities[] = $entity;\n }\n }\n\n // If there is only one match, sync the data and return the object(s).\n if (count($mappedEntities) === 1) {\n $entity = $mappedEntities[0];\n\n if ($entity['entityType'] === self::ENTITY_LEAD) {\n $lead = $this->syncLead($entity['entityId']);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } elseif (in_array($entity['entityType'], [self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n if ($entity['entityType'] === self::ENTITY_CONTACT) {\n $contact = $this->syncContact($entity['entityId']);\n $account = $contact->account;\n } else {\n $account = $this->syncAccount($entity['entityId']);\n }\n\n if ($contact?->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $bhOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact?->crm_provider_id,\n $userId,\n );\n\n // Take the first opportunity, which will be ordered as priority based on their settings.\n if (! empty($bhOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($bhOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n } catch (Exception) {\n // Nothing to see here.\n }\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n // There doesn't appear to be a way to deeplink to anything on https://app.bullhornstaffing.com.\n return null;\n }\n\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $this->client->post('entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId, $data);\n }\n\n public function getRecord(string $objectType, string $objectId, array $fields = ['id']): array\n {\n return $this->client->get(\n url: 'entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId,\n data: ['fields' => $this->getFieldsAsString($fields)],\n );\n }\n\n private function convertObjectTypeToResource(string $objectType)\n {\n switch ($objectType) {\n case FieldData::OBJECT_OPPORTUNITY:\n return self::ENTITY_OPPORTUNITY;\n\n case FieldData::OBJECT_CONTACT:\n return self::ENTITY_CONTACT;\n\n case FieldData::OBJECT_LEAD:\n return self::ENTITY_LEAD;\n\n case FieldData::OBJECT_ACCOUNT:\n return self::ENTITY_ACCOUNT;\n\n case FieldData::OBJECT_TASK:\n return self::ENTITY_ACTIVITY;\n\n default:\n throw new \\UnexpectedValueException('Unsupported object type \"' . $objectType . '\"');\n }\n }\n\n private function convertResourceToObjectType(string $resource): string\n {\n switch ($resource) {\n case self::ENTITY_OPPORTUNITY:\n return FieldData::OBJECT_OPPORTUNITY;\n\n case self::ENTITY_CONTACT:\n return FieldData::OBJECT_CONTACT;\n\n case self::ENTITY_LEAD:\n return FieldData::OBJECT_LEAD;\n\n case self::ENTITY_ACCOUNT:\n return FieldData::OBJECT_ACCOUNT;\n\n case self::ENTITY_ACTIVITY:\n return FieldData::OBJECT_TASK;\n\n default:\n throw new \\UnexpectedValueException('Unsupported resource \"' . $resource . '\"');\n }\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n // We need to know when it started to determine when to look for related activity.\n if ($activity->hasActualStartTime() === false) {\n return null;\n }\n\n try {\n $bhNote = $this->fetchRelatedActivity($activity);\n if (empty($bhNote)) {\n $this->logger->info('[Bullhorn] No related activity found', [\n 'activity' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $activityType = $this->getPlaybookCategory($this->getPlaybook($activity->user), $bhNote['action']);\n $comments = $bhNote['comments'] . '<br />//<br />' . $this->generateActivityDescription($activity);\n // Now update the Note to contain our data.\n $payload = [\n 'comments' => $comments,\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n ];\n\n $this->logger->info('[Bullhorn] updating related activity', [\n 'activity' => $activity->getUuid(),\n 'activityType' => $activityType->id ?? null,\n ]);\n\n $this->client->post('entity/Note/' . $bhNote['id'], $payload);\n\n $playbookCategoryId = null;\n if ($activity->getCategory() !== null) {\n $playbookCategoryId = $activity->getCategory()->getId();\n }\n\n // Update our activity to reflect the remote data.\n $activity->update([\n 'crm_provider_id' => $bhNote['id'],\n 'summary' => $bhNote['comments'],\n 'playbook_category_id' => $activityType->id ?? $playbookCategoryId,\n ]);\n\n return $activity;\n } catch (\\Exception $exception) {\n \\Sentry::captureException($exception);\n\n throw $exception;\n }\n }\n\n /**\n * Returns the most recently modified note within time range (if any).\n *\n * @return array A Note record from Bullhorn.\n */\n public function fetchRelatedActivity(Activity $activity): array\n {\n $from = $activity->hasScheduledStartTime()\n ? $activity->getScheduledStartTime()\n : $activity->getActualStartTime();\n $to = $activity->hasActualEndTime()\n ? $activity->getActualEndTime()?->addMinutes(15)\n : $from?->clone()->addMinutes(15);\n\n $filterStatements = [\n 'isDeleted: false',\n '*:* -externalID:[* TO *]', // externalID should be null e.g. we did not already relate it.\n sprintf('commentingPerson: %d', (int) $this->profile->crm_provider_id),\n ];\n\n /**\n * @XXX: Bullhorn does not specify the time zone in their docs. I've found a forum thread in which someone from\n * staff asserts it's UTC, however in my field test I've found it to be GMT-0300 (USA east coast).\n * To make the code immune to such glitches we will add 24h to start/end boundaries and will filter out\n * any excess items in code\n */\n $filterStatements[] = sprintf(\n 'dateLastModified:[%s TO %s]',\n $from?->clone()->subHours(24)->format('YmdHis'),\n $to->clone()->addHours(24)->format('YmdHis'),\n );\n\n if ($activity->lead_id) {\n $filterStatements[] = sprintf('candidateUserID: %d', (int) $activity->lead->crm_provider_id);\n }\n\n if ($activity->contact_id) {\n $filterStatements[] = sprintf('clientContactUserID: %d', (int) $activity->contact->crm_provider_id);\n }\n\n // if there is no contact or lead associated to the activity exit\n if ($activity->contact_id === null && $activity->lead_id === null) {\n return [];\n }\n\n $params = [\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => implode(' AND ', $filterStatements),\n 'sort' => '-dateLastModified',\n ];\n\n $bhNotes = $this->client->get('search/Note', $params);\n\n $startStamp = $from?->getTimestamp() * 1000;\n $endStamp = $to->getTimestamp() * 1000;\n\n $filteredNotes = array_values(\n array_filter(\n $bhNotes['data'],\n static fn (array $bhNote): bool\n => $bhNote['dateLastModified'] >= $startStamp && $startStamp <= $endStamp,\n ),\n );\n\n return ! empty($filteredNotes) ? array_shift($filteredNotes) : [];\n }\n\n /**\n * Select how to create the date out of the Bullhorn payload.\n * Do not allow dates beyond 9999-12-31 (max mysql DATE)\n */\n private function filterOutOfBoundDates(string $rawDateCandidate): ?Carbon\n {\n if (strlen($rawDateCandidate) > 12) {\n // A unix timestamp represented with more than 12 digits i\n // s definitely including milliseconds\n $dateFormatted = Carbon::createFromTimestampMs($rawDateCandidate);\n } else {\n $dateFormatted = Carbon::createFromTimestamp($rawDateCandidate);\n }\n\n $minDate = Carbon::createFromFormat('Y-m-d', '2000-01-01');\n if ($dateFormatted->lt($minDate)) {\n return null;\n }\n\n $maxDate = Carbon::createFromFormat('Y-m-d', '9999-12-31');\n if ($dateFormatted->gt($maxDate)) {\n $this->logger->warning('[Bullhorn] An out of bound date is provided', [\n 'date' => $dateFormatted,\n 'rawDate' => $rawDateCandidate,\n ]);\n\n return $maxDate;\n }\n\n return $dateFormatted;\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n $note = $this->getRecord('Note', $crmProviderId, ['id', 'isDeleted']);\n\n return ! empty($note) && ($note['isDeleted'] ?? false) === false;\n } catch (HttpNotFoundException|HttpBadRequestException) {\n // Note not found in CRM - this is expected and permanent\n $this->logger->info('[Bullhorn] Note not found during verification', [\n 'note_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Bullhorn;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\BullhornInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\ApplicationException;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\DomainException;\nuse Jiminny\\Exceptions\\HttpBadRequestException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\ServiceUnavailableException;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\UserRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\nuse Ramsey\\Uuid\\Uuid;\n\nclass BullhornService extends BaseService implements\n BullhornInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const string ENTITY_LEAD = 'Candidate';\n private const string ENTITY_OPPORTUNITY = 'JobOrder';\n private const string ENTITY_ACCOUNT = 'ClientCorporation';\n private const string ENTITY_CONTACT = 'ClientContact';\n private const string ENTITY_ACTIVITY = 'Note';\n\n private const array OPPORTUNITY_FIELDS = [\n 'id',\n 'owner',\n 'status',\n 'title',\n 'salary',\n 'salaryUnit',\n 'payRate',\n 'isOpen',\n 'employmentType',\n 'dateClosed',\n 'startDate',\n 'dateLastModified',\n 'dateAdded',\n 'clientCorporation',\n 'correlatedCustomText10', // currency\n ];\n\n private const array TASK_FIELDS = [\n 'id',\n 'comments',\n 'dateAdded',\n 'dateLastModified',\n 'externalID',\n 'isDeleted',\n 'corporateUsers',\n 'clientContacts',\n 'commentingPerson',\n 'candidates',\n 'jobOrder',\n 'minutesSpent',\n 'action',\n ];\n\n private const array LEAD_FIELDS = [\n 'id',\n 'name',\n 'owner',\n 'occupation',\n 'companyName',\n 'companyURL',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'workPhone',\n 'status',\n 'address',\n 'dateAdded',\n 'dateLastModified',\n ];\n\n private const array CONTACT_FIELDS = [\n 'id',\n 'name',\n 'occupation',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'address',\n 'clientCorporation',\n 'dateAdded',\n 'owner',\n ];\n\n private const array ACCOUNT_FIELDS = [\n 'id',\n 'name',\n 'phone',\n 'industryList',\n 'address',\n 'companyURL',\n 'dateAdded',\n ];\n\n public function __construct(\n BullhornClientInterface $client,\n private readonly UserRepository $userRepository,\n private readonly ProspectPhotoPathService $prospectPhotoPathService\n ) {\n parent::__construct();\n\n $this->client = $client;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);\n }\n\n public function getDisplayName(): string\n {\n return 'Bullhorn';\n }\n\n public function createTranscriptNotes(Activity $activity): void\n {\n // Not done until a customer requests it.\n }\n\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n 'task',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))\n );\n\n if (! empty($changedFields)) {\n $fields = implode(',', $newFields);\n Log::debug(\n sprintf(\n '%s fields changed from %s to: %s',\n ucfirst($fieldType),\n $this->profile->{$fieldType . '_fields'},\n $fields,\n ),\n );\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (\\Exception $exception) {\n \\Log::error('No access to ' . $fieldType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n //parent::OBJECT_ACCOUNT,\n //parent::OBJECT_CONTACT,\n //parent::OBJECT_OPPORTUNITY,\n //parent::OBJECT_LEAD,\n ];\n }\n\n protected function getFields(string $crmObject): array\n {\n $fields = [];\n foreach ($this->getObjectFields($crmObject) as $row) {\n $fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];\n }\n\n return $fields;\n }\n\n private function getObjectFields(string $objectType): array\n {\n $entityType = $this->convertObjectTypeToResource($objectType);\n\n return Cache::remember(\n key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,\n ttl: 60 * 60,\n callback: function () use ($entityType) {\n $entity = $this->client->get('meta/' . $entityType, [\n 'fields' => '*',\n ]);\n\n return $entity['fields'];\n },\n );\n }\n\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n $defaultFields = FieldDefinitions::defaultFields();\n\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n\n return $fields;\n }\n\n public function getDefaultActivityField(string $activityType): Field\n {\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'action',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n // We are not yet supporting follow-ups for this system.\n return [];\n }\n\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return $fieldValue;\n }\n\n public function syncField(Field $field): void\n {\n $resource = $this->convertObjectTypeToResource($field->object_type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => $field->crm_provider_id,\n 'meta' => 'full',\n ]);\n\n $bhField = $entity['fields'][0];\n\n $isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);\n $description = null;\n if (empty($bhField['description']) === false) {\n $description = mb_strimwidth($bhField['description'], 0, 191);\n }\n\n $label = 'Unknown';\n if (empty($bhField['label']) === false) {\n $label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);\n }\n\n $field->length = $bhField['maxLength'] ?? null;\n $field->is_mandatory = $isMandatory;\n $field->description = $description;\n $field->label = $label;\n $field->type = $this->convertFieldType(\n $bhField['dataType'] ?? null,\n $bhField['dataSpecialization'] ?? null,\n $bhField['inputType'] ?? null\n );\n\n $field->save();\n\n if (empty($bhField['options']) === false) {\n $values = [];\n\n // Import all values.\n foreach ($bhField['options'] as $i => $option) {\n $values[] = [\n 'value' => $option['value'],\n 'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),\n 'sequence' => $i,\n ];\n }\n\n // Take the existing set of field values.\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n // For all current values, upsert the field.\n $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n $key = array_search($value['value'], $fieldsToPurge, false);\n if ($key !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n }\n }\n\n public function importPicklistValues(Field $field): array\n {\n // Taken care of in syncField.\n return [];\n }\n\n private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string\n {\n if ($type === null) {\n return Field::TYPE_UNSUPPORTED;\n }\n\n $type = strtolower($type);\n $specialization = strtolower($specialization);\n $inputType = strtolower($inputType);\n\n switch ($type) {\n case 'boolean':\n return Field::TYPE_BOOLEAN;\n\n case 'integer':\n switch ($specialization) {\n case 'integer':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'bigdecimal':\n switch ($specialization) {\n case 'money':\n return Field::TYPE_CURRENCY;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'double':\n switch ($specialization) {\n case 'float':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'timestamp':\n switch ($specialization) {\n case 'date':\n return Field::TYPE_DATE;\n case 'time':\n return Field::TYPE_TIME;\n case 'datetime':\n return Field::TYPE_DATETIME;\n default:\n return Field::TYPE_DATE;\n }\n\n // no break\n case 'string':\n switch ($inputType) {\n case 'textarea':\n return Field::TYPE_TEXTAREA;\n case 'select':\n return Field::TYPE_PICKLIST;\n default:\n return Field::TYPE_TEXT;\n }\n\n // no break\n default:\n // This is not actually a supported field.\n return Field::TYPE_UNSUPPORTED;\n }\n }\n\n private function importContact($crmData): Contact\n {\n $account = $mobilePhone = $phone = $email = null;\n if (empty($crmData['clientCorporation']) === false) {\n $account = $this->team\n ->accounts()\n ->where('crm_provider_id', $crmData['clientCorporation']['id'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n }\n\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => $crmData['name'],\n 'email' => $email,\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'title' => $crmData['occupation'],\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Contact::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n if ($crmData['clientCorporation']['id']) {\n $account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n } else {\n // If there is nothing to associate this with, don't import it.\n return null;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $stage = $this->config->stages()\n ->where('crm_provider_id', $crmData['status'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => mb_strimwidth($crmData['title'], 0, 128),\n 'value' => $crmData['salary'] ?? $crmData['payRate'],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),\n 'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),\n 'is_closed' => $crmData['isOpen'] !== true,\n 'is_won' => strtolower($crmData['status']) === 'placed',\n 'stage_id' => $stage->id,\n 'record_type_id' => null,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importAccount($crmData): Account\n {\n $countryCode = $domain = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $name = $crmData['name'] ?? 'Unknown';\n\n if ($crmData['companyURL'] !== null) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => null,\n 'owner_id' => null,\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Account::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'country_code' => $countryCode,\n 'domain' => $domain,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importLead($crmData): ?Lead\n {\n // Get the current stage.\n $stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);\n }\n\n // If we have no way of importing this, just return null :(\n if ($stage === null) {\n return null;\n }\n\n $countryCode = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $mobilePhone = $phone = $email = null;\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $company = 'Unknown';\n if (empty($crmData['companyName']) === false) {\n $companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];\n $company = mb_strimwidth($companyName, 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['companyURL']) === false) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'company' => $company,\n 'domain' => $domain,\n 'name' => mb_strimwidth($crmData['name'], 0, 191),\n 'title' => mb_strimwidth($crmData['occupation'], 0, 128),\n 'email' => mb_strimwidth($email, 0, 80),\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Lead::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'stage_id' => $stage->id,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhContacts = $this->client->get('search/ClientContact', $params);\n\n foreach ($bhContacts['data'] as $bhContact) {\n // Only sync if previously imported.\n if ($this->hasContact($bhContact['id'])) {\n $this->importContact($bhContact);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategies = $strategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n $total = 0;\n $count = 0;\n $offset = 0;\n\n try {\n $bhOpportunities = [];\n foreach ($strategies as $syncStrategy) {\n $opportunitiesData = $syncStrategy->fetchOpportunities($parameters);\n $total = (int) ($opportunitiesData['total'] ?? 0);\n $count = (int) ($opportunitiesData['count'] ?? 0);\n $offset = (int) ($opportunitiesData['start'] ?? 0);\n $bhOpportunities[] = $opportunitiesData['data'] ?? [];\n }\n\n $bhOpportunities = array_merge(...$bhOpportunities);\n\n foreach ($bhOpportunities as $bhOpportunity) {\n $this->importOpportunity($bhOpportunity);\n $syncCount++;\n }\n } catch (\\Exception $exception) {\n $this->logger->info('Failed to sync opportunities', [\n 'params' => $parameters,\n 'exception' => $exception->getMessage(),\n ]);\n }\n\n // only log if there are one sync strategy\n if (count($strategies) === 1 && $total > $count + $offset) {\n $this->logger->info('[Bullhorn] Sync Opportunities - count warning', [\n 'team_id' => $this->team->getId(),\n 'total' => $total,\n 'count' => $count,\n 'offset' => $offset,\n ]);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhAccounts = $this->client->get('search/ClientCorporation', $params);\n\n foreach ($bhAccounts['data'] as $bhAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($bhAccount['id'])) {\n $this->importAccount($bhAccount);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhLeads = $this->client->get('search/Candidate', $params);\n if ($bhLeads === null) {\n return $syncCount;\n }\n\n foreach ($bhLeads['data'] as $bhLead) {\n // Only sync if previously imported.\n if ($this->hasLead($bhLead['id'])) {\n $this->importLead($bhLead);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n\n public function syncContact(string $crmId): ?Contact\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importContact($data['data']);\n }\n\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategy = $strategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n try {\n $data = $strategy->fetchOpportunities(['crm_id' => $crmId]);\n } catch (HttpNotFoundException $exception) {\n $this->logger->info('[Bullhorn] Opportunity not found', [\n 'crm_id' => $crmId,\n 'reason' => $exception->getMessage(),\n ]);\n }\n\n return $this->importOpportunity($data['data'] ?? []);\n }\n\n public function syncAccount(string $crmId): ?Account\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importAccount($data['data']);\n }\n\n public function syncLead(string $crmId): ?Lead\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importLead($data['data']);\n }\n\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $missingStage = null;\n\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n\n foreach ($types as $type) {\n $resource = $this->convertObjectTypeToResource($type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => 'status',\n 'meta' => 'full',\n ]);\n\n $missingStage = null;\n\n if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {\n throw new \\UnexpectedValueException('Invalid response from Bullhorn API');\n }\n\n // Upsert all stages for the team.\n foreach ($entity['fields'][0]['options'] as $i => $option) {\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $option['value'],\n 'type' => $type,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($option['value'], 0, 50),\n 'label' => mb_strimwidth($option['label'], 0, 191),\n 'sequence' => $i,\n 'is_selectable' => 1,\n ]);\n\n if ($missingStageName && $missingStageName === $option['value']) {\n $missingStage = $stage;\n }\n }\n\n if ($missingStageName && $missingStage === null) {\n // If they requested a stage that still doesn't exist, it must be inactive so lazy create it.\n $missingStage = $this->config->stages()->create([\n 'team_id' => $this->team->id,\n 'crm_provider_id' => Uuid::uuid4(),\n 'name' => mb_strimwidth($missingStageName, 0, 50),\n 'label' => mb_strimwidth($missingStageName, 0, 191),\n 'type' => $type,\n 'sequence' => 0,\n 'is_selectable' => 0,\n ]);\n }\n }\n\n return $missingStage;\n }\n\n public function syncOrganization(): void\n {\n // There appears to be nothing we can sync/map to.\n }\n\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $data = \\Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {\n $result = [];\n\n try {\n $objects = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => $count,\n ]);\n } catch (\\GuzzleHttp\\Exception\\ServerException $exception) {\n throw new ServiceUnavailableException($exception->getMessage());\n }\n\n foreach ($objects['data'] as $object) {\n try {\n $prospectType = $this->convertResourceToObjectType($object['entityType']);\n } catch (\\UnexpectedValueException $exception) {\n // We don't support this, so skip it.\n continue;\n }\n\n $record = [\n 'crmId' => $object['entityId'],\n 'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),\n 'prospectType' => $prospectType,\n 'phoneNumbers' => [],\n ];\n\n // Unfortunately we need to go and query each entity itself to get the data we need.\n switch ($object['entityType']) {\n case self::ENTITY_ACCOUNT:\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['industry'] = $entity['industryList'];\n if (empty($entity['phone']) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity['phone'],\n 'nationalFormat' => phone_national(null, $entity['phone']),\n 'type' => 'phone',\n ];\n }\n\n break;\n\n case self::ENTITY_CONTACT:\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n case self::ENTITY_LEAD:\n $bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);\n $entity = $bhData['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['companyName'];\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n default:\n // We are not interested in this entity type so skip it.\n continue 2;\n }\n\n $result[] = $record;\n }\n\n return $result;\n });\n\n return $data;\n }\n\n public function getClient(): BullhornClientInterface\n {\n return $this->client;\n }\n\n private function getFieldsAsString(array $fields)\n {\n return implode(', ', $fields);\n }\n\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),\n ];\n\n $onlyOpen = true;\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort'] = '-dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort'] = '+dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n $onlyOpen = false;\n }\n\n if ($onlyOpen) {\n $where .= ' AND isOpen: true';\n }\n\n $params['query'] = $where;\n\n $bhOpportunities = $this->client->get('search/JobOrder', $params);\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n foreach ($bhOpportunities['data'] as $bhOpportunity) {\n $stage = $this->config\n ->stages()\n ->where('crm_provider_id', $bhOpportunity['status'])\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);\n }\n\n $record = [\n 'crmId' => $bhOpportunity['id'],\n 'name' => $bhOpportunity['title'],\n 'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),\n 'won' => strtolower($bhOpportunity['status']) === 'placed',\n 'closed' => $bhOpportunity['isOpen'] !== true,\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n 'recordType' => [],\n ];\n\n if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = [];\n\n // For now it has not been agreed on how to implement this e.g. appointments or tasks?\n return [];\n\n if ($objectType === 'account' && $opportunityId === null) {\n // You cannot attach tasks to only accounts.\n return [];\n }\n\n // Query should default to any open task.\n $where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;\n\n // If we are also going to check on a specific job order, set that up.\n if ($opportunityId) {\n $where .= ' OR JobOrder: ' . (int) $opportunityId;\n }\n\n $where .= ')';\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => $where,\n ];\n\n $bhTasks = $this->client->get('search/Task', $params);\n\n foreach ($bhTasks['data'] as $bhTask) {\n $data[] = [\n 'crmId' => $bhTask['id'],\n 'subject' => $bhTask['subject'],\n 'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),\n 'type' => null,\n ];\n }\n\n return $data;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * ?Lead,\n * ?Account,\n * ?Opportunity,\n * ?Contact,\n * ?Stage,\n * ?string\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $bhObject = $this->client->get('find', [\n 'query' => $email,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember === false) {\n $bhObject = $this->client->get('find', [\n 'query' => $rawPhoneNumber ?? $phone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n if (empty($bhObject['data'])) {\n $nationalPhone = phone_national(null, $rawPhoneNumber ?? $phone);\n $formattedPhone = ltrim($nationalPhone, '+0');\n $bhObject = $this->client->get('find', [\n 'query' => $formattedPhone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n }\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n return null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 3) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = \\Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n $bhObject = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->team->getId() . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n public function saveActivity(Activity $activity): Activity\n {\n\n if ($activity->hasCrmProviderId()) {\n return $activity;\n }\n\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildNotePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n /**\n * @throws CrmException\n * @throws DomainException\n */\n private function buildNotePayload(Activity $activity): Activity\n {\n if ($activity->hasActivityType() === false) {\n throw new DomainException('[Bullhorn] No activity type assigned');\n }\n\n $action = $this->getCrmType($activity->getActivityType());\n if ($action === null) {\n throw new DomainException('[Bullhorn] No mapped CRM type for \"' . $activity->category->name . '\"');\n }\n\n if ($activity->lead_id === null && $activity->contact_id === null) {\n throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');\n }\n\n $payload = [\n 'comments' => $this->generateActivityDescription($activity),\n 'action' => $action->value,\n 'commentingPerson' => [\n 'id' => (int) $this->profile->crm_provider_id,\n 'type' => 'CorporateUser',\n ],\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n 'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),\n ];\n\n if ($activity->lead_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->lead->crm_provider_id,\n 'type' => 'Candidate',\n ];\n }\n\n if ($activity->contact_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->contact->crm_provider_id,\n 'type' => 'ClientContact',\n ];\n }\n\n if ($activity->opportunity_id) {\n $payload['jobOrders'] = [\n 'replaceAll' => [\n (int) $activity->opportunity->crm_provider_id,\n ],\n ];\n }\n\n $bhActivity = $this->client->put('entity/Note', $payload);\n\n $activity->crm_provider_id = $bhActivity['changedEntityId'];\n $activity->save();\n\n return $activity;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = '';\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: %s</span></p>',\n $activity->to->phone_number,\n );\n }\n $description .= '<p></p>';\n }\n\n if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: %s</span></p>',\n $activity->from->phone_number,\n );\n $description .= '<p></p>';\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span>'\n . '</p>';\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span>'\n . '</p>';\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= sprintf(\n '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . '<a href=\"%s\" target=\"_blank\">'\n . 'Review in Jiminny'\n . '</a>'\n . '️</span>'\n . '</p>',\n $playbackUrl,\n );\n }\n\n if ($activity->isTypeConference()) {\n $description .= '<p><strong>Attendees</strong></p><ul>';\n\n // Only include participants that joined.\n $participants = $activity->participants()->ghost(false)->whereNotNull('enter_time')->get();\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->name) {\n $attendee .= $participant->name;\n if ($participant->phone_number) {\n $attendee .= ' (' . $participant->phone_number . ')';\n } elseif ($participant->email) {\n $attendee .= ' (' . $participant->email . ')';\n }\n } else {\n $attendee .= $participant->phone_number;\n }\n\n if ($participant->is_ghost) {\n $attendee .= ' <strong>coach</coach>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $description .= $attendee . '</li>';\n }\n $description .= '</ul>';\n }\n\n if (count($activity->notes) > 0) {\n $description .= '<p><strong>Notes</strong></p>';\n\n foreach ($activity->notes as $note) {\n $time = ($note->time > 3600) ? gmdate('H:i:s', $note->time) : gmdate('i:s', $note->time);\n $description .= '<p>' . $time . ' ' . $note->note . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n if ($activity->summary) {\n $description .= '<p><strong>Summary</strong></p><p>' . $activity->summary . '</p><p></p>';\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n // Use Rich-text formatting.\n $description = sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>%s</strong></span></p>',\n $activity->title,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->description,\n );\n\n break;\n }\n\n return $description;\n }\n\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // Not yet required by current customers.\n return null;\n }\n\n public function updateStage($crmObject, Stage $stage): void\n {\n $objectId = $crmObject->crm_provider_id;\n\n $this->updateRecord($stage->type, $objectId, ['status' => $stage->crm_provider_id]);\n }\n\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $start = 0;\n $payload = [\n 'fields' => 'id,email',\n 'where' => 'isDeleted=false',\n 'count' => 500,\n ];\n\n $payload['start'] = $start;\n $profiles = $this->client->get('query/CorporateUser', $payload);\n\n foreach ($profiles['data'] as $profile) {\n if (empty($profile['email'])) {\n continue;\n }\n\n $user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);\n\n // Only import profiles for users we have locally.\n if ($user) {\n $profile = $user->crmProfile()->updateOrCreate([\n 'crm_configuration_id' => $this->config->id,\n 'crm_provider_id' => $profile['id'],\n ]);\n\n if ($userToSearch && $userToSearch->id === $user->id) {\n return $profile;\n }\n }\n }\n\n return null;\n }\n\n protected function convertCrmData(array $entities, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n $mappedEntities = [];\n foreach ($entities as $entity) {\n if (in_array($entity['entityType'], [self::ENTITY_LEAD, self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n $mappedEntities[] = $entity;\n }\n }\n\n // If there is only one match, sync the data and return the object(s).\n if (count($mappedEntities) === 1) {\n $entity = $mappedEntities[0];\n\n if ($entity['entityType'] === self::ENTITY_LEAD) {\n $lead = $this->syncLead($entity['entityId']);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } elseif (in_array($entity['entityType'], [self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n if ($entity['entityType'] === self::ENTITY_CONTACT) {\n $contact = $this->syncContact($entity['entityId']);\n $account = $contact->account;\n } else {\n $account = $this->syncAccount($entity['entityId']);\n }\n\n if ($contact?->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $bhOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact?->crm_provider_id,\n $userId,\n );\n\n // Take the first opportunity, which will be ordered as priority based on their settings.\n if (! empty($bhOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($bhOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n } catch (Exception) {\n // Nothing to see here.\n }\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n // There doesn't appear to be a way to deeplink to anything on https://app.bullhornstaffing.com.\n return null;\n }\n\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $this->client->post('entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId, $data);\n }\n\n public function getRecord(string $objectType, string $objectId, array $fields = ['id']): array\n {\n return $this->client->get(\n url: 'entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId,\n data: ['fields' => $this->getFieldsAsString($fields)],\n );\n }\n\n private function convertObjectTypeToResource(string $objectType)\n {\n switch ($objectType) {\n case FieldData::OBJECT_OPPORTUNITY:\n return self::ENTITY_OPPORTUNITY;\n\n case FieldData::OBJECT_CONTACT:\n return self::ENTITY_CONTACT;\n\n case FieldData::OBJECT_LEAD:\n return self::ENTITY_LEAD;\n\n case FieldData::OBJECT_ACCOUNT:\n return self::ENTITY_ACCOUNT;\n\n case FieldData::OBJECT_TASK:\n return self::ENTITY_ACTIVITY;\n\n default:\n throw new \\UnexpectedValueException('Unsupported object type \"' . $objectType . '\"');\n }\n }\n\n private function convertResourceToObjectType(string $resource): string\n {\n switch ($resource) {\n case self::ENTITY_OPPORTUNITY:\n return FieldData::OBJECT_OPPORTUNITY;\n\n case self::ENTITY_CONTACT:\n return FieldData::OBJECT_CONTACT;\n\n case self::ENTITY_LEAD:\n return FieldData::OBJECT_LEAD;\n\n case self::ENTITY_ACCOUNT:\n return FieldData::OBJECT_ACCOUNT;\n\n case self::ENTITY_ACTIVITY:\n return FieldData::OBJECT_TASK;\n\n default:\n throw new \\UnexpectedValueException('Unsupported resource \"' . $resource . '\"');\n }\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n // We need to know when it started to determine when to look for related activity.\n if ($activity->hasActualStartTime() === false) {\n return null;\n }\n\n try {\n $bhNote = $this->fetchRelatedActivity($activity);\n if (empty($bhNote)) {\n $this->logger->info('[Bullhorn] No related activity found', [\n 'activity' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $activityType = $this->getPlaybookCategory($this->getPlaybook($activity->user), $bhNote['action']);\n $comments = $bhNote['comments'] . '<br />//<br />' . $this->generateActivityDescription($activity);\n // Now update the Note to contain our data.\n $payload = [\n 'comments' => $comments,\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n ];\n\n $this->logger->info('[Bullhorn] updating related activity', [\n 'activity' => $activity->getUuid(),\n 'activityType' => $activityType->id ?? null,\n ]);\n\n $this->client->post('entity/Note/' . $bhNote['id'], $payload);\n\n $playbookCategoryId = null;\n if ($activity->getCategory() !== null) {\n $playbookCategoryId = $activity->getCategory()->getId();\n }\n\n // Update our activity to reflect the remote data.\n $activity->update([\n 'crm_provider_id' => $bhNote['id'],\n 'summary' => $bhNote['comments'],\n 'playbook_category_id' => $activityType->id ?? $playbookCategoryId,\n ]);\n\n return $activity;\n } catch (\\Exception $exception) {\n \\Sentry::captureException($exception);\n\n throw $exception;\n }\n }\n\n /**\n * Returns the most recently modified note within time range (if any).\n *\n * @return array A Note record from Bullhorn.\n */\n public function fetchRelatedActivity(Activity $activity): array\n {\n $from = $activity->hasScheduledStartTime()\n ? $activity->getScheduledStartTime()\n : $activity->getActualStartTime();\n $to = $activity->hasActualEndTime()\n ? $activity->getActualEndTime()?->addMinutes(15)\n : $from?->clone()->addMinutes(15);\n\n $filterStatements = [\n 'isDeleted: false',\n '*:* -externalID:[* TO *]', // externalID should be null e.g. we did not already relate it.\n sprintf('commentingPerson: %d', (int) $this->profile->crm_provider_id),\n ];\n\n /**\n * @XXX: Bullhorn does not specify the time zone in their docs. I've found a forum thread in which someone from\n * staff asserts it's UTC, however in my field test I've found it to be GMT-0300 (USA east coast).\n * To make the code immune to such glitches we will add 24h to start/end boundaries and will filter out\n * any excess items in code\n */\n $filterStatements[] = sprintf(\n 'dateLastModified:[%s TO %s]',\n $from?->clone()->subHours(24)->format('YmdHis'),\n $to->clone()->addHours(24)->format('YmdHis'),\n );\n\n if ($activity->lead_id) {\n $filterStatements[] = sprintf('candidateUserID: %d', (int) $activity->lead->crm_provider_id);\n }\n\n if ($activity->contact_id) {\n $filterStatements[] = sprintf('clientContactUserID: %d', (int) $activity->contact->crm_provider_id);\n }\n\n // if there is no contact or lead associated to the activity exit\n if ($activity->contact_id === null && $activity->lead_id === null) {\n return [];\n }\n\n $params = [\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => implode(' AND ', $filterStatements),\n 'sort' => '-dateLastModified',\n ];\n\n $bhNotes = $this->client->get('search/Note', $params);\n\n $startStamp = $from?->getTimestamp() * 1000;\n $endStamp = $to->getTimestamp() * 1000;\n\n $filteredNotes = array_values(\n array_filter(\n $bhNotes['data'],\n static fn (array $bhNote): bool\n => $bhNote['dateLastModified'] >= $startStamp && $startStamp <= $endStamp,\n ),\n );\n\n return ! empty($filteredNotes) ? array_shift($filteredNotes) : [];\n }\n\n /**\n * Select how to create the date out of the Bullhorn payload.\n * Do not allow dates beyond 9999-12-31 (max mysql DATE)\n */\n private function filterOutOfBoundDates(string $rawDateCandidate): ?Carbon\n {\n if (strlen($rawDateCandidate) > 12) {\n // A unix timestamp represented with more than 12 digits i\n // s definitely including milliseconds\n $dateFormatted = Carbon::createFromTimestampMs($rawDateCandidate);\n } else {\n $dateFormatted = Carbon::createFromTimestamp($rawDateCandidate);\n }\n\n $minDate = Carbon::createFromFormat('Y-m-d', '2000-01-01');\n if ($dateFormatted->lt($minDate)) {\n return null;\n }\n\n $maxDate = Carbon::createFromFormat('Y-m-d', '9999-12-31');\n if ($dateFormatted->gt($maxDate)) {\n $this->logger->warning('[Bullhorn] An out of bound date is provided', [\n 'date' => $dateFormatted,\n 'rawDate' => $rawDateCandidate,\n ]);\n\n return $maxDate;\n }\n\n return $dateFormatted;\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n $note = $this->getRecord('Note', $crmProviderId, ['id', 'isDeleted']);\n\n return ! empty($note) && ($note['isDeleted'] ?? false) === false;\n } catch (HttpNotFoundException|HttpBadRequestException) {\n // Note not found in CRM - this is expected and permanent\n $this->logger->info('[Bullhorn] Note not found during verification', [\n 'note_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.85486114,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.87291664,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.9138889,"top":0.31,"width":0.059027776,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.8645833,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.8854167,"top":0.34444445,"width":0.015277778,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.9048611,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"bounds":{"left":0.92569447,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.9458333,"top":0.3422222,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.9611111,"top":0.3422222,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","depth":4,"on_screen":true,"value":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.025,"top":0.06666667,"width":0.050694443,"height":0.034444444},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Expand Selected","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Collapse All","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Options","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
2798564629323822362
|
-3411827625184589122
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
2
13
3
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Bullhorn;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\Provider\BullhornInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\ApplicationException;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\DomainException;
use Jiminny\Exceptions\HttpBadRequestException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\ServiceUnavailableException;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\UserRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
use Ramsey\Uuid\Uuid;
class BullhornService extends BaseService implements
BullhornInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const string ENTITY_LEAD = 'Candidate';
private const string ENTITY_OPPORTUNITY = 'JobOrder';
private const string ENTITY_ACCOUNT = 'ClientCorporation';
private const string ENTITY_CONTACT = 'ClientContact';
private const string ENTITY_ACTIVITY = 'Note';
private const array OPPORTUNITY_FIELDS = [
'id',
'owner',
'status',
'title',
'salary',
'salaryUnit',
'payRate',
'isOpen',
'employmentType',
'dateClosed',
'startDate',
'dateLastModified',
'dateAdded',
'clientCorporation',
'correlatedCustomText10', // currency
];
private const array TASK_FIELDS = [
'id',
'comments',
'dateAdded',
'dateLastModified',
'externalID',
'isDeleted',
'corporateUsers',
'clientContacts',
'commentingPerson',
'candidates',
'jobOrder',
'minutesSpent',
'action',
];
private const array LEAD_FIELDS = [
'id',
'name',
'owner',
'occupation',
'companyName',
'companyURL',
'mobile',
'phone',
'phone2',
'phone3',
'workPhone',
'status',
'address',
'dateAdded',
'dateLastModified',
];
private const array CONTACT_FIELDS = [
'id',
'name',
'occupation',
'mobile',
'phone',
'phone2',
'phone3',
'address',
'clientCorporation',
'dateAdded',
'owner',
];
private const array ACCOUNT_FIELDS = [
'id',
'name',
'phone',
'industryList',
'address',
'companyURL',
'dateAdded',
];
public function __construct(
BullhornClientInterface $client,
private readonly UserRepository $userRepository,
private readonly ProspectPhotoPathService $prospectPhotoPathService
) {
parent::__construct();
$this->client = $client;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);
}
public function getDisplayName(): string
{
return 'Bullhorn';
}
public function createTranscriptNotes(Activity $activity): void
{
// Not done until a customer requests it.
}
public function syncProfileFields(): void
{
$fieldTypes = [
'lead',
'account',
'contact',
'opportunity',
'task',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))
);
if (! empty($changedFields)) {
$fields = implode(',', $newFields);
Log::debug(
sprintf(
'%s fields changed from %s to: %s',
ucfirst($fieldType),
$this->profile->{$fieldType . '_fields'},
$fields,
),
);
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (\Exception $exception) {
\Log::error('No access to ' . $fieldType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
$this->profile->save();
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
//parent::OBJECT_ACCOUNT,
//parent::OBJECT_CONTACT,
//parent::OBJECT_OPPORTUNITY,
//parent::OBJECT_LEAD,
];
}
protected function getFields(string $crmObject): array
{
$fields = [];
foreach ($this->getObjectFields($crmObject) as $row) {
$fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];
}
return $fields;
}
private function getObjectFields(string $objectType): array
{
$entityType = $this->convertObjectTypeToResource($objectType);
return Cache::remember(
key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,
ttl: 60 * 60,
callback: function () use ($entityType) {
$entity = $this->client->get('meta/' . $entityType, [
'fields' => '*',
]);
return $entity['fields'];
},
);
}
public function getDefaultFields(string $activityType): array
{
$fields = [];
$defaultFields = FieldDefinitions::defaultFields();
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
return $fields;
}
public function getDefaultActivityField(string $activityType): Field
{
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'action',
'object_type' => $activityType,
])->first();
return $activityField;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
// We are not yet supporting follow-ups for this system.
return [];
}
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return $fieldValue;
}
public function syncField(Field $field): void
{
$resource = $this->convertObjectTypeToResource($field->object_type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => $field->crm_provider_id,
'meta' => 'full',
]);
$bhField = $entity['fields'][0];
$isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);
$description = null;
if (empty($bhField['description']) === false) {
$description = mb_strimwidth($bhField['description'], 0, 191);
}
$label = 'Unknown';
if (empty($bhField['label']) === false) {
$label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);
}
$field->length = $bhField['maxLength'] ?? null;
$field->is_mandatory = $isMandatory;
$field->description = $description;
$field->label = $label;
$field->type = $this->convertFieldType(
$bhField['dataType'] ?? null,
$bhField['dataSpecialization'] ?? null,
$bhField['inputType'] ?? null
);
$field->save();
if (empty($bhField['options']) === false) {
$values = [];
// Import all values.
foreach ($bhField['options'] as $i => $option) {
$values[] = [
'value' => $option['value'],
'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),
'sequence' => $i,
];
}
// Take the existing set of field values.
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
// For all current values, upsert the field.
$field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
$key = array_search($value['value'], $fieldsToPurge, false);
if ($key !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
}
}
public function importPicklistValues(Field $field): array
{
// Taken care of in syncField.
return [];
}
private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string
{
if ($type === null) {
return Field::TYPE_UNSUPPORTED;
}
$type = strtolower($type);
$specialization = strtolower($specialization);
$inputType = strtolower($inputType);
switch ($type) {
case 'boolean':
return Field::TYPE_BOOLEAN;
case 'integer':
switch ($specialization) {
case 'integer':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'bigdecimal':
switch ($specialization) {
case 'money':
return Field::TYPE_CURRENCY;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'double':
switch ($specialization) {
case 'float':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'timestamp':
switch ($specialization) {
case 'date':
return Field::TYPE_DATE;
case 'time':
return Field::TYPE_TIME;
case 'datetime':
return Field::TYPE_DATETIME;
default:
return Field::TYPE_DATE;
}
// no break
case 'string':
switch ($inputType) {
case 'textarea':
return Field::TYPE_TEXTAREA;
case 'select':
return Field::TYPE_PICKLIST;
default:
return Field::TYPE_TEXT;
}
// no break
default:
// This is not actually a supported field.
return Field::TYPE_UNSUPPORTED;
}
}
private function importContact($crmData): Contact
{
$account = $mobilePhone = $phone = $email = null;
if (empty($crmData['clientCorporation']) === false) {
$account = $this->team
->accounts()
->where('crm_provider_id', $crmData['clientCorporation']['id'])
->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
}
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => $crmData['name'],
'email' => $email,
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'title' => $crmData['occupation'],
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Contact::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importOpportunity($crmData): ?Opportunity
{
if ($crmData['clientCorporation']['id']) {
$account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
} else {
// If there is nothing to associate this with, don't import it.
return null;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$stage = $this->config->stages()
->where('crm_provider_id', $crmData['status'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);
}
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => mb_strimwidth($crmData['title'], 0, 128),
'value' => $crmData['salary'] ?? $crmData['payRate'],
'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),
'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),
'is_closed' => $crmData['isOpen'] !== true,
'is_won' => strtolower($crmData['status']) === 'placed',
'stage_id' => $stage->id,
'record_type_id' => null,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importAccount($crmData): Account
{
$countryCode = $domain = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$name = $crmData['name'] ?? 'Unknown';
if ($crmData['companyURL'] !== null) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$data = [
'team_id' => $this->team->id,
'user_id' => null,
'owner_id' => null,
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Account::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'country_code' => $countryCode,
'domain' => $domain,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importLead($crmData): ?Lead
{
// Get the current stage.
$stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);
}
// If we have no way of importing this, just return null :(
if ($stage === null) {
return null;
}
$countryCode = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$mobilePhone = $phone = $email = null;
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$company = 'Unknown';
if (empty($crmData['companyName']) === false) {
$companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];
$company = mb_strimwidth($companyName, 0, 191);
}
$domain = null;
if (empty($crmData['companyURL']) === false) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'company' => $company,
'domain' => $domain,
'name' => mb_strimwidth($crmData['name'], 0, 191),
'title' => mb_strimwidth($crmData['occupation'], 0, 128),
'email' => mb_strimwidth($email, 0, 80),
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Lead::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'stage_id' => $stage->id,
'country_code' => $countryCode,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
/**
* @throws ApplicationException
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhContacts = $this->client->get('search/ClientContact', $params);
foreach ($bhContacts['data'] as $bhContact) {
// Only sync if previously imported.
if ($this->hasContact($bhContact['id'])) {
$this->importContact($bhContact);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategies = $strategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
$total = 0;
$count = 0;
$offset = 0;
try {
$bhOpportunities = [];
foreach ($strategies as $syncStrategy) {
$opportunitiesData = $syncStrategy->fetchOpportunities($parameters);
$total = (int) ($opportunitiesData['total'] ?? 0);
$count = (int) ($opportunitiesData['count'] ?? 0);
$offset = (int) ($opportunitiesData['start'] ?? 0);
$bhOpportunities[] = $opportunitiesData['data'] ?? [];
}
$bhOpportunities = array_merge(...$bhOpportunities);
foreach ($bhOpportunities as $bhOpportunity) {
$this->importOpportunity($bhOpportunity);
$syncCount++;
}
} catch (\Exception $exception) {
$this->logger->info('Failed to sync opportunities', [
'params' => $parameters,
'exception' => $exception->getMessage(),
]);
}
// only log if there are one sync strategy
if (count($strategies) === 1 && $total > $count + $offset) {
$this->logger->info('[Bullhorn] Sync Opportunities - count warning', [
'team_id' => $this->team->getId(),
'total' => $total,
'count' => $count,
'offset' => $offset,
]);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhAccounts = $this->client->get('search/ClientCorporation', $params);
foreach ($bhAccounts['data'] as $bhAccount) {
// Only sync if previously imported.
if ($this->hasAccount($bhAccount['id'])) {
$this->importAccount($bhAccount);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhLeads = $this->client->get('search/Candidate', $params);
if ($bhLeads === null) {
return $syncCount;
}
foreach ($bhLeads['data'] as $bhLead) {
// Only sync if previously imported.
if ($this->hasLead($bhLead['id'])) {
$this->importLead($bhLead);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncContact(string $crmId): ?Contact
{
try {
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importContact($data['data']);
}
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategy = $strategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
try {
$data = $strategy->fetchOpportunities(['crm_id' => $crmId]);
} catch (HttpNotFoundException $exception) {
$this->logger->info('[Bullhorn] Opportunity not found', [
'crm_id' => $crmId,
'reason' => $exception->getMessage(),
]);
}
return $this->importOpportunity($data['data'] ?? []);
}
public function syncAccount(string $crmId): ?Account
{
try {
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importAccount($data['data']);
}
public function syncLead(string $crmId): ?Lead
{
try {
$data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importLead($data['data']);
}
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$missingStage = null;
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
foreach ($types as $type) {
$resource = $this->convertObjectTypeToResource($type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => 'status',
'meta' => 'full',
]);
$missingStage = null;
if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {
throw new \UnexpectedValueException('Invalid response from Bullhorn API');
}
// Upsert all stages for the team.
foreach ($entity['fields'][0]['options'] as $i => $option) {
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $option['value'],
'type' => $type,
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($option['value'], 0, 50),
'label' => mb_strimwidth($option['label'], 0, 191),
'sequence' => $i,
'is_selectable' => 1,
]);
if ($missingStageName && $missingStageName === $option['value']) {
$missingStage = $stage;
}
}
if ($missingStageName && $missingStage === null) {
// If they requested a stage that still doesn't exist, it must be inactive so lazy create it.
$missingStage = $this->config->stages()->create([
'team_id' => $this->team->id,
'crm_provider_id' => Uuid::uuid4(),
'name' => mb_strimwidth($missingStageName, 0, 50),
'label' => mb_strimwidth($missingStageName, 0, 191),
'type' => $type,
'sequence' => 0,
'is_selectable' => 0,
]);
}
}
return $missingStage;
}
public function syncOrganization(): void
{
// There appears to be nothing we can sync/map to.
}
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$data = \Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {
$result = [];
try {
$objects = $this->client->get('find', [
'query' => $name,
'meta' => 'basic',
'countPerEntity' => $count,
]);
} catch (\GuzzleHttp\Exception\ServerException $exception) {
throw new ServiceUnavailableException($exception->getMessage());
}
foreach ($objects['data'] as $object) {
try {
$prospectType = $this->convertResourceToObjectType($object['entityType']);
} catch (\UnexpectedValueException $exception) {
// We don't support this, so skip it.
continue;
}
$record = [
'crmId' => $object['entityId'],
'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),
'prospectType' => $prospectType,
'phoneNumbers' => [],
];
// Unfortunately we need to go and query each entity itself to get the data we need.
switch ($object['entityType']) {
case self::ENTITY_ACCOUNT:
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['industry'] = $entity['industryList'];
if (empty($entity['phone']) === false) {
$record['phoneNumbers'][] = [
'number' => $entity['phone'],
'nationalFormat' => phone_national(null, $entity['phone']),
'type' => 'phone',
];
}
break;
case self::ENTITY_CONTACT:
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
case self::ENTITY_LEAD:
$bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);
$entity = $bhData['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['companyName'];
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
default:
// We are not interested in this entity type so skip it.
continue 2;
}
$result[] = $record;
}
return $result;
});
return $data;
}
public function getClient(): BullhornClientInterface
{
return $this->client;
}
private function getFieldsAsString(array $fields)
{
return implode(', ', $fields);
}
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),
];
$onlyOpen = true;
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort'] = '-dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort'] = '+dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
$onlyOpen = false;
}
if ($onlyOpen) {
$where .= ' AND isOpen: true';
}
$params['query'] = $where;
$bhOpportunities = $this->client->get('search/JobOrder', $params);
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
foreach ($bhOpportunities['data'] as $bhOpportunity) {
$stage = $this->config
->stages()
->where('crm_provider_id', $bhOpportunity['status'])
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);
}
$record = [
'crmId' => $bhOpportunity['id'],
'name' => $bhOpportunity['title'],
'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),
'won' => strtolower($bhOpportunity['status']) === 'placed',
'closed' => $bhOpportunity['isOpen'] !== true,
'stage' => [
'id' => $stage->id_string,
'name' => $stage->name,
],
'recordType' => [],
];
if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = [];
// For now it has not been agreed on how to implement this e.g. appointments or tasks?
return [];
if ($objectType === 'account' && $opportunityId === null) {
// You cannot attach tasks to only accounts.
return [];
}
// Query should default to any open task.
$where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;
// If we are also going to check on a specific job order, set that up.
if ($opportunityId) {
$where .= ' OR JobOrder: ' . (int) $opportunityId;
}
$where .= ')';
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::TASK_FIELDS),
'query' => $where,
];
$bhTasks = $this->client->get('search/Task', $params);
foreach ($bhTasks['data'] as $bhTask) {
$data[] = [
'crmId' => $bhTask['id'],
'subject' => $bhTask['subject'],
'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),
'type' => null,
];
}
return $data;
}
/**
* @url [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] CrmException
* @throws DomainException
*/
private function buildNotePayload(Activity $activity): Activity
{
if ($activity->hasActivityType() === false) {
throw new DomainException('[Bullhorn] No activity type assigned');
}
$action = $this->getCrmType($activity->getActivityType());
if ($action === null) {
throw new DomainException('[Bullhorn] No mapped CRM type for "' . $activity->category->name . '"');
}
if ($activity->lead_id === null && $activity->contact_id === null) {
throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');
}
$payload = [
'comments' => $this->generateActivityDescription($activity),
'action' => $action->value,
'commentingPerson' => [
'id' => (int) $this->profile->crm_provider_id,
'type' => 'CorporateUser',
],
'externalID' => $activity->id_string,
'minutesSpent' => $activity->duration,
'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),
];
if ($activity->lead_id) {
$payload['personReference'] = [
'id' => (int) $activity->lead->crm_provider_id,
'type' => 'Candidate',
];
}
if ($activity->contact_id) {
$payload['personReference'] = [
'id' => (int) $activity->contact->crm_provider_id,
'type' => 'ClientContact',
];
}
if ($activity->opportunity_id) {
$payload['jobOrders'] = [
'replaceAll' => [
(int) $activity->opportunity->crm_provider_id,
],
];
}
$bhActivity = $this->client->put('entity/Note', $payload);
$activity->crm_provider_id = $bhActivity['changedEntityId'];
$activity->save();
return $activity;
}
private function generateActivityDescription(Activity $activity): string
{
$description = '';
switch ($activity->type) {
case Activity::TYPE_SOFTPHONE:
case Activity::TYPE_SOFTPHONE_INBOUND:
case Activity::TYPE_CONFERENCE:
if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
// Dialer calls have no native field for the subject.
if ($activity->title) {
$description .= sprintf(
'<p><span style="font-size: 16px; line-height: 19.2px;">%s</span></p>',
$activity->title,
);
}
// Conference meetings log duration into a distinct field, so log this in the main text.
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Call Duration: %s</span></p>',
$activity->duration_for_humans,
);
// Tell them which number was dialed.
if ($activity->to) {
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Dialed: %s</span></p>',
$activity->to->phone_number,
);
}
$description .= '<p></p>';
}
if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45384
|
1626
|
18
|
2026-05-14T14:33:52.328607+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769232328_m2.jpg...
|
PhpStorm
|
faVsco.js – BullhornService.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
2
13
3
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Bullhorn;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\Provider\BullhornInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\ApplicationException;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\DomainException;
use Jiminny\Exceptions\HttpBadRequestException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\ServiceUnavailableException;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\UserRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
use Ramsey\Uuid\Uuid;
class BullhornService extends BaseService implements
BullhornInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const string ENTITY_LEAD = 'Candidate';
private const string ENTITY_OPPORTUNITY = 'JobOrder';
private const string ENTITY_ACCOUNT = 'ClientCorporation';
private const string ENTITY_CONTACT = 'ClientContact';
private const string ENTITY_ACTIVITY = 'Note';
private const array OPPORTUNITY_FIELDS = [
'id',
'owner',
'status',
'title',
'salary',
'salaryUnit',
'payRate',
'isOpen',
'employmentType',
'dateClosed',
'startDate',
'dateLastModified',
'dateAdded',
'clientCorporation',
'correlatedCustomText10', // currency
];
private const array TASK_FIELDS = [
'id',
'comments',
'dateAdded',
'dateLastModified',
'externalID',
'isDeleted',
'corporateUsers',
'clientContacts',
'commentingPerson',
'candidates',
'jobOrder',
'minutesSpent',
'action',
];
private const array LEAD_FIELDS = [
'id',
'name',
'owner',
'occupation',
'companyName',
'companyURL',
'mobile',
'phone',
'phone2',
'phone3',
'workPhone',
'status',
'address',
'dateAdded',
'dateLastModified',
];
private const array CONTACT_FIELDS = [
'id',
'name',
'occupation',
'mobile',
'phone',
'phone2',
'phone3',
'address',
'clientCorporation',
'dateAdded',
'owner',
];
private const array ACCOUNT_FIELDS = [
'id',
'name',
'phone',
'industryList',
'address',
'companyURL',
'dateAdded',
];
public function __construct(
BullhornClientInterface $client,
private readonly UserRepository $userRepository,
private readonly ProspectPhotoPathService $prospectPhotoPathService
) {
parent::__construct();
$this->client = $client;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);
}
public function getDisplayName(): string
{
return 'Bullhorn';
}
public function createTranscriptNotes(Activity $activity): void
{
// Not done until a customer requests it.
}
public function syncProfileFields(): void
{
$fieldTypes = [
'lead',
'account',
'contact',
'opportunity',
'task',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))
);
if (! empty($changedFields)) {
$fields = implode(',', $newFields);
Log::debug(
sprintf(
'%s fields changed from %s to: %s',
ucfirst($fieldType),
$this->profile->{$fieldType . '_fields'},
$fields,
),
);
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (\Exception $exception) {
\Log::error('No access to ' . $fieldType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
$this->profile->save();
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
//parent::OBJECT_ACCOUNT,
//parent::OBJECT_CONTACT,
//parent::OBJECT_OPPORTUNITY,
//parent::OBJECT_LEAD,
];
}
protected function getFields(string $crmObject): array
{
$fields = [];
foreach ($this->getObjectFields($crmObject) as $row) {
$fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];
}
return $fields;
}
private function getObjectFields(string $objectType): array
{
$entityType = $this->convertObjectTypeToResource($objectType);
return Cache::remember(
key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,
ttl: 60 * 60,
callback: function () use ($entityType) {
$entity = $this->client->get('meta/' . $entityType, [
'fields' => '*',
]);
return $entity['fields'];
},
);
}
public function getDefaultFields(string $activityType): array
{
$fields = [];
$defaultFields = FieldDefinitions::defaultFields();
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
return $fields;
}
public function getDefaultActivityField(string $activityType): Field
{
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'action',
'object_type' => $activityType,
])->first();
return $activityField;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
// We are not yet supporting follow-ups for this system.
return [];
}
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return $fieldValue;
}
public function syncField(Field $field): void
{
$resource = $this->convertObjectTypeToResource($field->object_type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => $field->crm_provider_id,
'meta' => 'full',
]);
$bhField = $entity['fields'][0];
$isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);
$description = null;
if (empty($bhField['description']) === false) {
$description = mb_strimwidth($bhField['description'], 0, 191);
}
$label = 'Unknown';
if (empty($bhField['label']) === false) {
$label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);
}
$field->length = $bhField['maxLength'] ?? null;
$field->is_mandatory = $isMandatory;
$field->description = $description;
$field->label = $label;
$field->type = $this->convertFieldType(
$bhField['dataType'] ?? null,
$bhField['dataSpecialization'] ?? null,
$bhField['inputType'] ?? null
);
$field->save();
if (empty($bhField['options']) === false) {
$values = [];
// Import all values.
foreach ($bhField['options'] as $i => $option) {
$values[] = [
'value' => $option['value'],
'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),
'sequence' => $i,
];
}
// Take the existing set of field values.
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
// For all current values, upsert the field.
$field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
$key = array_search($value['value'], $fieldsToPurge, false);
if ($key !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
}
}
public function importPicklistValues(Field $field): array
{
// Taken care of in syncField.
return [];
}
private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string
{
if ($type === null) {
return Field::TYPE_UNSUPPORTED;
}
$type = strtolower($type);
$specialization = strtolower($specialization);
$inputType = strtolower($inputType);
switch ($type) {
case 'boolean':
return Field::TYPE_BOOLEAN;
case 'integer':
switch ($specialization) {
case 'integer':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'bigdecimal':
switch ($specialization) {
case 'money':
return Field::TYPE_CURRENCY;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'double':
switch ($specialization) {
case 'float':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'timestamp':
switch ($specialization) {
case 'date':
return Field::TYPE_DATE;
case 'time':
return Field::TYPE_TIME;
case 'datetime':
return Field::TYPE_DATETIME;
default:
return Field::TYPE_DATE;
}
// no break
case 'string':
switch ($inputType) {
case 'textarea':
return Field::TYPE_TEXTAREA;
case 'select':
return Field::TYPE_PICKLIST;
default:
return Field::TYPE_TEXT;
}
// no break
default:
// This is not actually a supported field.
return Field::TYPE_UNSUPPORTED;
}
}
private function importContact($crmData): Contact
{
$account = $mobilePhone = $phone = $email = null;
if (empty($crmData['clientCorporation']) === false) {
$account = $this->team
->accounts()
->where('crm_provider_id', $crmData['clientCorporation']['id'])
->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
}
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => $crmData['name'],
'email' => $email,
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'title' => $crmData['occupation'],
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Contact::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importOpportunity($crmData): ?Opportunity
{
if ($crmData['clientCorporation']['id']) {
$account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
} else {
// If there is nothing to associate this with, don't import it.
return null;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$stage = $this->config->stages()
->where('crm_provider_id', $crmData['status'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);
}
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => mb_strimwidth($crmData['title'], 0, 128),
'value' => $crmData['salary'] ?? $crmData['payRate'],
'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),
'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),
'is_closed' => $crmData['isOpen'] !== true,
'is_won' => strtolower($crmData['status']) === 'placed',
'stage_id' => $stage->id,
'record_type_id' => null,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importAccount($crmData): Account
{
$countryCode = $domain = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$name = $crmData['name'] ?? 'Unknown';
if ($crmData['companyURL'] !== null) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$data = [
'team_id' => $this->team->id,
'user_id' => null,
'owner_id' => null,
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Account::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'country_code' => $countryCode,
'domain' => $domain,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importLead($crmData): ?Lead
{
// Get the current stage.
$stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);
}
// If we have no way of importing this, just return null :(
if ($stage === null) {
return null;
}
$countryCode = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$mobilePhone = $phone = $email = null;
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$company = 'Unknown';
if (empty($crmData['companyName']) === false) {
$companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];
$company = mb_strimwidth($companyName, 0, 191);
}
$domain = null;
if (empty($crmData['companyURL']) === false) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'company' => $company,
'domain' => $domain,
'name' => mb_strimwidth($crmData['name'], 0, 191),
'title' => mb_strimwidth($crmData['occupation'], 0, 128),
'email' => mb_strimwidth($email, 0, 80),
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Lead::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'stage_id' => $stage->id,
'country_code' => $countryCode,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
/**
* @throws ApplicationException
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhContacts = $this->client->get('search/ClientContact', $params);
foreach ($bhContacts['data'] as $bhContact) {
// Only sync if previously imported.
if ($this->hasContact($bhContact['id'])) {
$this->importContact($bhContact);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategies = $strategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
$total = 0;
$count = 0;
$offset = 0;
try {
$bhOpportunities = [];
foreach ($strategies as $syncStrategy) {
$opportunitiesData = $syncStrategy->fetchOpportunities($parameters);
$total = (int) ($opportunitiesData['total'] ?? 0);
$count = (int) ($opportunitiesData['count'] ?? 0);
$offset = (int) ($opportunitiesData['start'] ?? 0);
$bhOpportunities[] = $opportunitiesData['data'] ?? [];
}
$bhOpportunities = array_merge(...$bhOpportunities);
foreach ($bhOpportunities as $bhOpportunity) {
$this->importOpportunity($bhOpportunity);
$syncCount++;
}
} catch (\Exception $exception) {
$this->logger->info('Failed to sync opportunities', [
'params' => $parameters,
'exception' => $exception->getMessage(),
]);
}
// only log if there are one sync strategy
if (count($strategies) === 1 && $total > $count + $offset) {
$this->logger->info('[Bullhorn] Sync Opportunities - count warning', [
'team_id' => $this->team->getId(),
'total' => $total,
'count' => $count,
'offset' => $offset,
]);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhAccounts = $this->client->get('search/ClientCorporation', $params);
foreach ($bhAccounts['data'] as $bhAccount) {
// Only sync if previously imported.
if ($this->hasAccount($bhAccount['id'])) {
$this->importAccount($bhAccount);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhLeads = $this->client->get('search/Candidate', $params);
if ($bhLeads === null) {
return $syncCount;
}
foreach ($bhLeads['data'] as $bhLead) {
// Only sync if previously imported.
if ($this->hasLead($bhLead['id'])) {
$this->importLead($bhLead);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncContact(string $crmId): ?Contact
{
try {
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importContact($data['data']);
}
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategy = $strategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
try {
$data = $strategy->fetchOpportunities(['crm_id' => $crmId]);
} catch (HttpNotFoundException $exception) {
$this->logger->info('[Bullhorn] Opportunity not found', [
'crm_id' => $crmId,
'reason' => $exception->getMessage(),
]);
}
return $this->importOpportunity($data['data'] ?? []);
}
public function syncAccount(string $crmId): ?Account
{
try {
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importAccount($data['data']);
}
public function syncLead(string $crmId): ?Lead
{
try {
$data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importLead($data['data']);
}
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$missingStage = null;
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
foreach ($types as $type) {
$resource = $this->convertObjectTypeToResource($type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => 'status',
'meta' => 'full',
]);
$missingStage = null;
if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {
throw new \UnexpectedValueException('Invalid response from Bullhorn API');
}
// Upsert all stages for the team.
foreach ($entity['fields'][0]['options'] as $i => $option) {
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $option['value'],
'type' => $type,
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($option['value'], 0, 50),
'label' => mb_strimwidth($option['label'], 0, 191),
'sequence' => $i,
'is_selectable' => 1,
]);
if ($missingStageName && $missingStageName === $option['value']) {
$missingStage = $stage;
}
}
if ($missingStageName && $missingStage === null) {
// If they requested a stage that still doesn't exist, it must be inactive so lazy create it.
$missingStage = $this->config->stages()->create([
'team_id' => $this->team->id,
'crm_provider_id' => Uuid::uuid4(),
'name' => mb_strimwidth($missingStageName, 0, 50),
'label' => mb_strimwidth($missingStageName, 0, 191),
'type' => $type,
'sequence' => 0,
'is_selectable' => 0,
]);
}
}
return $missingStage;
}
public function syncOrganization(): void
{
// There appears to be nothing we can sync/map to.
}
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$data = \Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {
$result = [];
try {
$objects = $this->client->get('find', [
'query' => $name,
'meta' => 'basic',
'countPerEntity' => $count,
]);
} catch (\GuzzleHttp\Exception\ServerException $exception) {
throw new ServiceUnavailableException($exception->getMessage());
}
foreach ($objects['data'] as $object) {
try {
$prospectType = $this->convertResourceToObjectType($object['entityType']);
} catch (\UnexpectedValueException $exception) {
// We don't support this, so skip it.
continue;
}
$record = [
'crmId' => $object['entityId'],
'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),
'prospectType' => $prospectType,
'phoneNumbers' => [],
];
// Unfortunately we need to go and query each entity itself to get the data we need.
switch ($object['entityType']) {
case self::ENTITY_ACCOUNT:
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['industry'] = $entity['industryList'];
if (empty($entity['phone']) === false) {
$record['phoneNumbers'][] = [
'number' => $entity['phone'],
'nationalFormat' => phone_national(null, $entity['phone']),
'type' => 'phone',
];
}
break;
case self::ENTITY_CONTACT:
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
case self::ENTITY_LEAD:
$bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);
$entity = $bhData['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['companyName'];
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
default:
// We are not interested in this entity type so skip it.
continue 2;
}
$result[] = $record;
}
return $result;
});
return $data;
}
public function getClient(): BullhornClientInterface
{
return $this->client;
}
private function getFieldsAsString(array $fields)
{
return implode(', ', $fields);
}
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),
];
$onlyOpen = true;
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort'] = '-dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort'] = '+dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
$onlyOpen = false;
}
if ($onlyOpen) {
$where .= ' AND isOpen: true';
}
$params['query'] = $where;
$bhOpportunities = $this->client->get('search/JobOrder', $params);
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
foreach ($bhOpportunities['data'] as $bhOpportunity) {
$stage = $this->config
->stages()
->where('crm_provider_id', $bhOpportunity['status'])
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);
}
$record = [
'crmId' => $bhOpportunity['id'],
'name' => $bhOpportunity['title'],
'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),
'won' => strtolower($bhOpportunity['status']) === 'placed',
'closed' => $bhOpportunity['isOpen'] !== true,
'stage' => [
'id' => $stage->id_string,
'name' => $stage->name,
],
'recordType' => [],
];
if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = [];
// For now it has not been agreed on how to implement this e.g. appointments or tasks?
return [];
if ($objectType === 'account' && $opportunityId === null) {
// You cannot attach tasks to only accounts.
return [];
}
// Query should default to any open task.
$where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;
// If we are also going to check on a specific job order, set that up.
if ($opportunityId) {
$where .= ' OR JobOrder: ' . (int) $opportunityId;
}
$where .= ')';
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::TASK_FIELDS),
'query' => $where,
];
$bhTasks = $this->client->get('search/Task', $params);
foreach ($bhTasks['data'] as $bhTask) {
$data[] = [
'crmId' => $bhTask['id'],
'subject' => $bhTask['subject'],
'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),
'type' => null,
];
}
return $data;
}
/**
* @url [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] CrmException
* @throws DomainException
*/
private function buildNotePayload(Activity $activity): Activity
{
if ($activity->hasActivityType() === false) {
throw new DomainException('[Bullhorn] No activity type assigned');
}
$action = $this->getCrmType($activity->getActivityType());
if ($action === null) {
throw new DomainException('[Bullhorn] No mapped CRM type for "' . $activity->category->name . '"');
}
if ($activity->lead_id === null && $activity->contact_id === null) {
throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');
}
$payload = [
'comments' => $this->generateActivityDescription($activity),
'action' => $action->value,
'commentingPerson' => [
'id' => (int) $this->profile->crm_provider_id,
'type' => 'CorporateUser',
],
'externalID' => $activity->id_string,
'minutesSpent' => $activity->duration,
'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),
];
if ($activity->lead_id) {
$payload['personReference'] = [
'id' => (int) $activity->lead->crm_provider_id,
'type' => 'Candidate',
];
}
if ($activity->contact_id) {
$payload['personReference'] = [
'id' => (int) $activity->contact->crm_provider_id,
'type' => 'ClientContact',
];
}
if ($activity->opportunity_id) {
$payload['jobOrders'] = [
'replaceAll' => [
(int) $activity->opportunity->crm_provider_id,
],
];
}
$bhActivity = $this->client->put('entity/Note', $payload);
$activity->crm_provider_id = $bhActivity['changedEntityId'];
$activity->save();
return $activity;
}
private function generateActivityDescription(Activity $activity): string
{
$description = '';
switch ($activity->type) {
case Activity::TYPE_SOFTPHONE:
case Activity::TYPE_SOFTPHONE_INBOUND:
case Activity::TYPE_CONFERENCE:
if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
// Dialer calls have no native field for the subject.
if ($activity->title) {
$description .= sprintf(
'<p><span style="font-size: 16px; line-height: 19.2px;">%s</span></p>',
$activity->title,
);
}
// Conference meetings log duration into a distinct field, so log this in the main text.
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Call Duration: %s</span></p>',
$activity->duration_for_humans,
);
// Tell them which number was dialed.
if ($activity->to) {
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Dialed: %s</span></p>',
$activity->to->phone_number,
);
}
$description .= '<p></p>';
}
if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.66456115,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.67586434,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.6871675,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.7150931,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.72639626,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.73769945,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"2","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"13","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Bullhorn;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\BullhornInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\ApplicationException;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\DomainException;\nuse Jiminny\\Exceptions\\HttpBadRequestException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\ServiceUnavailableException;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\UserRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\nuse Ramsey\\Uuid\\Uuid;\n\nclass BullhornService extends BaseService implements\n BullhornInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const string ENTITY_LEAD = 'Candidate';\n private const string ENTITY_OPPORTUNITY = 'JobOrder';\n private const string ENTITY_ACCOUNT = 'ClientCorporation';\n private const string ENTITY_CONTACT = 'ClientContact';\n private const string ENTITY_ACTIVITY = 'Note';\n\n private const array OPPORTUNITY_FIELDS = [\n 'id',\n 'owner',\n 'status',\n 'title',\n 'salary',\n 'salaryUnit',\n 'payRate',\n 'isOpen',\n 'employmentType',\n 'dateClosed',\n 'startDate',\n 'dateLastModified',\n 'dateAdded',\n 'clientCorporation',\n 'correlatedCustomText10', // currency\n ];\n\n private const array TASK_FIELDS = [\n 'id',\n 'comments',\n 'dateAdded',\n 'dateLastModified',\n 'externalID',\n 'isDeleted',\n 'corporateUsers',\n 'clientContacts',\n 'commentingPerson',\n 'candidates',\n 'jobOrder',\n 'minutesSpent',\n 'action',\n ];\n\n private const array LEAD_FIELDS = [\n 'id',\n 'name',\n 'owner',\n 'occupation',\n 'companyName',\n 'companyURL',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'workPhone',\n 'status',\n 'address',\n 'dateAdded',\n 'dateLastModified',\n ];\n\n private const array CONTACT_FIELDS = [\n 'id',\n 'name',\n 'occupation',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'address',\n 'clientCorporation',\n 'dateAdded',\n 'owner',\n ];\n\n private const array ACCOUNT_FIELDS = [\n 'id',\n 'name',\n 'phone',\n 'industryList',\n 'address',\n 'companyURL',\n 'dateAdded',\n ];\n\n public function __construct(\n BullhornClientInterface $client,\n private readonly UserRepository $userRepository,\n private readonly ProspectPhotoPathService $prospectPhotoPathService\n ) {\n parent::__construct();\n\n $this->client = $client;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);\n }\n\n public function getDisplayName(): string\n {\n return 'Bullhorn';\n }\n\n public function createTranscriptNotes(Activity $activity): void\n {\n // Not done until a customer requests it.\n }\n\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n 'task',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))\n );\n\n if (! empty($changedFields)) {\n $fields = implode(',', $newFields);\n Log::debug(\n sprintf(\n '%s fields changed from %s to: %s',\n ucfirst($fieldType),\n $this->profile->{$fieldType . '_fields'},\n $fields,\n ),\n );\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (\\Exception $exception) {\n \\Log::error('No access to ' . $fieldType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n //parent::OBJECT_ACCOUNT,\n //parent::OBJECT_CONTACT,\n //parent::OBJECT_OPPORTUNITY,\n //parent::OBJECT_LEAD,\n ];\n }\n\n protected function getFields(string $crmObject): array\n {\n $fields = [];\n foreach ($this->getObjectFields($crmObject) as $row) {\n $fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];\n }\n\n return $fields;\n }\n\n private function getObjectFields(string $objectType): array\n {\n $entityType = $this->convertObjectTypeToResource($objectType);\n\n return Cache::remember(\n key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,\n ttl: 60 * 60,\n callback: function () use ($entityType) {\n $entity = $this->client->get('meta/' . $entityType, [\n 'fields' => '*',\n ]);\n\n return $entity['fields'];\n },\n );\n }\n\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n $defaultFields = FieldDefinitions::defaultFields();\n\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n\n return $fields;\n }\n\n public function getDefaultActivityField(string $activityType): Field\n {\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'action',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n // We are not yet supporting follow-ups for this system.\n return [];\n }\n\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return $fieldValue;\n }\n\n public function syncField(Field $field): void\n {\n $resource = $this->convertObjectTypeToResource($field->object_type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => $field->crm_provider_id,\n 'meta' => 'full',\n ]);\n\n $bhField = $entity['fields'][0];\n\n $isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);\n $description = null;\n if (empty($bhField['description']) === false) {\n $description = mb_strimwidth($bhField['description'], 0, 191);\n }\n\n $label = 'Unknown';\n if (empty($bhField['label']) === false) {\n $label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);\n }\n\n $field->length = $bhField['maxLength'] ?? null;\n $field->is_mandatory = $isMandatory;\n $field->description = $description;\n $field->label = $label;\n $field->type = $this->convertFieldType(\n $bhField['dataType'] ?? null,\n $bhField['dataSpecialization'] ?? null,\n $bhField['inputType'] ?? null\n );\n\n $field->save();\n\n if (empty($bhField['options']) === false) {\n $values = [];\n\n // Import all values.\n foreach ($bhField['options'] as $i => $option) {\n $values[] = [\n 'value' => $option['value'],\n 'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),\n 'sequence' => $i,\n ];\n }\n\n // Take the existing set of field values.\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n // For all current values, upsert the field.\n $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n $key = array_search($value['value'], $fieldsToPurge, false);\n if ($key !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n }\n }\n\n public function importPicklistValues(Field $field): array\n {\n // Taken care of in syncField.\n return [];\n }\n\n private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string\n {\n if ($type === null) {\n return Field::TYPE_UNSUPPORTED;\n }\n\n $type = strtolower($type);\n $specialization = strtolower($specialization);\n $inputType = strtolower($inputType);\n\n switch ($type) {\n case 'boolean':\n return Field::TYPE_BOOLEAN;\n\n case 'integer':\n switch ($specialization) {\n case 'integer':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'bigdecimal':\n switch ($specialization) {\n case 'money':\n return Field::TYPE_CURRENCY;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'double':\n switch ($specialization) {\n case 'float':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'timestamp':\n switch ($specialization) {\n case 'date':\n return Field::TYPE_DATE;\n case 'time':\n return Field::TYPE_TIME;\n case 'datetime':\n return Field::TYPE_DATETIME;\n default:\n return Field::TYPE_DATE;\n }\n\n // no break\n case 'string':\n switch ($inputType) {\n case 'textarea':\n return Field::TYPE_TEXTAREA;\n case 'select':\n return Field::TYPE_PICKLIST;\n default:\n return Field::TYPE_TEXT;\n }\n\n // no break\n default:\n // This is not actually a supported field.\n return Field::TYPE_UNSUPPORTED;\n }\n }\n\n private function importContact($crmData): Contact\n {\n $account = $mobilePhone = $phone = $email = null;\n if (empty($crmData['clientCorporation']) === false) {\n $account = $this->team\n ->accounts()\n ->where('crm_provider_id', $crmData['clientCorporation']['id'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n }\n\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => $crmData['name'],\n 'email' => $email,\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'title' => $crmData['occupation'],\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Contact::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n if ($crmData['clientCorporation']['id']) {\n $account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n } else {\n // If there is nothing to associate this with, don't import it.\n return null;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $stage = $this->config->stages()\n ->where('crm_provider_id', $crmData['status'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => mb_strimwidth($crmData['title'], 0, 128),\n 'value' => $crmData['salary'] ?? $crmData['payRate'],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),\n 'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),\n 'is_closed' => $crmData['isOpen'] !== true,\n 'is_won' => strtolower($crmData['status']) === 'placed',\n 'stage_id' => $stage->id,\n 'record_type_id' => null,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importAccount($crmData): Account\n {\n $countryCode = $domain = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $name = $crmData['name'] ?? 'Unknown';\n\n if ($crmData['companyURL'] !== null) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => null,\n 'owner_id' => null,\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Account::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'country_code' => $countryCode,\n 'domain' => $domain,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importLead($crmData): ?Lead\n {\n // Get the current stage.\n $stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);\n }\n\n // If we have no way of importing this, just return null :(\n if ($stage === null) {\n return null;\n }\n\n $countryCode = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $mobilePhone = $phone = $email = null;\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $company = 'Unknown';\n if (empty($crmData['companyName']) === false) {\n $companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];\n $company = mb_strimwidth($companyName, 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['companyURL']) === false) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'company' => $company,\n 'domain' => $domain,\n 'name' => mb_strimwidth($crmData['name'], 0, 191),\n 'title' => mb_strimwidth($crmData['occupation'], 0, 128),\n 'email' => mb_strimwidth($email, 0, 80),\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Lead::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'stage_id' => $stage->id,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhContacts = $this->client->get('search/ClientContact', $params);\n\n foreach ($bhContacts['data'] as $bhContact) {\n // Only sync if previously imported.\n if ($this->hasContact($bhContact['id'])) {\n $this->importContact($bhContact);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategies = $strategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n $total = 0;\n $count = 0;\n $offset = 0;\n\n try {\n $bhOpportunities = [];\n foreach ($strategies as $syncStrategy) {\n $opportunitiesData = $syncStrategy->fetchOpportunities($parameters);\n $total = (int) ($opportunitiesData['total'] ?? 0);\n $count = (int) ($opportunitiesData['count'] ?? 0);\n $offset = (int) ($opportunitiesData['start'] ?? 0);\n $bhOpportunities[] = $opportunitiesData['data'] ?? [];\n }\n\n $bhOpportunities = array_merge(...$bhOpportunities);\n\n foreach ($bhOpportunities as $bhOpportunity) {\n $this->importOpportunity($bhOpportunity);\n $syncCount++;\n }\n } catch (\\Exception $exception) {\n $this->logger->info('Failed to sync opportunities', [\n 'params' => $parameters,\n 'exception' => $exception->getMessage(),\n ]);\n }\n\n // only log if there are one sync strategy\n if (count($strategies) === 1 && $total > $count + $offset) {\n $this->logger->info('[Bullhorn] Sync Opportunities - count warning', [\n 'team_id' => $this->team->getId(),\n 'total' => $total,\n 'count' => $count,\n 'offset' => $offset,\n ]);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhAccounts = $this->client->get('search/ClientCorporation', $params);\n\n foreach ($bhAccounts['data'] as $bhAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($bhAccount['id'])) {\n $this->importAccount($bhAccount);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhLeads = $this->client->get('search/Candidate', $params);\n if ($bhLeads === null) {\n return $syncCount;\n }\n\n foreach ($bhLeads['data'] as $bhLead) {\n // Only sync if previously imported.\n if ($this->hasLead($bhLead['id'])) {\n $this->importLead($bhLead);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n\n public function syncContact(string $crmId): ?Contact\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importContact($data['data']);\n }\n\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategy = $strategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n try {\n $data = $strategy->fetchOpportunities(['crm_id' => $crmId]);\n } catch (HttpNotFoundException $exception) {\n $this->logger->info('[Bullhorn] Opportunity not found', [\n 'crm_id' => $crmId,\n 'reason' => $exception->getMessage(),\n ]);\n }\n\n return $this->importOpportunity($data['data'] ?? []);\n }\n\n public function syncAccount(string $crmId): ?Account\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importAccount($data['data']);\n }\n\n public function syncLead(string $crmId): ?Lead\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importLead($data['data']);\n }\n\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $missingStage = null;\n\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n\n foreach ($types as $type) {\n $resource = $this->convertObjectTypeToResource($type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => 'status',\n 'meta' => 'full',\n ]);\n\n $missingStage = null;\n\n if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {\n throw new \\UnexpectedValueException('Invalid response from Bullhorn API');\n }\n\n // Upsert all stages for the team.\n foreach ($entity['fields'][0]['options'] as $i => $option) {\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $option['value'],\n 'type' => $type,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($option['value'], 0, 50),\n 'label' => mb_strimwidth($option['label'], 0, 191),\n 'sequence' => $i,\n 'is_selectable' => 1,\n ]);\n\n if ($missingStageName && $missingStageName === $option['value']) {\n $missingStage = $stage;\n }\n }\n\n if ($missingStageName && $missingStage === null) {\n // If they requested a stage that still doesn't exist, it must be inactive so lazy create it.\n $missingStage = $this->config->stages()->create([\n 'team_id' => $this->team->id,\n 'crm_provider_id' => Uuid::uuid4(),\n 'name' => mb_strimwidth($missingStageName, 0, 50),\n 'label' => mb_strimwidth($missingStageName, 0, 191),\n 'type' => $type,\n 'sequence' => 0,\n 'is_selectable' => 0,\n ]);\n }\n }\n\n return $missingStage;\n }\n\n public function syncOrganization(): void\n {\n // There appears to be nothing we can sync/map to.\n }\n\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $data = \\Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {\n $result = [];\n\n try {\n $objects = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => $count,\n ]);\n } catch (\\GuzzleHttp\\Exception\\ServerException $exception) {\n throw new ServiceUnavailableException($exception->getMessage());\n }\n\n foreach ($objects['data'] as $object) {\n try {\n $prospectType = $this->convertResourceToObjectType($object['entityType']);\n } catch (\\UnexpectedValueException $exception) {\n // We don't support this, so skip it.\n continue;\n }\n\n $record = [\n 'crmId' => $object['entityId'],\n 'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),\n 'prospectType' => $prospectType,\n 'phoneNumbers' => [],\n ];\n\n // Unfortunately we need to go and query each entity itself to get the data we need.\n switch ($object['entityType']) {\n case self::ENTITY_ACCOUNT:\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['industry'] = $entity['industryList'];\n if (empty($entity['phone']) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity['phone'],\n 'nationalFormat' => phone_national(null, $entity['phone']),\n 'type' => 'phone',\n ];\n }\n\n break;\n\n case self::ENTITY_CONTACT:\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n case self::ENTITY_LEAD:\n $bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);\n $entity = $bhData['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['companyName'];\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n default:\n // We are not interested in this entity type so skip it.\n continue 2;\n }\n\n $result[] = $record;\n }\n\n return $result;\n });\n\n return $data;\n }\n\n public function getClient(): BullhornClientInterface\n {\n return $this->client;\n }\n\n private function getFieldsAsString(array $fields)\n {\n return implode(', ', $fields);\n }\n\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),\n ];\n\n $onlyOpen = true;\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort'] = '-dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort'] = '+dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n $onlyOpen = false;\n }\n\n if ($onlyOpen) {\n $where .= ' AND isOpen: true';\n }\n\n $params['query'] = $where;\n\n $bhOpportunities = $this->client->get('search/JobOrder', $params);\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n foreach ($bhOpportunities['data'] as $bhOpportunity) {\n $stage = $this->config\n ->stages()\n ->where('crm_provider_id', $bhOpportunity['status'])\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);\n }\n\n $record = [\n 'crmId' => $bhOpportunity['id'],\n 'name' => $bhOpportunity['title'],\n 'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),\n 'won' => strtolower($bhOpportunity['status']) === 'placed',\n 'closed' => $bhOpportunity['isOpen'] !== true,\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n 'recordType' => [],\n ];\n\n if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = [];\n\n // For now it has not been agreed on how to implement this e.g. appointments or tasks?\n return [];\n\n if ($objectType === 'account' && $opportunityId === null) {\n // You cannot attach tasks to only accounts.\n return [];\n }\n\n // Query should default to any open task.\n $where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;\n\n // If we are also going to check on a specific job order, set that up.\n if ($opportunityId) {\n $where .= ' OR JobOrder: ' . (int) $opportunityId;\n }\n\n $where .= ')';\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => $where,\n ];\n\n $bhTasks = $this->client->get('search/Task', $params);\n\n foreach ($bhTasks['data'] as $bhTask) {\n $data[] = [\n 'crmId' => $bhTask['id'],\n 'subject' => $bhTask['subject'],\n 'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),\n 'type' => null,\n ];\n }\n\n return $data;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * ?Lead,\n * ?Account,\n * ?Opportunity,\n * ?Contact,\n * ?Stage,\n * ?string\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $bhObject = $this->client->get('find', [\n 'query' => $email,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember === false) {\n $bhObject = $this->client->get('find', [\n 'query' => $rawPhoneNumber ?? $phone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n if (empty($bhObject['data'])) {\n $nationalPhone = phone_national(null, $rawPhoneNumber ?? $phone);\n $formattedPhone = ltrim($nationalPhone, '+0');\n $bhObject = $this->client->get('find', [\n 'query' => $formattedPhone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n }\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n return null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 3) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = \\Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n $bhObject = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->team->getId() . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n public function saveActivity(Activity $activity): Activity\n {\n\n if ($activity->hasCrmProviderId()) {\n return $activity;\n }\n\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildNotePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n /**\n * @throws CrmException\n * @throws DomainException\n */\n private function buildNotePayload(Activity $activity): Activity\n {\n if ($activity->hasActivityType() === false) {\n throw new DomainException('[Bullhorn] No activity type assigned');\n }\n\n $action = $this->getCrmType($activity->getActivityType());\n if ($action === null) {\n throw new DomainException('[Bullhorn] No mapped CRM type for \"' . $activity->category->name . '\"');\n }\n\n if ($activity->lead_id === null && $activity->contact_id === null) {\n throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');\n }\n\n $payload = [\n 'comments' => $this->generateActivityDescription($activity),\n 'action' => $action->value,\n 'commentingPerson' => [\n 'id' => (int) $this->profile->crm_provider_id,\n 'type' => 'CorporateUser',\n ],\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n 'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),\n ];\n\n if ($activity->lead_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->lead->crm_provider_id,\n 'type' => 'Candidate',\n ];\n }\n\n if ($activity->contact_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->contact->crm_provider_id,\n 'type' => 'ClientContact',\n ];\n }\n\n if ($activity->opportunity_id) {\n $payload['jobOrders'] = [\n 'replaceAll' => [\n (int) $activity->opportunity->crm_provider_id,\n ],\n ];\n }\n\n $bhActivity = $this->client->put('entity/Note', $payload);\n\n $activity->crm_provider_id = $bhActivity['changedEntityId'];\n $activity->save();\n\n return $activity;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = '';\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: %s</span></p>',\n $activity->to->phone_number,\n );\n }\n $description .= '<p></p>';\n }\n\n if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: %s</span></p>',\n $activity->from->phone_number,\n );\n $description .= '<p></p>';\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span>'\n . '</p>';\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span>'\n . '</p>';\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= sprintf(\n '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . '<a href=\"%s\" target=\"_blank\">'\n . 'Review in Jiminny'\n . '</a>'\n . '️</span>'\n . '</p>',\n $playbackUrl,\n );\n }\n\n if ($activity->isTypeConference()) {\n $description .= '<p><strong>Attendees</strong></p><ul>';\n\n // Only include participants that joined.\n $participants = $activity->participants()->ghost(false)->whereNotNull('enter_time')->get();\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->name) {\n $attendee .= $participant->name;\n if ($participant->phone_number) {\n $attendee .= ' (' . $participant->phone_number . ')';\n } elseif ($participant->email) {\n $attendee .= ' (' . $participant->email . ')';\n }\n } else {\n $attendee .= $participant->phone_number;\n }\n\n if ($participant->is_ghost) {\n $attendee .= ' <strong>coach</coach>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $description .= $attendee . '</li>';\n }\n $description .= '</ul>';\n }\n\n if (count($activity->notes) > 0) {\n $description .= '<p><strong>Notes</strong></p>';\n\n foreach ($activity->notes as $note) {\n $time = ($note->time > 3600) ? gmdate('H:i:s', $note->time) : gmdate('i:s', $note->time);\n $description .= '<p>' . $time . ' ' . $note->note . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n if ($activity->summary) {\n $description .= '<p><strong>Summary</strong></p><p>' . $activity->summary . '</p><p></p>';\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n // Use Rich-text formatting.\n $description = sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>%s</strong></span></p>',\n $activity->title,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->description,\n );\n\n break;\n }\n\n return $description;\n }\n\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // Not yet required by current customers.\n return null;\n }\n\n public function updateStage($crmObject, Stage $stage): void\n {\n $objectId = $crmObject->crm_provider_id;\n\n $this->updateRecord($stage->type, $objectId, ['status' => $stage->crm_provider_id]);\n }\n\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $start = 0;\n $payload = [\n 'fields' => 'id,email',\n 'where' => 'isDeleted=false',\n 'count' => 500,\n ];\n\n $payload['start'] = $start;\n $profiles = $this->client->get('query/CorporateUser', $payload);\n\n foreach ($profiles['data'] as $profile) {\n if (empty($profile['email'])) {\n continue;\n }\n\n $user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);\n\n // Only import profiles for users we have locally.\n if ($user) {\n $profile = $user->crmProfile()->updateOrCreate([\n 'crm_configuration_id' => $this->config->id,\n 'crm_provider_id' => $profile['id'],\n ]);\n\n if ($userToSearch && $userToSearch->id === $user->id) {\n return $profile;\n }\n }\n }\n\n return null;\n }\n\n protected function convertCrmData(array $entities, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n $mappedEntities = [];\n foreach ($entities as $entity) {\n if (in_array($entity['entityType'], [self::ENTITY_LEAD, self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n $mappedEntities[] = $entity;\n }\n }\n\n // If there is only one match, sync the data and return the object(s).\n if (count($mappedEntities) === 1) {\n $entity = $mappedEntities[0];\n\n if ($entity['entityType'] === self::ENTITY_LEAD) {\n $lead = $this->syncLead($entity['entityId']);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } elseif (in_array($entity['entityType'], [self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n if ($entity['entityType'] === self::ENTITY_CONTACT) {\n $contact = $this->syncContact($entity['entityId']);\n $account = $contact->account;\n } else {\n $account = $this->syncAccount($entity['entityId']);\n }\n\n if ($contact?->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $bhOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact?->crm_provider_id,\n $userId,\n );\n\n // Take the first opportunity, which will be ordered as priority based on their settings.\n if (! empty($bhOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($bhOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n } catch (Exception) {\n // Nothing to see here.\n }\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n // There doesn't appear to be a way to deeplink to anything on https://app.bullhornstaffing.com.\n return null;\n }\n\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $this->client->post('entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId, $data);\n }\n\n public function getRecord(string $objectType, string $objectId, array $fields = ['id']): array\n {\n return $this->client->get(\n url: 'entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId,\n data: ['fields' => $this->getFieldsAsString($fields)],\n );\n }\n\n private function convertObjectTypeToResource(string $objectType)\n {\n switch ($objectType) {\n case FieldData::OBJECT_OPPORTUNITY:\n return self::ENTITY_OPPORTUNITY;\n\n case FieldData::OBJECT_CONTACT:\n return self::ENTITY_CONTACT;\n\n case FieldData::OBJECT_LEAD:\n return self::ENTITY_LEAD;\n\n case FieldData::OBJECT_ACCOUNT:\n return self::ENTITY_ACCOUNT;\n\n case FieldData::OBJECT_TASK:\n return self::ENTITY_ACTIVITY;\n\n default:\n throw new \\UnexpectedValueException('Unsupported object type \"' . $objectType . '\"');\n }\n }\n\n private function convertResourceToObjectType(string $resource): string\n {\n switch ($resource) {\n case self::ENTITY_OPPORTUNITY:\n return FieldData::OBJECT_OPPORTUNITY;\n\n case self::ENTITY_CONTACT:\n return FieldData::OBJECT_CONTACT;\n\n case self::ENTITY_LEAD:\n return FieldData::OBJECT_LEAD;\n\n case self::ENTITY_ACCOUNT:\n return FieldData::OBJECT_ACCOUNT;\n\n case self::ENTITY_ACTIVITY:\n return FieldData::OBJECT_TASK;\n\n default:\n throw new \\UnexpectedValueException('Unsupported resource \"' . $resource . '\"');\n }\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n // We need to know when it started to determine when to look for related activity.\n if ($activity->hasActualStartTime() === false) {\n return null;\n }\n\n try {\n $bhNote = $this->fetchRelatedActivity($activity);\n if (empty($bhNote)) {\n $this->logger->info('[Bullhorn] No related activity found', [\n 'activity' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $activityType = $this->getPlaybookCategory($this->getPlaybook($activity->user), $bhNote['action']);\n $comments = $bhNote['comments'] . '<br />//<br />' . $this->generateActivityDescription($activity);\n // Now update the Note to contain our data.\n $payload = [\n 'comments' => $comments,\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n ];\n\n $this->logger->info('[Bullhorn] updating related activity', [\n 'activity' => $activity->getUuid(),\n 'activityType' => $activityType->id ?? null,\n ]);\n\n $this->client->post('entity/Note/' . $bhNote['id'], $payload);\n\n $playbookCategoryId = null;\n if ($activity->getCategory() !== null) {\n $playbookCategoryId = $activity->getCategory()->getId();\n }\n\n // Update our activity to reflect the remote data.\n $activity->update([\n 'crm_provider_id' => $bhNote['id'],\n 'summary' => $bhNote['comments'],\n 'playbook_category_id' => $activityType->id ?? $playbookCategoryId,\n ]);\n\n return $activity;\n } catch (\\Exception $exception) {\n \\Sentry::captureException($exception);\n\n throw $exception;\n }\n }\n\n /**\n * Returns the most recently modified note within time range (if any).\n *\n * @return array A Note record from Bullhorn.\n */\n public function fetchRelatedActivity(Activity $activity): array\n {\n $from = $activity->hasScheduledStartTime()\n ? $activity->getScheduledStartTime()\n : $activity->getActualStartTime();\n $to = $activity->hasActualEndTime()\n ? $activity->getActualEndTime()?->addMinutes(15)\n : $from?->clone()->addMinutes(15);\n\n $filterStatements = [\n 'isDeleted: false',\n '*:* -externalID:[* TO *]', // externalID should be null e.g. we did not already relate it.\n sprintf('commentingPerson: %d', (int) $this->profile->crm_provider_id),\n ];\n\n /**\n * @XXX: Bullhorn does not specify the time zone in their docs. I've found a forum thread in which someone from\n * staff asserts it's UTC, however in my field test I've found it to be GMT-0300 (USA east coast).\n * To make the code immune to such glitches we will add 24h to start/end boundaries and will filter out\n * any excess items in code\n */\n $filterStatements[] = sprintf(\n 'dateLastModified:[%s TO %s]',\n $from?->clone()->subHours(24)->format('YmdHis'),\n $to->clone()->addHours(24)->format('YmdHis'),\n );\n\n if ($activity->lead_id) {\n $filterStatements[] = sprintf('candidateUserID: %d', (int) $activity->lead->crm_provider_id);\n }\n\n if ($activity->contact_id) {\n $filterStatements[] = sprintf('clientContactUserID: %d', (int) $activity->contact->crm_provider_id);\n }\n\n // if there is no contact or lead associated to the activity exit\n if ($activity->contact_id === null && $activity->lead_id === null) {\n return [];\n }\n\n $params = [\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => implode(' AND ', $filterStatements),\n 'sort' => '-dateLastModified',\n ];\n\n $bhNotes = $this->client->get('search/Note', $params);\n\n $startStamp = $from?->getTimestamp() * 1000;\n $endStamp = $to->getTimestamp() * 1000;\n\n $filteredNotes = array_values(\n array_filter(\n $bhNotes['data'],\n static fn (array $bhNote): bool\n => $bhNote['dateLastModified'] >= $startStamp && $startStamp <= $endStamp,\n ),\n );\n\n return ! empty($filteredNotes) ? array_shift($filteredNotes) : [];\n }\n\n /**\n * Select how to create the date out of the Bullhorn payload.\n * Do not allow dates beyond 9999-12-31 (max mysql DATE)\n */\n private function filterOutOfBoundDates(string $rawDateCandidate): ?Carbon\n {\n if (strlen($rawDateCandidate) > 12) {\n // A unix timestamp represented with more than 12 digits i\n // s definitely including milliseconds\n $dateFormatted = Carbon::createFromTimestampMs($rawDateCandidate);\n } else {\n $dateFormatted = Carbon::createFromTimestamp($rawDateCandidate);\n }\n\n $minDate = Carbon::createFromFormat('Y-m-d', '2000-01-01');\n if ($dateFormatted->lt($minDate)) {\n return null;\n }\n\n $maxDate = Carbon::createFromFormat('Y-m-d', '9999-12-31');\n if ($dateFormatted->gt($maxDate)) {\n $this->logger->warning('[Bullhorn] An out of bound date is provided', [\n 'date' => $dateFormatted,\n 'rawDate' => $rawDateCandidate,\n ]);\n\n return $maxDate;\n }\n\n return $dateFormatted;\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n $note = $this->getRecord('Note', $crmProviderId, ['id', 'isDeleted']);\n\n return ! empty($note) && ($note['isDeleted'] ?? false) === false;\n } catch (HttpNotFoundException|HttpBadRequestException) {\n // Note not found in CRM - this is expected and permanent\n $this->logger->info('[Bullhorn] Note not found during verification', [\n 'note_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Bullhorn;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\BullhornInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\ApplicationException;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\DomainException;\nuse Jiminny\\Exceptions\\HttpBadRequestException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Exceptions\\ServiceUnavailableException;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\UserRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\nuse Ramsey\\Uuid\\Uuid;\n\nclass BullhornService extends BaseService implements\n BullhornInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const string ENTITY_LEAD = 'Candidate';\n private const string ENTITY_OPPORTUNITY = 'JobOrder';\n private const string ENTITY_ACCOUNT = 'ClientCorporation';\n private const string ENTITY_CONTACT = 'ClientContact';\n private const string ENTITY_ACTIVITY = 'Note';\n\n private const array OPPORTUNITY_FIELDS = [\n 'id',\n 'owner',\n 'status',\n 'title',\n 'salary',\n 'salaryUnit',\n 'payRate',\n 'isOpen',\n 'employmentType',\n 'dateClosed',\n 'startDate',\n 'dateLastModified',\n 'dateAdded',\n 'clientCorporation',\n 'correlatedCustomText10', // currency\n ];\n\n private const array TASK_FIELDS = [\n 'id',\n 'comments',\n 'dateAdded',\n 'dateLastModified',\n 'externalID',\n 'isDeleted',\n 'corporateUsers',\n 'clientContacts',\n 'commentingPerson',\n 'candidates',\n 'jobOrder',\n 'minutesSpent',\n 'action',\n ];\n\n private const array LEAD_FIELDS = [\n 'id',\n 'name',\n 'owner',\n 'occupation',\n 'companyName',\n 'companyURL',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'workPhone',\n 'status',\n 'address',\n 'dateAdded',\n 'dateLastModified',\n ];\n\n private const array CONTACT_FIELDS = [\n 'id',\n 'name',\n 'occupation',\n 'mobile',\n 'phone',\n 'phone2',\n 'phone3',\n 'address',\n 'clientCorporation',\n 'dateAdded',\n 'owner',\n ];\n\n private const array ACCOUNT_FIELDS = [\n 'id',\n 'name',\n 'phone',\n 'industryList',\n 'address',\n 'companyURL',\n 'dateAdded',\n ];\n\n public function __construct(\n BullhornClientInterface $client,\n private readonly UserRepository $userRepository,\n private readonly ProspectPhotoPathService $prospectPhotoPathService\n ) {\n parent::__construct();\n\n $this->client = $client;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);\n }\n\n public function getDisplayName(): string\n {\n return 'Bullhorn';\n }\n\n public function createTranscriptNotes(Activity $activity): void\n {\n // Not done until a customer requests it.\n }\n\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n 'task',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))\n );\n\n if (! empty($changedFields)) {\n $fields = implode(',', $newFields);\n Log::debug(\n sprintf(\n '%s fields changed from %s to: %s',\n ucfirst($fieldType),\n $this->profile->{$fieldType . '_fields'},\n $fields,\n ),\n );\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (\\Exception $exception) {\n \\Log::error('No access to ' . $fieldType . ' object, skipping...');\n\n // XXX: should we log this fact somewhere?\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n //parent::OBJECT_ACCOUNT,\n //parent::OBJECT_CONTACT,\n //parent::OBJECT_OPPORTUNITY,\n //parent::OBJECT_LEAD,\n ];\n }\n\n protected function getFields(string $crmObject): array\n {\n $fields = [];\n foreach ($this->getObjectFields($crmObject) as $row) {\n $fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];\n }\n\n return $fields;\n }\n\n private function getObjectFields(string $objectType): array\n {\n $entityType = $this->convertObjectTypeToResource($objectType);\n\n return Cache::remember(\n key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,\n ttl: 60 * 60,\n callback: function () use ($entityType) {\n $entity = $this->client->get('meta/' . $entityType, [\n 'fields' => '*',\n ]);\n\n return $entity['fields'];\n },\n );\n }\n\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n $defaultFields = FieldDefinitions::defaultFields();\n\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n\n return $fields;\n }\n\n public function getDefaultActivityField(string $activityType): Field\n {\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'action',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n // We are not yet supporting follow-ups for this system.\n return [];\n }\n\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return $fieldValue;\n }\n\n public function syncField(Field $field): void\n {\n $resource = $this->convertObjectTypeToResource($field->object_type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => $field->crm_provider_id,\n 'meta' => 'full',\n ]);\n\n $bhField = $entity['fields'][0];\n\n $isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);\n $description = null;\n if (empty($bhField['description']) === false) {\n $description = mb_strimwidth($bhField['description'], 0, 191);\n }\n\n $label = 'Unknown';\n if (empty($bhField['label']) === false) {\n $label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);\n }\n\n $field->length = $bhField['maxLength'] ?? null;\n $field->is_mandatory = $isMandatory;\n $field->description = $description;\n $field->label = $label;\n $field->type = $this->convertFieldType(\n $bhField['dataType'] ?? null,\n $bhField['dataSpecialization'] ?? null,\n $bhField['inputType'] ?? null\n );\n\n $field->save();\n\n if (empty($bhField['options']) === false) {\n $values = [];\n\n // Import all values.\n foreach ($bhField['options'] as $i => $option) {\n $values[] = [\n 'value' => $option['value'],\n 'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),\n 'sequence' => $i,\n ];\n }\n\n // Take the existing set of field values.\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n // For all current values, upsert the field.\n $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n $key = array_search($value['value'], $fieldsToPurge, false);\n if ($key !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n }\n }\n\n public function importPicklistValues(Field $field): array\n {\n // Taken care of in syncField.\n return [];\n }\n\n private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string\n {\n if ($type === null) {\n return Field::TYPE_UNSUPPORTED;\n }\n\n $type = strtolower($type);\n $specialization = strtolower($specialization);\n $inputType = strtolower($inputType);\n\n switch ($type) {\n case 'boolean':\n return Field::TYPE_BOOLEAN;\n\n case 'integer':\n switch ($specialization) {\n case 'integer':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'bigdecimal':\n switch ($specialization) {\n case 'money':\n return Field::TYPE_CURRENCY;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'double':\n switch ($specialization) {\n case 'float':\n return Field::TYPE_NUMBER;\n default:\n return Field::TYPE_NUMBER;\n }\n\n // no break\n case 'timestamp':\n switch ($specialization) {\n case 'date':\n return Field::TYPE_DATE;\n case 'time':\n return Field::TYPE_TIME;\n case 'datetime':\n return Field::TYPE_DATETIME;\n default:\n return Field::TYPE_DATE;\n }\n\n // no break\n case 'string':\n switch ($inputType) {\n case 'textarea':\n return Field::TYPE_TEXTAREA;\n case 'select':\n return Field::TYPE_PICKLIST;\n default:\n return Field::TYPE_TEXT;\n }\n\n // no break\n default:\n // This is not actually a supported field.\n return Field::TYPE_UNSUPPORTED;\n }\n }\n\n private function importContact($crmData): Contact\n {\n $account = $mobilePhone = $phone = $email = null;\n if (empty($crmData['clientCorporation']) === false) {\n $account = $this->team\n ->accounts()\n ->where('crm_provider_id', $crmData['clientCorporation']['id'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n }\n\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => $crmData['name'],\n 'email' => $email,\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'title' => $crmData['occupation'],\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Contact::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n if ($crmData['clientCorporation']['id']) {\n $account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['clientCorporation']['id']);\n }\n } else {\n // If there is nothing to associate this with, don't import it.\n return null;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $stage = $this->config->stages()\n ->where('crm_provider_id', $crmData['status'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'name' => mb_strimwidth($crmData['title'], 0, 128),\n 'value' => $crmData['salary'] ?? $crmData['payRate'],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),\n 'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),\n 'is_closed' => $crmData['isOpen'] !== true,\n 'is_won' => strtolower($crmData['status']) === 'placed',\n 'stage_id' => $stage->id,\n 'record_type_id' => null,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importAccount($crmData): Account\n {\n $countryCode = $domain = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $name = $crmData['name'] ?? 'Unknown';\n\n if ($crmData['companyURL'] !== null) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => null,\n 'owner_id' => null,\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Account::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'country_code' => $countryCode,\n 'domain' => $domain,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function importLead($crmData): ?Lead\n {\n // Get the current stage.\n $stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();\n if ($stage === null) {\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);\n }\n\n // If we have no way of importing this, just return null :(\n if ($stage === null) {\n return null;\n }\n\n $countryCode = null;\n if (empty($crmData['address']['countryCode'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);\n }\n\n $mobilePhone = $phone = $email = null;\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n if ($type === 'mobile') {\n $mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);\n } else {\n $phone = parsePhoneNumber($countryCode, $crmData[$type]);\n }\n\n break;\n }\n\n foreach (['email', 'email1', 'email2'] as $type) {\n if (empty($crmData[$type])) {\n continue;\n }\n\n $email = mb_strimwidth($crmData[$type], 0, 80);\n\n break;\n }\n\n $company = 'Unknown';\n if (empty($crmData['companyName']) === false) {\n $companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];\n $company = mb_strimwidth($companyName, 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['companyURL']) === false) {\n $domain = mb_strimwidth($crmData['companyURL'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['owner']['id'],\n 'company' => $company,\n 'domain' => $domain,\n 'name' => mb_strimwidth($crmData['name'], 0, 191),\n 'title' => mb_strimwidth($crmData['occupation'], 0, 128),\n 'email' => mb_strimwidth($email, 0, 80),\n 'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),\n 'ext' => $phone['ext'] ?? null,\n 'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Lead::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name'] ?? 'Unknown'\n ),\n 'stage_id' => $stage->id,\n 'country_code' => $countryCode,\n 'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),\n ];\n\n return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhContacts = $this->client->get('search/ClientContact', $params);\n\n foreach ($bhContacts['data'] as $bhContact) {\n // Only sync if previously imported.\n if ($this->hasContact($bhContact['id'])) {\n $this->importContact($bhContact);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategies = $strategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n $total = 0;\n $count = 0;\n $offset = 0;\n\n try {\n $bhOpportunities = [];\n foreach ($strategies as $syncStrategy) {\n $opportunitiesData = $syncStrategy->fetchOpportunities($parameters);\n $total = (int) ($opportunitiesData['total'] ?? 0);\n $count = (int) ($opportunitiesData['count'] ?? 0);\n $offset = (int) ($opportunitiesData['start'] ?? 0);\n $bhOpportunities[] = $opportunitiesData['data'] ?? [];\n }\n\n $bhOpportunities = array_merge(...$bhOpportunities);\n\n foreach ($bhOpportunities as $bhOpportunity) {\n $this->importOpportunity($bhOpportunity);\n $syncCount++;\n }\n } catch (\\Exception $exception) {\n $this->logger->info('Failed to sync opportunities', [\n 'params' => $parameters,\n 'exception' => $exception->getMessage(),\n ]);\n }\n\n // only log if there are one sync strategy\n if (count($strategies) === 1 && $total > $count + $offset) {\n $this->logger->info('[Bullhorn] Sync Opportunities - count warning', [\n 'team_id' => $this->team->getId(),\n 'total' => $total,\n 'count' => $count,\n 'offset' => $offset,\n ]);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhAccounts = $this->client->get('search/ClientCorporation', $params);\n\n foreach ($bhAccounts['data'] as $bhAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($bhAccount['id'])) {\n $this->importAccount($bhAccount);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n /**\n * @throws ApplicationException\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),\n 'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',\n ];\n\n try {\n $bhLeads = $this->client->get('search/Candidate', $params);\n if ($bhLeads === null) {\n return $syncCount;\n }\n\n foreach ($bhLeads['data'] as $bhLead) {\n // Only sync if previously imported.\n if ($this->hasLead($bhLead['id'])) {\n $this->importLead($bhLead);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);\n }\n\n return $syncCount;\n }\n\n\n public function syncContact(string $crmId): ?Contact\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importContact($data['data']);\n }\n\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $strategy = $strategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n try {\n $data = $strategy->fetchOpportunities(['crm_id' => $crmId]);\n } catch (HttpNotFoundException $exception) {\n $this->logger->info('[Bullhorn] Opportunity not found', [\n 'crm_id' => $crmId,\n 'reason' => $exception->getMessage(),\n ]);\n }\n\n return $this->importOpportunity($data['data'] ?? []);\n }\n\n public function syncAccount(string $crmId): ?Account\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importAccount($data['data']);\n }\n\n public function syncLead(string $crmId): ?Lead\n {\n try {\n $data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);\n } catch (HttpNotFoundException $exception) {\n return null;\n }\n\n return $this->importLead($data['data']);\n }\n\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $missingStage = null;\n\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n\n foreach ($types as $type) {\n $resource = $this->convertObjectTypeToResource($type);\n $entity = $this->client->get('meta/' . $resource, [\n 'fields' => 'status',\n 'meta' => 'full',\n ]);\n\n $missingStage = null;\n\n if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {\n throw new \\UnexpectedValueException('Invalid response from Bullhorn API');\n }\n\n // Upsert all stages for the team.\n foreach ($entity['fields'][0]['options'] as $i => $option) {\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $option['value'],\n 'type' => $type,\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($option['value'], 0, 50),\n 'label' => mb_strimwidth($option['label'], 0, 191),\n 'sequence' => $i,\n 'is_selectable' => 1,\n ]);\n\n if ($missingStageName && $missingStageName === $option['value']) {\n $missingStage = $stage;\n }\n }\n\n if ($missingStageName && $missingStage === null) {\n // If they requested a stage that still doesn't exist, it must be inactive so lazy create it.\n $missingStage = $this->config->stages()->create([\n 'team_id' => $this->team->id,\n 'crm_provider_id' => Uuid::uuid4(),\n 'name' => mb_strimwidth($missingStageName, 0, 50),\n 'label' => mb_strimwidth($missingStageName, 0, 191),\n 'type' => $type,\n 'sequence' => 0,\n 'is_selectable' => 0,\n ]);\n }\n }\n\n return $missingStage;\n }\n\n public function syncOrganization(): void\n {\n // There appears to be nothing we can sync/map to.\n }\n\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $data = \\Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {\n $result = [];\n\n try {\n $objects = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => $count,\n ]);\n } catch (\\GuzzleHttp\\Exception\\ServerException $exception) {\n throw new ServiceUnavailableException($exception->getMessage());\n }\n\n foreach ($objects['data'] as $object) {\n try {\n $prospectType = $this->convertResourceToObjectType($object['entityType']);\n } catch (\\UnexpectedValueException $exception) {\n // We don't support this, so skip it.\n continue;\n }\n\n $record = [\n 'crmId' => $object['entityId'],\n 'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),\n 'prospectType' => $prospectType,\n 'phoneNumbers' => [],\n ];\n\n // Unfortunately we need to go and query each entity itself to get the data we need.\n switch ($object['entityType']) {\n case self::ENTITY_ACCOUNT:\n $data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['industry'] = $entity['industryList'];\n if (empty($entity['phone']) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity['phone'],\n 'nationalFormat' => phone_national(null, $entity['phone']),\n 'type' => 'phone',\n ];\n }\n\n break;\n\n case self::ENTITY_CONTACT:\n $data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);\n $entity = $data['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n case self::ENTITY_LEAD:\n $bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);\n $entity = $bhData['data'];\n\n $record['name'] = $entity['name'];\n $record['organization'] = $entity['companyName'];\n $record['title'] = $entity['occupation'];\n\n foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {\n if (empty($entity[$phone]) === false) {\n $record['phoneNumbers'][] = [\n 'number' => $entity[$phone],\n 'nationalFormat' => phone_national(null, $entity[$phone]),\n 'type' => $phone === 'mobile' ? 'mobile' : 'phone',\n ];\n }\n }\n\n break;\n\n default:\n // We are not interested in this entity type so skip it.\n continue 2;\n }\n\n $result[] = $record;\n }\n\n return $result;\n });\n\n return $data;\n }\n\n public function getClient(): BullhornClientInterface\n {\n return $this->client;\n }\n\n private function getFieldsAsString(array $fields)\n {\n return implode(', ', $fields);\n }\n\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),\n ];\n\n $onlyOpen = true;\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort'] = '-dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort'] = '+dateAdded';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort'] = '-dateLastModified';\n $onlyOpen = false;\n }\n\n if ($onlyOpen) {\n $where .= ' AND isOpen: true';\n }\n\n $params['query'] = $where;\n\n $bhOpportunities = $this->client->get('search/JobOrder', $params);\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n foreach ($bhOpportunities['data'] as $bhOpportunity) {\n $stage = $this->config\n ->stages()\n ->where('crm_provider_id', $bhOpportunity['status'])\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);\n }\n\n $record = [\n 'crmId' => $bhOpportunity['id'],\n 'name' => $bhOpportunity['title'],\n 'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),\n 'won' => strtolower($bhOpportunity['status']) === 'placed',\n 'closed' => $bhOpportunity['isOpen'] !== true,\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n 'recordType' => [],\n ];\n\n if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = [];\n\n // For now it has not been agreed on how to implement this e.g. appointments or tasks?\n return [];\n\n if ($objectType === 'account' && $opportunityId === null) {\n // You cannot attach tasks to only accounts.\n return [];\n }\n\n // Query should default to any open task.\n $where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;\n\n // If we are also going to check on a specific job order, set that up.\n if ($opportunityId) {\n $where .= ' OR JobOrder: ' . (int) $opportunityId;\n }\n\n $where .= ')';\n\n $params = [\n 'sort' => '-dateLastModified',\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => $where,\n ];\n\n $bhTasks = $this->client->get('search/Task', $params);\n\n foreach ($bhTasks['data'] as $bhTask) {\n $data[] = [\n 'crmId' => $bhTask['id'],\n 'subject' => $bhTask['subject'],\n 'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),\n 'type' => null,\n ];\n }\n\n return $data;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * ?Lead,\n * ?Account,\n * ?Opportunity,\n * ?Contact,\n * ?Stage,\n * ?string\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $bhObject = $this->client->get('find', [\n 'query' => $email,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember === false) {\n $bhObject = $this->client->get('find', [\n 'query' => $rawPhoneNumber ?? $phone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n if (empty($bhObject['data'])) {\n $nationalPhone = phone_national(null, $rawPhoneNumber ?? $phone);\n $formattedPhone = ltrim($nationalPhone, '+0');\n $bhObject = $this->client->get('find', [\n 'query' => $formattedPhone,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n }\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n return null;\n }\n\n /**\n * @url https://bullhorn.github.io/rest-api-docs/index.html#get-find\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 3) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = \\Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n $bhObject = $this->client->get('find', [\n 'query' => $name,\n 'meta' => 'basic',\n 'countPerEntity' => 10,\n ]);\n\n $data = $this->convertCrmData($bhObject['data'], $userId);\n\n return ! empty(array_filter($data)) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->team->getId() . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n public function saveActivity(Activity $activity): Activity\n {\n\n if ($activity->hasCrmProviderId()) {\n return $activity;\n }\n\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildNotePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n /**\n * @throws CrmException\n * @throws DomainException\n */\n private function buildNotePayload(Activity $activity): Activity\n {\n if ($activity->hasActivityType() === false) {\n throw new DomainException('[Bullhorn] No activity type assigned');\n }\n\n $action = $this->getCrmType($activity->getActivityType());\n if ($action === null) {\n throw new DomainException('[Bullhorn] No mapped CRM type for \"' . $activity->category->name . '\"');\n }\n\n if ($activity->lead_id === null && $activity->contact_id === null) {\n throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');\n }\n\n $payload = [\n 'comments' => $this->generateActivityDescription($activity),\n 'action' => $action->value,\n 'commentingPerson' => [\n 'id' => (int) $this->profile->crm_provider_id,\n 'type' => 'CorporateUser',\n ],\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n 'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),\n ];\n\n if ($activity->lead_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->lead->crm_provider_id,\n 'type' => 'Candidate',\n ];\n }\n\n if ($activity->contact_id) {\n $payload['personReference'] = [\n 'id' => (int) $activity->contact->crm_provider_id,\n 'type' => 'ClientContact',\n ];\n }\n\n if ($activity->opportunity_id) {\n $payload['jobOrders'] = [\n 'replaceAll' => [\n (int) $activity->opportunity->crm_provider_id,\n ],\n ];\n }\n\n $bhActivity = $this->client->put('entity/Note', $payload);\n\n $activity->crm_provider_id = $bhActivity['changedEntityId'];\n $activity->save();\n\n return $activity;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = '';\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Dialed: %s</span></p>',\n $activity->to->phone_number,\n );\n }\n $description .= '<p></p>';\n }\n\n if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {\n // Dialer calls have no native field for the subject.\n if ($activity->title) {\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->title,\n );\n }\n\n // Conference meetings log duration into a distinct field, so log this in the main text.\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Call Duration: %s</span></p>',\n $activity->duration_for_humans,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">Caller: %s</span></p>',\n $activity->from->phone_number,\n );\n $description .= '<p></p>';\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker removed from this meeting'\n . '</span>'\n . '</p>';\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . 'Notetaker did not join due to recording consent not being provided by attendees'\n . '</span>'\n . '</p>';\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= sprintf(\n '<p>'\n . '<span style=\"font-size: 13.3333px; line-height: 16px;\">'\n . '<a href=\"%s\" target=\"_blank\">'\n . 'Review in Jiminny'\n . '</a>'\n . '️</span>'\n . '</p>',\n $playbackUrl,\n );\n }\n\n if ($activity->isTypeConference()) {\n $description .= '<p><strong>Attendees</strong></p><ul>';\n\n // Only include participants that joined.\n $participants = $activity->participants()->ghost(false)->whereNotNull('enter_time')->get();\n foreach ($participants as $participant) {\n $attendee = '<li>';\n if ($participant->name) {\n $attendee .= $participant->name;\n if ($participant->phone_number) {\n $attendee .= ' (' . $participant->phone_number . ')';\n } elseif ($participant->email) {\n $attendee .= ' (' . $participant->email . ')';\n }\n } else {\n $attendee .= $participant->phone_number;\n }\n\n if ($participant->is_ghost) {\n $attendee .= ' <strong>coach</coach>';\n }\n\n if ($participant->getTitle()) {\n $attendee .= ', ' . $participant->getTitle();\n }\n\n $description .= $attendee . '</li>';\n }\n $description .= '</ul>';\n }\n\n if (count($activity->notes) > 0) {\n $description .= '<p><strong>Notes</strong></p>';\n\n foreach ($activity->notes as $note) {\n $time = ($note->time > 3600) ? gmdate('H:i:s', $note->time) : gmdate('i:s', $note->time);\n $description .= '<p>' . $time . ' ' . $note->note . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Coaching Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= '<p><strong>Customer Chat</strong></p>';\n\n foreach ($messages->get() as $message) {\n $description .= '<p>' . $message->participant->name . ': ' . $message->message . '</p>';\n }\n $description .= '</p>';\n }\n\n if ($activity->summary) {\n $description .= '<p><strong>Summary</strong></p><p>' . $activity->summary . '</p><p></p>';\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n // Use Rich-text formatting.\n $description = sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\"><strong>%s</strong></span></p>',\n $activity->title,\n );\n $description .= sprintf(\n '<p><span style=\"font-size: 16px; line-height: 19.2px;\">%s</span></p>',\n $activity->description,\n );\n\n break;\n }\n\n return $description;\n }\n\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // Not yet required by current customers.\n return null;\n }\n\n public function updateStage($crmObject, Stage $stage): void\n {\n $objectId = $crmObject->crm_provider_id;\n\n $this->updateRecord($stage->type, $objectId, ['status' => $stage->crm_provider_id]);\n }\n\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $start = 0;\n $payload = [\n 'fields' => 'id,email',\n 'where' => 'isDeleted=false',\n 'count' => 500,\n ];\n\n $payload['start'] = $start;\n $profiles = $this->client->get('query/CorporateUser', $payload);\n\n foreach ($profiles['data'] as $profile) {\n if (empty($profile['email'])) {\n continue;\n }\n\n $user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);\n\n // Only import profiles for users we have locally.\n if ($user) {\n $profile = $user->crmProfile()->updateOrCreate([\n 'crm_configuration_id' => $this->config->id,\n 'crm_provider_id' => $profile['id'],\n ]);\n\n if ($userToSearch && $userToSearch->id === $user->id) {\n return $profile;\n }\n }\n }\n\n return null;\n }\n\n protected function convertCrmData(array $entities, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n $mappedEntities = [];\n foreach ($entities as $entity) {\n if (in_array($entity['entityType'], [self::ENTITY_LEAD, self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n $mappedEntities[] = $entity;\n }\n }\n\n // If there is only one match, sync the data and return the object(s).\n if (count($mappedEntities) === 1) {\n $entity = $mappedEntities[0];\n\n if ($entity['entityType'] === self::ENTITY_LEAD) {\n $lead = $this->syncLead($entity['entityId']);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } elseif (in_array($entity['entityType'], [self::ENTITY_CONTACT, self::ENTITY_ACCOUNT])) {\n if ($entity['entityType'] === self::ENTITY_CONTACT) {\n $contact = $this->syncContact($entity['entityId']);\n $account = $contact->account;\n } else {\n $account = $this->syncAccount($entity['entityId']);\n }\n\n if ($contact?->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $bhOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact?->crm_provider_id,\n $userId,\n );\n\n // Take the first opportunity, which will be ordered as priority based on their settings.\n if (! empty($bhOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($bhOpportunities[0]['crmId']);\n $stage = $opportunity?->stage;\n }\n } catch (Exception) {\n // Nothing to see here.\n }\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n // There doesn't appear to be a way to deeplink to anything on https://app.bullhornstaffing.com.\n return null;\n }\n\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $this->client->post('entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId, $data);\n }\n\n public function getRecord(string $objectType, string $objectId, array $fields = ['id']): array\n {\n return $this->client->get(\n url: 'entity/' . $this->convertObjectTypeToResource($objectType) . '/' . $objectId,\n data: ['fields' => $this->getFieldsAsString($fields)],\n );\n }\n\n private function convertObjectTypeToResource(string $objectType)\n {\n switch ($objectType) {\n case FieldData::OBJECT_OPPORTUNITY:\n return self::ENTITY_OPPORTUNITY;\n\n case FieldData::OBJECT_CONTACT:\n return self::ENTITY_CONTACT;\n\n case FieldData::OBJECT_LEAD:\n return self::ENTITY_LEAD;\n\n case FieldData::OBJECT_ACCOUNT:\n return self::ENTITY_ACCOUNT;\n\n case FieldData::OBJECT_TASK:\n return self::ENTITY_ACTIVITY;\n\n default:\n throw new \\UnexpectedValueException('Unsupported object type \"' . $objectType . '\"');\n }\n }\n\n private function convertResourceToObjectType(string $resource): string\n {\n switch ($resource) {\n case self::ENTITY_OPPORTUNITY:\n return FieldData::OBJECT_OPPORTUNITY;\n\n case self::ENTITY_CONTACT:\n return FieldData::OBJECT_CONTACT;\n\n case self::ENTITY_LEAD:\n return FieldData::OBJECT_LEAD;\n\n case self::ENTITY_ACCOUNT:\n return FieldData::OBJECT_ACCOUNT;\n\n case self::ENTITY_ACTIVITY:\n return FieldData::OBJECT_TASK;\n\n default:\n throw new \\UnexpectedValueException('Unsupported resource \"' . $resource . '\"');\n }\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n // We need to know when it started to determine when to look for related activity.\n if ($activity->hasActualStartTime() === false) {\n return null;\n }\n\n try {\n $bhNote = $this->fetchRelatedActivity($activity);\n if (empty($bhNote)) {\n $this->logger->info('[Bullhorn] No related activity found', [\n 'activity' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n $activityType = $this->getPlaybookCategory($this->getPlaybook($activity->user), $bhNote['action']);\n $comments = $bhNote['comments'] . '<br />//<br />' . $this->generateActivityDescription($activity);\n // Now update the Note to contain our data.\n $payload = [\n 'comments' => $comments,\n 'externalID' => $activity->id_string,\n 'minutesSpent' => $activity->duration,\n ];\n\n $this->logger->info('[Bullhorn] updating related activity', [\n 'activity' => $activity->getUuid(),\n 'activityType' => $activityType->id ?? null,\n ]);\n\n $this->client->post('entity/Note/' . $bhNote['id'], $payload);\n\n $playbookCategoryId = null;\n if ($activity->getCategory() !== null) {\n $playbookCategoryId = $activity->getCategory()->getId();\n }\n\n // Update our activity to reflect the remote data.\n $activity->update([\n 'crm_provider_id' => $bhNote['id'],\n 'summary' => $bhNote['comments'],\n 'playbook_category_id' => $activityType->id ?? $playbookCategoryId,\n ]);\n\n return $activity;\n } catch (\\Exception $exception) {\n \\Sentry::captureException($exception);\n\n throw $exception;\n }\n }\n\n /**\n * Returns the most recently modified note within time range (if any).\n *\n * @return array A Note record from Bullhorn.\n */\n public function fetchRelatedActivity(Activity $activity): array\n {\n $from = $activity->hasScheduledStartTime()\n ? $activity->getScheduledStartTime()\n : $activity->getActualStartTime();\n $to = $activity->hasActualEndTime()\n ? $activity->getActualEndTime()?->addMinutes(15)\n : $from?->clone()->addMinutes(15);\n\n $filterStatements = [\n 'isDeleted: false',\n '*:* -externalID:[* TO *]', // externalID should be null e.g. we did not already relate it.\n sprintf('commentingPerson: %d', (int) $this->profile->crm_provider_id),\n ];\n\n /**\n * @XXX: Bullhorn does not specify the time zone in their docs. I've found a forum thread in which someone from\n * staff asserts it's UTC, however in my field test I've found it to be GMT-0300 (USA east coast).\n * To make the code immune to such glitches we will add 24h to start/end boundaries and will filter out\n * any excess items in code\n */\n $filterStatements[] = sprintf(\n 'dateLastModified:[%s TO %s]',\n $from?->clone()->subHours(24)->format('YmdHis'),\n $to->clone()->addHours(24)->format('YmdHis'),\n );\n\n if ($activity->lead_id) {\n $filterStatements[] = sprintf('candidateUserID: %d', (int) $activity->lead->crm_provider_id);\n }\n\n if ($activity->contact_id) {\n $filterStatements[] = sprintf('clientContactUserID: %d', (int) $activity->contact->crm_provider_id);\n }\n\n // if there is no contact or lead associated to the activity exit\n if ($activity->contact_id === null && $activity->lead_id === null) {\n return [];\n }\n\n $params = [\n 'fields' => $this->getFieldsAsString(self::TASK_FIELDS),\n 'query' => implode(' AND ', $filterStatements),\n 'sort' => '-dateLastModified',\n ];\n\n $bhNotes = $this->client->get('search/Note', $params);\n\n $startStamp = $from?->getTimestamp() * 1000;\n $endStamp = $to->getTimestamp() * 1000;\n\n $filteredNotes = array_values(\n array_filter(\n $bhNotes['data'],\n static fn (array $bhNote): bool\n => $bhNote['dateLastModified'] >= $startStamp && $startStamp <= $endStamp,\n ),\n );\n\n return ! empty($filteredNotes) ? array_shift($filteredNotes) : [];\n }\n\n /**\n * Select how to create the date out of the Bullhorn payload.\n * Do not allow dates beyond 9999-12-31 (max mysql DATE)\n */\n private function filterOutOfBoundDates(string $rawDateCandidate): ?Carbon\n {\n if (strlen($rawDateCandidate) > 12) {\n // A unix timestamp represented with more than 12 digits i\n // s definitely including milliseconds\n $dateFormatted = Carbon::createFromTimestampMs($rawDateCandidate);\n } else {\n $dateFormatted = Carbon::createFromTimestamp($rawDateCandidate);\n }\n\n $minDate = Carbon::createFromFormat('Y-m-d', '2000-01-01');\n if ($dateFormatted->lt($minDate)) {\n return null;\n }\n\n $maxDate = Carbon::createFromFormat('Y-m-d', '9999-12-31');\n if ($dateFormatted->gt($maxDate)) {\n $this->logger->warning('[Bullhorn] An out of bound date is provided', [\n 'date' => $dateFormatted,\n 'rawDate' => $rawDateCandidate,\n ]);\n\n return $maxDate;\n }\n\n return $dateFormatted;\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n $note = $this->getRecord('Note', $crmProviderId, ['id', 'isDeleted']);\n\n return ! empty($note) && ($note['isDeleted'] ?? false) === false;\n } catch (HttpNotFoundException|HttpBadRequestException) {\n // Note not found in CRM - this is expected and permanent\n $this->logger->info('[Bullhorn] Note not found during verification', [\n 'note_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false}]...
|
2798564629323822362
|
-3411827625184589122
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
2
13
3
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Bullhorn;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\Provider\BullhornInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\ApplicationException;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\DomainException;
use Jiminny\Exceptions\HttpBadRequestException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Exceptions\ServiceUnavailableException;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\UserRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
use Ramsey\Uuid\Uuid;
class BullhornService extends BaseService implements
BullhornInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const string ENTITY_LEAD = 'Candidate';
private const string ENTITY_OPPORTUNITY = 'JobOrder';
private const string ENTITY_ACCOUNT = 'ClientCorporation';
private const string ENTITY_CONTACT = 'ClientContact';
private const string ENTITY_ACTIVITY = 'Note';
private const array OPPORTUNITY_FIELDS = [
'id',
'owner',
'status',
'title',
'salary',
'salaryUnit',
'payRate',
'isOpen',
'employmentType',
'dateClosed',
'startDate',
'dateLastModified',
'dateAdded',
'clientCorporation',
'correlatedCustomText10', // currency
];
private const array TASK_FIELDS = [
'id',
'comments',
'dateAdded',
'dateLastModified',
'externalID',
'isDeleted',
'corporateUsers',
'clientContacts',
'commentingPerson',
'candidates',
'jobOrder',
'minutesSpent',
'action',
];
private const array LEAD_FIELDS = [
'id',
'name',
'owner',
'occupation',
'companyName',
'companyURL',
'mobile',
'phone',
'phone2',
'phone3',
'workPhone',
'status',
'address',
'dateAdded',
'dateLastModified',
];
private const array CONTACT_FIELDS = [
'id',
'name',
'occupation',
'mobile',
'phone',
'phone2',
'phone3',
'address',
'clientCorporation',
'dateAdded',
'owner',
];
private const array ACCOUNT_FIELDS = [
'id',
'name',
'phone',
'industryList',
'address',
'companyURL',
'dateAdded',
];
public function __construct(
BullhornClientInterface $client,
private readonly UserRepository $userRepository,
private readonly ProspectPhotoPathService $prospectPhotoPathService
) {
parent::__construct();
$this->client = $client;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_BULLHORN);
}
public function getDisplayName(): string
{
return 'Bullhorn';
}
public function createTranscriptNotes(Activity $activity): void
{
// Not done until a customer requests it.
}
public function syncProfileFields(): void
{
$fieldTypes = [
'lead',
'account',
'contact',
'opportunity',
'task',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields($this->convertObjectTypeToResource($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))
);
if (! empty($changedFields)) {
$fields = implode(',', $newFields);
Log::debug(
sprintf(
'%s fields changed from %s to: %s',
ucfirst($fieldType),
$this->profile->{$fieldType . '_fields'},
$fields,
),
);
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (\Exception $exception) {
\Log::error('No access to ' . $fieldType . ' object, skipping...');
// XXX: should we log this fact somewhere?
continue;
}
}
$this->profile->save();
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
//parent::OBJECT_ACCOUNT,
//parent::OBJECT_CONTACT,
//parent::OBJECT_OPPORTUNITY,
//parent::OBJECT_LEAD,
];
}
protected function getFields(string $crmObject): array
{
$fields = [];
foreach ($this->getObjectFields($crmObject) as $row) {
$fields[] = ['label' => $row['label'] ?? $row['name'], 'name' => $row['name']];
}
return $fields;
}
private function getObjectFields(string $objectType): array
{
$entityType = $this->convertObjectTypeToResource($objectType);
return Cache::remember(
key: 'crm.profile#' . $this->profile->id . '.fieldType:' . $objectType,
ttl: 60 * 60,
callback: function () use ($entityType) {
$entity = $this->client->get('meta/' . $entityType, [
'fields' => '*',
]);
return $entity['fields'];
},
);
}
public function getDefaultFields(string $activityType): array
{
$fields = [];
$defaultFields = FieldDefinitions::defaultFields();
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
return $fields;
}
public function getDefaultActivityField(string $activityType): Field
{
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'action',
'object_type' => $activityType,
])->first();
return $activityField;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
// We are not yet supporting follow-ups for this system.
return [];
}
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return $fieldValue;
}
public function syncField(Field $field): void
{
$resource = $this->convertObjectTypeToResource($field->object_type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => $field->crm_provider_id,
'meta' => 'full',
]);
$bhField = $entity['fields'][0];
$isMandatory = (empty($bhField['optional']) == false && $bhField['optional'] === false);
$description = null;
if (empty($bhField['description']) === false) {
$description = mb_strimwidth($bhField['description'], 0, 191);
}
$label = 'Unknown';
if (empty($bhField['label']) === false) {
$label = mb_strimwidth($bhField['label'], 0, Field::LABEL_MAX_LENGTH);
}
$field->length = $bhField['maxLength'] ?? null;
$field->is_mandatory = $isMandatory;
$field->description = $description;
$field->label = $label;
$field->type = $this->convertFieldType(
$bhField['dataType'] ?? null,
$bhField['dataSpecialization'] ?? null,
$bhField['inputType'] ?? null
);
$field->save();
if (empty($bhField['options']) === false) {
$values = [];
// Import all values.
foreach ($bhField['options'] as $i => $option) {
$values[] = [
'value' => $option['value'],
'label' => mb_strimwidth($option['label'], 0, Field::LABEL_MAX_LENGTH),
'sequence' => $i,
];
}
// Take the existing set of field values.
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
// For all current values, upsert the field.
$field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
$key = array_search($value['value'], $fieldsToPurge, false);
if ($key !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
}
}
public function importPicklistValues(Field $field): array
{
// Taken care of in syncField.
return [];
}
private function convertFieldType(?string $type, ?string $specialization, ?string $inputType): string
{
if ($type === null) {
return Field::TYPE_UNSUPPORTED;
}
$type = strtolower($type);
$specialization = strtolower($specialization);
$inputType = strtolower($inputType);
switch ($type) {
case 'boolean':
return Field::TYPE_BOOLEAN;
case 'integer':
switch ($specialization) {
case 'integer':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'bigdecimal':
switch ($specialization) {
case 'money':
return Field::TYPE_CURRENCY;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'double':
switch ($specialization) {
case 'float':
return Field::TYPE_NUMBER;
default:
return Field::TYPE_NUMBER;
}
// no break
case 'timestamp':
switch ($specialization) {
case 'date':
return Field::TYPE_DATE;
case 'time':
return Field::TYPE_TIME;
case 'datetime':
return Field::TYPE_DATETIME;
default:
return Field::TYPE_DATE;
}
// no break
case 'string':
switch ($inputType) {
case 'textarea':
return Field::TYPE_TEXTAREA;
case 'select':
return Field::TYPE_PICKLIST;
default:
return Field::TYPE_TEXT;
}
// no break
default:
// This is not actually a supported field.
return Field::TYPE_UNSUPPORTED;
}
}
private function importContact($crmData): Contact
{
$account = $mobilePhone = $phone = $email = null;
if (empty($crmData['clientCorporation']) === false) {
$account = $this->team
->accounts()
->where('crm_provider_id', $crmData['clientCorporation']['id'])
->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
}
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => $crmData['name'],
'email' => $email,
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'title' => $crmData['occupation'],
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Contact::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importOpportunity($crmData): ?Opportunity
{
if ($crmData['clientCorporation']['id']) {
$account = $this->config->accounts()->where('crm_provider_id', (string) $crmData['clientCorporation']['id'])->first();
if ($account === null) {
$account = $this->syncAccount($crmData['clientCorporation']['id']);
}
} else {
// If there is nothing to associate this with, don't import it.
return null;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$stage = $this->config->stages()
->where('crm_provider_id', $crmData['status'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['status']);
}
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'name' => mb_strimwidth($crmData['title'], 0, 128),
'value' => $crmData['salary'] ?? $crmData['payRate'],
'currency_code' => CurrencyFormatter::formatCode($crmData['correlatedCustomText10'] ?? 'USD'),
'close_date' => $this->filterOutOfBoundDates($crmData['startDate']),
'is_closed' => $crmData['isOpen'] !== true,
'is_won' => strtolower($crmData['status']) === 'placed',
'stage_id' => $stage->id,
'record_type_id' => null,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->opportunities()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importAccount($crmData): Account
{
$countryCode = $domain = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$name = $crmData['name'] ?? 'Unknown';
if ($crmData['companyURL'] !== null) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$data = [
'team_id' => $this->team->id,
'user_id' => null,
'owner_id' => null,
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Account::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'country_code' => $countryCode,
'domain' => $domain,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function importLead($crmData): ?Lead
{
// Get the current stage.
$stage = $this->config->stages()->where('name', $crmData['status'])->where('type', Stage::TYPE_LEAD)->first();
if ($stage === null) {
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status']);
}
// If we have no way of importing this, just return null :(
if ($stage === null) {
return null;
}
$countryCode = null;
if (empty($crmData['address']['countryCode'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['countryCode']);
}
$mobilePhone = $phone = $email = null;
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $type) {
if (empty($crmData[$type])) {
continue;
}
if ($type === 'mobile') {
$mobilePhone = parsePhoneNumber($countryCode, $crmData[$type]);
} else {
$phone = parsePhoneNumber($countryCode, $crmData[$type]);
}
break;
}
foreach (['email', 'email1', 'email2'] as $type) {
if (empty($crmData[$type])) {
continue;
}
$email = mb_strimwidth($crmData[$type], 0, 80);
break;
}
$company = 'Unknown';
if (empty($crmData['companyName']) === false) {
$companyName = is_array($crmData['companyName']) ? $crmData['companyName'][0] : $crmData['companyName'];
$company = mb_strimwidth($companyName, 0, 191);
}
$domain = null;
if (empty($crmData['companyURL']) === false) {
$domain = mb_strimwidth($crmData['companyURL'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['owner']['id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['owner']['id'],
'company' => $company,
'domain' => $domain,
'name' => mb_strimwidth($crmData['name'], 0, 191),
'title' => mb_strimwidth($crmData['occupation'], 0, 128),
'email' => mb_strimwidth($email, 0, 80),
'phone' => empty($phone['phone']) ? null : mb_strimwidth($phone['phone'], 0, 25),
'ext' => $phone['ext'] ?? null,
'mobile_phone' => empty($mobilePhone['phone']) ? null : mb_strimwidth($mobilePhone['phone'], 0, 25),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Lead::class,
fileName: $crmData['id'],
avatarText: $crmData['name'] ?? 'Unknown'
),
'stage_id' => $stage->id,
'country_code' => $countryCode,
'remotely_created_at' => $this->filterOutOfBoundDates($crmData['dateAdded']),
];
return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
/**
* @throws ApplicationException
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::CONTACT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhContacts = $this->client->get('search/ClientContact', $params);
foreach ($bhContacts['data'] as $bhContact) {
// Only sync if previously imported.
if ($this->hasContact($bhContact['id'])) {
$this->importContact($bhContact);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync contacts', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategies = $strategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
$total = 0;
$count = 0;
$offset = 0;
try {
$bhOpportunities = [];
foreach ($strategies as $syncStrategy) {
$opportunitiesData = $syncStrategy->fetchOpportunities($parameters);
$total = (int) ($opportunitiesData['total'] ?? 0);
$count = (int) ($opportunitiesData['count'] ?? 0);
$offset = (int) ($opportunitiesData['start'] ?? 0);
$bhOpportunities[] = $opportunitiesData['data'] ?? [];
}
$bhOpportunities = array_merge(...$bhOpportunities);
foreach ($bhOpportunities as $bhOpportunity) {
$this->importOpportunity($bhOpportunity);
$syncCount++;
}
} catch (\Exception $exception) {
$this->logger->info('Failed to sync opportunities', [
'params' => $parameters,
'exception' => $exception->getMessage(),
]);
}
// only log if there are one sync strategy
if (count($strategies) === 1 && $total > $count + $offset) {
$this->logger->info('[Bullhorn] Sync Opportunities - count warning', [
'team_id' => $this->team->getId(),
'total' => $total,
'count' => $count,
'offset' => $offset,
]);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::ACCOUNT_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhAccounts = $this->client->get('search/ClientCorporation', $params);
foreach ($bhAccounts['data'] as $bhAccount) {
// Only sync if previously imported.
if ($this->hasAccount($bhAccount['id'])) {
$this->importAccount($bhAccount);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync accounts', $exception->getCode(), $exception);
}
return $syncCount;
}
/**
* @throws ApplicationException
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::LEAD_FIELDS),
'query' => 'isDeleted: false AND dateLastModified:[' . $since->format('YmdHis') . ' TO *]',
];
try {
$bhLeads = $this->client->get('search/Candidate', $params);
if ($bhLeads === null) {
return $syncCount;
}
foreach ($bhLeads['data'] as $bhLead) {
// Only sync if previously imported.
if ($this->hasLead($bhLead['id'])) {
$this->importLead($bhLead);
$syncCount++;
}
}
} catch (\Exception $exception) {
throw new ApplicationException('Failed to sync leads', $exception->getCode(), $exception);
}
return $syncCount;
}
public function syncContact(string $crmId): ?Contact
{
try {
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $crmId, self::CONTACT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importContact($data['data']);
}
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$strategy = $strategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
try {
$data = $strategy->fetchOpportunities(['crm_id' => $crmId]);
} catch (HttpNotFoundException $exception) {
$this->logger->info('[Bullhorn] Opportunity not found', [
'crm_id' => $crmId,
'reason' => $exception->getMessage(),
]);
}
return $this->importOpportunity($data['data'] ?? []);
}
public function syncAccount(string $crmId): ?Account
{
try {
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $crmId, self::ACCOUNT_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importAccount($data['data']);
}
public function syncLead(string $crmId): ?Lead
{
try {
$data = $this->getRecord(FieldData::OBJECT_LEAD, $crmId, self::LEAD_FIELDS);
} catch (HttpNotFoundException $exception) {
return null;
}
return $this->importLead($data['data']);
}
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$missingStage = null;
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
foreach ($types as $type) {
$resource = $this->convertObjectTypeToResource($type);
$entity = $this->client->get('meta/' . $resource, [
'fields' => 'status',
'meta' => 'full',
]);
$missingStage = null;
if (! is_array($entity['fields']) || count($entity['fields']) !== 1 || $entity['fields'][0]['name'] !== 'status') {
throw new \UnexpectedValueException('Invalid response from Bullhorn API');
}
// Upsert all stages for the team.
foreach ($entity['fields'][0]['options'] as $i => $option) {
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $option['value'],
'type' => $type,
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($option['value'], 0, 50),
'label' => mb_strimwidth($option['label'], 0, 191),
'sequence' => $i,
'is_selectable' => 1,
]);
if ($missingStageName && $missingStageName === $option['value']) {
$missingStage = $stage;
}
}
if ($missingStageName && $missingStage === null) {
// If they requested a stage that still doesn't exist, it must be inactive so lazy create it.
$missingStage = $this->config->stages()->create([
'team_id' => $this->team->id,
'crm_provider_id' => Uuid::uuid4(),
'name' => mb_strimwidth($missingStageName, 0, 50),
'label' => mb_strimwidth($missingStageName, 0, 191),
'type' => $type,
'sequence' => 0,
'is_selectable' => 0,
]);
}
}
return $missingStage;
}
public function syncOrganization(): void
{
// There appears to be nothing we can sync/map to.
}
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$data = \Cache::remember($this->team->id . $name . $count . $offset, 300, function () use ($name, $count) {
$result = [];
try {
$objects = $this->client->get('find', [
'query' => $name,
'meta' => 'basic',
'countPerEntity' => $count,
]);
} catch (\GuzzleHttp\Exception\ServerException $exception) {
throw new ServiceUnavailableException($exception->getMessage());
}
foreach ($objects['data'] as $object) {
try {
$prospectType = $this->convertResourceToObjectType($object['entityType']);
} catch (\UnexpectedValueException $exception) {
// We don't support this, so skip it.
continue;
}
$record = [
'crmId' => $object['entityId'],
'crmUrl' => $this->generateProviderUrl($object['entityId'], $object['entityType']),
'prospectType' => $prospectType,
'phoneNumbers' => [],
];
// Unfortunately we need to go and query each entity itself to get the data we need.
switch ($object['entityType']) {
case self::ENTITY_ACCOUNT:
$data = $this->getRecord(FieldData::OBJECT_ACCOUNT, $object['entityId'], self::ACCOUNT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['industry'] = $entity['industryList'];
if (empty($entity['phone']) === false) {
$record['phoneNumbers'][] = [
'number' => $entity['phone'],
'nationalFormat' => phone_national(null, $entity['phone']),
'type' => 'phone',
];
}
break;
case self::ENTITY_CONTACT:
$data = $this->getRecord(FieldData::OBJECT_CONTACT, $object['entityId'], self::CONTACT_FIELDS);
$entity = $data['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['clientCorporation'] ? $entity['clientCorporation']['name'] : null;
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
case self::ENTITY_LEAD:
$bhData = $this->getRecord(FieldData::OBJECT_LEAD, $object['entityId'], self::LEAD_FIELDS);
$entity = $bhData['data'];
$record['name'] = $entity['name'];
$record['organization'] = $entity['companyName'];
$record['title'] = $entity['occupation'];
foreach (['mobile', 'phone', 'phone2', 'phone3', 'workPhone'] as $phone) {
if (empty($entity[$phone]) === false) {
$record['phoneNumbers'][] = [
'number' => $entity[$phone],
'nationalFormat' => phone_national(null, $entity[$phone]),
'type' => $phone === 'mobile' ? 'mobile' : 'phone',
];
}
}
break;
default:
// We are not interested in this entity type so skip it.
continue 2;
}
$result[] = $record;
}
return $result;
});
return $data;
}
public function getClient(): BullhornClientInterface
{
return $this->client;
}
private function getFieldsAsString(array $fields)
{
return implode(', ', $fields);
}
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$where = 'isDeleted: false AND clientCorporation.id:' . (int) $account->crm_provider_id;
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::OPPORTUNITY_FIELDS),
];
$onlyOpen = true;
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort'] = '-dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort'] = '+dateAdded';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort'] = '-dateLastModified';
$onlyOpen = false;
}
if ($onlyOpen) {
$where .= ' AND isOpen: true';
}
$params['query'] = $where;
$bhOpportunities = $this->client->get('search/JobOrder', $params);
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
foreach ($bhOpportunities['data'] as $bhOpportunity) {
$stage = $this->config
->stages()
->where('crm_provider_id', $bhOpportunity['status'])
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $bhOpportunity['status']);
}
$record = [
'crmId' => $bhOpportunity['id'],
'name' => $bhOpportunity['title'],
'value' => currency_format($bhOpportunity['salary'], $bhOpportunity['correlatedCustomText10'] ?? 'USD'),
'won' => strtolower($bhOpportunity['status']) === 'placed',
'closed' => $bhOpportunity['isOpen'] !== true,
'stage' => [
'id' => $stage->id_string,
'name' => $stage->name,
],
'recordType' => [],
];
if ($ownerId && isset($bhOpportunity['owner']['id']) && $bhOpportunity['owner']['id'] === (int) $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = [];
// For now it has not been agreed on how to implement this e.g. appointments or tasks?
return [];
if ($objectType === 'account' && $opportunityId === null) {
// You cannot attach tasks to only accounts.
return [];
}
// Query should default to any open task.
$where = 'isDeleted: false AND isCompleted: false AND (' . $this->convertObjectTypeToResource($objectType) . 'UserId: ' . (int) $objectId;
// If we are also going to check on a specific job order, set that up.
if ($opportunityId) {
$where .= ' OR JobOrder: ' . (int) $opportunityId;
}
$where .= ')';
$params = [
'sort' => '-dateLastModified',
'fields' => $this->getFieldsAsString(self::TASK_FIELDS),
'query' => $where,
];
$bhTasks = $this->client->get('search/Task', $params);
foreach ($bhTasks['data'] as $bhTask) {
$data[] = [
'crmId' => $bhTask['id'],
'subject' => $bhTask['subject'],
'due' => Carbon::createFromTimestampMs($bhTask['dateEnd'])->toIso8601String(),
'type' => null,
];
}
return $data;
}
/**
* @url [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] [URL_WITH_CREDENTIALS] CrmException
* @throws DomainException
*/
private function buildNotePayload(Activity $activity): Activity
{
if ($activity->hasActivityType() === false) {
throw new DomainException('[Bullhorn] No activity type assigned');
}
$action = $this->getCrmType($activity->getActivityType());
if ($action === null) {
throw new DomainException('[Bullhorn] No mapped CRM type for "' . $activity->category->name . '"');
}
if ($activity->lead_id === null && $activity->contact_id === null) {
throw new DomainException('[Bullhorn] Cannot save note without candidate or DM');
}
$payload = [
'comments' => $this->generateActivityDescription($activity),
'action' => $action->value,
'commentingPerson' => [
'id' => (int) $this->profile->crm_provider_id,
'type' => 'CorporateUser',
],
'externalID' => $activity->id_string,
'minutesSpent' => $activity->duration,
'dateAdded' => $activity->hasActualEndTime() ? $activity->getActualEndTime()?->valueOf() : now()->valueOf(),
];
if ($activity->lead_id) {
$payload['personReference'] = [
'id' => (int) $activity->lead->crm_provider_id,
'type' => 'Candidate',
];
}
if ($activity->contact_id) {
$payload['personReference'] = [
'id' => (int) $activity->contact->crm_provider_id,
'type' => 'ClientContact',
];
}
if ($activity->opportunity_id) {
$payload['jobOrders'] = [
'replaceAll' => [
(int) $activity->opportunity->crm_provider_id,
],
];
}
$bhActivity = $this->client->put('entity/Note', $payload);
$activity->crm_provider_id = $bhActivity['changedEntityId'];
$activity->save();
return $activity;
}
private function generateActivityDescription(Activity $activity): string
{
$description = '';
switch ($activity->type) {
case Activity::TYPE_SOFTPHONE:
case Activity::TYPE_SOFTPHONE_INBOUND:
case Activity::TYPE_CONFERENCE:
if ($activity->isTypeSoftPhone() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
// Dialer calls have no native field for the subject.
if ($activity->title) {
$description .= sprintf(
'<p><span style="font-size: 16px; line-height: 19.2px;">%s</span></p>',
$activity->title,
);
}
// Conference meetings log duration into a distinct field, so log this in the main text.
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Call Duration: %s</span></p>',
$activity->duration_for_humans,
);
// Tell them which number was dialed.
if ($activity->to) {
$description .= sprintf(
'<p><span style="font-size: 13.3333px; line-height: 16px;">Dialed: %s</span></p>',
$activity->to->phone_number,
);
}
$description .= '<p></p>';
}
if ($activity->isTypeSoftphoneInbound() && $activity->getProvider() !== Activity::PROVIDER_UPLOADER) {
...
|
45376
|
NULL
|
NULL
|
NULL
|
|
45383
|
1625
|
32
|
2026-05-14T14:33:50.810101+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769230810_m1.jpg...
|
PhpStorm
|
faVsco.js – BullhornService.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelplhl100% C•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit K vHandleHubspotRateLimitTest8• Thu 14 May 17:33:50* :QProjectv© UserAutomatedReportsController.php:=custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.php© BullhornLoginHandler.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php© BullhornLoginHandlerInterfa© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© Salesforce/Service.phpT LogActivityTrait.php© BullhornService.php© BullhornSessionDecorator.plPipedrive/Service.phpClose/Service.phpCopper/Service.phpBullhornService.php X© PlainTextDecorateActivity.php© BullhornSessionManager.ph|© ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php= .env.staging18® BullhornSessionManagerInte© FieldDefinitions.phpE.envDetachActivityObject.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpv @ Close> OpportunitySyncStrategy© HubspotPaginationService.phpHandleHubspotRateLimit.phpclass BullhornServiceextends BaseServiceimplements> O Processor> D ProspectSearchStrategy> O Translator© Client.php© CloseException.php4712741275 GГ ›12981299130642 413 M3 ^public function matchByName(string $name, ?int $userId = null): ?array{...-protected function getCacheKey(string $object, ?int $userId = null): ?stringf...}© FieldDefinitions.php1 usage© FieldValueConverter.php1307private function getOwnerKeySuffix(?int $userId = null): string{..© Service.php1311© StandardFieldMetadata.php1312 €public function saveActivity(Activity $activity): Activityv Copper1313> C Apі|1314> D Exception1315> D OpportunitySyncStrategy1316if ($activity->hasCrmProviderId()) {return Sactivity;> D ProspectSearchStrategy1317C Traits1318© FieldDefinitions.php1319© FieldValueConverter.php1320© Service.php1321> @ CrmObjects1322D DecorateActivity1323© BaseDecorateActivity.php1324© PlainTextDecorateActivity.pl1325> C Dummyswitch (Sactivity->type) {case Activity:: TYPE_CONFERENCE:case Activity:: TYPE_SOFTPHONE:case Activity: : TYPE_SOFTPHONE_INBOUND:case Activity::TYPE_SMS_INBOUND:case Activity::TYPE_SMS_OUTBOUND:Sactivity = Sthis->buildNotePayload(Sactivity);1326v D Helpers1327break;T ActivityPlaybookTrait.php1328© Arraylterator.php1329# CannantionCtstaTrait nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]DGo jiminny084143 ×4 л215|•m_layout_id =2162,1661,66799,66217218219id = 33;220221222223224id THEN •(own225226227228229=230hubspot':-231232233 VT234= 11512582;W Windsurf Teams1312:21UTF-8Ca 4 spaces...
|
NULL
|
1783969437749759195
|
NULL
|
visual_change
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelplhl100% C•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit K vHandleHubspotRateLimitTest8• Thu 14 May 17:33:50* :QProjectv© UserAutomatedReportsController.php:=custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.php© BullhornLoginHandler.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php© BullhornLoginHandlerInterfa© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© Salesforce/Service.phpT LogActivityTrait.php© BullhornService.php© BullhornSessionDecorator.plPipedrive/Service.phpClose/Service.phpCopper/Service.phpBullhornService.php X© PlainTextDecorateActivity.php© BullhornSessionManager.ph|© ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php= .env.staging18® BullhornSessionManagerInte© FieldDefinitions.phpE.envDetachActivityObject.phpRematchActivityOnCrmObjectDetach.phpMatchActivityCrmData.phpClient.phpv @ Close> OpportunitySyncStrategy© HubspotPaginationService.phpHandleHubspotRateLimit.phpclass BullhornServiceextends BaseServiceimplements> O Processor> D ProspectSearchStrategy> O Translator© Client.php© CloseException.php4712741275 GГ ›12981299130642 413 M3 ^public function matchByName(string $name, ?int $userId = null): ?array{...-protected function getCacheKey(string $object, ?int $userId = null): ?stringf...}© FieldDefinitions.php1 usage© FieldValueConverter.php1307private function getOwnerKeySuffix(?int $userId = null): string{..© Service.php1311© StandardFieldMetadata.php1312 €public function saveActivity(Activity $activity): Activityv Copper1313> C Apі|1314> D Exception1315> D OpportunitySyncStrategy1316if ($activity->hasCrmProviderId()) {return Sactivity;> D ProspectSearchStrategy1317C Traits1318© FieldDefinitions.php1319© FieldValueConverter.php1320© Service.php1321> @ CrmObjects1322D DecorateActivity1323© BaseDecorateActivity.php1324© PlainTextDecorateActivity.pl1325> C Dummyswitch (Sactivity->type) {case Activity:: TYPE_CONFERENCE:case Activity:: TYPE_SOFTPHONE:case Activity: : TYPE_SOFTPHONE_INBOUND:case Activity::TYPE_SMS_INBOUND:case Activity::TYPE_SMS_OUTBOUND:Sactivity = Sthis->buildNotePayload(Sactivity);1326v D Helpers1327break;T ActivityPlaybookTrait.php1328© Arraylterator.php1329# CannantionCtstaTrait nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]DGo jiminny084143 ×4 л215|•m_layout_id =2162,1661,66799,66217218219id = 33;220221222223224id THEN •(own225226227228229=230hubspot':-231232233 VT234= 11512582;W Windsurf Teams1312:21UTF-8Ca 4 spaces...
|
45382
|
NULL
|
NULL
|
NULL
|
|
45382
|
1625
|
31
|
2026-05-14T14:33:47.768633+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769227768_m1.jpg...
|
PhpStorm
|
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
s
Inherited members (⌘R)
Anonymous Classes (⌘I)
La s
Inherited members (⌘R)
Anonymous Classes (⌘I)
Lambdas (⌘L)
BullhornService, class
ACCOUNT_FIELDS: array|string[] = [...], private
CONTACT_FIELDS: array|string[] = [...], private
ENTITY_ACCOUNT: string = 'ClientCorporation', private
ENTITY_ACTIVITY: string = 'Note', private
ENTITY_CONTACT: string = 'ClientContact', private
ENTITY_LEAD: string = 'Candidate', private
ENTITY_OPPORTUNITY: string = 'JobOrder', private
LEAD_FIELDS: array|string[] = [...], private
OPPORTUNITY_FIELDS: array|string[] = [...], private
TASK_FIELDS: array|string[] = [...], private
TASK_VERIFICATION_CACHE_TTL: int = 86400, private
prospectPhotoPathService: ProspectPhotoPathService, parameter
userRepository: UserRepository, parameter
__construct(client: BullhornClientInterface, userRepository: UserRepository, prospectPhotoPathService: ProspectPhotoPathService) ↑BaseService, method
convertCrmData(entities: array, [userId: int|null = null]): array, method
convertFieldType(type: null|string, specialization: null|string, inputType: null|string): string, method
convertObjectTypeToResource(objectType: string): string, method
convertResourceToObjectType(resource: string): string, method
createTranscriptNotes(activity: Activity): void ↑RemoteEntityManipulationInterface, method
fetchAndAssociateRelatedActivity(activity: Activity): Activity|null ↑FetchRelatedActivityInterface, public method
filterOutOfBoundDates(rawDateCandidate: string): Carbon|null, method
find(name: string, scopes: array): array ↑RemoteEntityLookupInterface, method
findOpportunities(crmAccountId: null|string, crmContactId: null|string, [userId: int|null = null]): array ↑RemoteEntityLookupInterface, method
generateActivityDescription(activity: Activity): string, method
generateProviderUrl(providerId: string, objectType: string): null|string ↑SettingsInterface, method
getCacheKey(object: string, [userId: int|null = null]): null|string, method
getDealInsightsFields(): array|string[][] ↑LayoutManagementInterface, method
getDefaultActivityField(activityType: string): Field ↑LayoutManagementInterface, method
getDefaultFields(activityType: string): array ↑LayoutManagementInterface, method
getDefaultFollowupLayoutFields(activityType: string): array ↑BaseService, method
getDisplayName(): string ↑SettingsInterface, method
getFields(crmObject: string): array ↑BaseService, method
getFieldsAsString(fields: array): string, private method
getFieldTypes(): array ↑BaseService, method
getOAuthAccount(user: User): SocialAccount|null ↑BaseService, method
getObjectFields(objectType: string): array, method
getOwnerKeySuffix([userId: int|null = null]): string, method
getRecord(objectType: string, objectId: string, [fields: array|string[] = [...]]): array ↑RemoteEntityLookupInterface, method
getSupportedPlaybookTypes(): array ↑SettingsInterface, method
getTasks(objectType: string, objectId: string, opportunityId: null|string): array ↑RemoteEntityLookupInterface, method
importPicklistValues(field: Field): array ↑SyncCrmEntitiesInterface, method
importStages([types: array|null = null], [missingStageName: null|string = null]): Stage|null ↑SyncCrmEntitiesInterface, public method
matchByName(name: string, [userId: int|null = null]): array|null ↑MatchCrmEntitiesInterface, method
matchByPhone(phone: string, [rawPhoneNumber: null|string = null], [userId: int|null = null]): array|null ↑MatchCrmEntitiesInterface, method
matchExactlyByEmail(email: string, [userId: int|null = null]): array|null ↑MatchCrmEntitiesInterface, method
normalizeValue(fieldType: string, fieldValue: string, [internal: bool = false]): string ↑SettingsInterface, method
saveActivity(activity: Activity): Activity ↑RemoteEntityManipulationInterface, method
saveFollowupActivity(activity: Activity, fields: array): null|string ↑RemoteEntityManipulationInterface, method
syncAccount(crmId: string): Account|null ↑SyncCrmEntitiesInterface, method
syncAccounts(since: \Carbon\Carbon, [to: \Carbon\Carbon|null = null]): int ↑SyncCrmEntitiesInterface, method
syncContact(crmId: string): Contact|null ↑SyncCrmEntitiesInterface, method
syncContacts(since: \Carbon\Carbon, [to: \Carbon\Carbon|null = null]): int ↑SyncCrmEntitiesInterface, method
syncField(field: Field): void ↑SyncCrmEntitiesInterface, method
syncLead(crmId: string): Lead|null ↑SyncCrmEntitiesInterface, method
syncLeads(since: \Carbon\Carbon, [to: \Carbon\Carbon|null = null], [crmProfileId: null|string = null]): int ↑SyncCrmEntitiesInterface, method
syncOpportunities(parameters: array, [strategy: null|string = null]): int ↑SyncCrmEntitiesInterface, method
syncOpportunity(crmId: string): Opportunity|null ↑SyncCrmEntitiesInterface, method
syncOrganization(): void ↑SyncCrmMetadataInterface, method
syncProfileFields(): void ↑SyncCrmMetadataInterface, method
syncProfiles([userToSearch: User|null = null]): Profile|null ↑SyncCrmMetadataInterface, method
updateRecord(objectType: string, objectId: string, data: array, [headers: array = [...]]): void ↑RemoteEntityManipulationInterface, method...
|
[{"role":"AXTextField","text [{"role":"AXTextField","text":"s","depth":1,"bounds":{"left":0.52152777,"top":0.32,"width":0.06458333,"height":0.031111112},"on_screen":true,"value":"s","role_description":"text field","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Inherited members (⌘R)","depth":1,"bounds":{"left":0.5277778,"top":0.35555556,"width":0.10972222,"height":0.031111112},"on_screen":true,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Anonymous Classes (⌘I)","depth":1,"bounds":{"left":0.64444447,"top":0.35555556,"width":0.10972222,"height":0.031111112},"on_screen":true,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Lambdas (⌘L)","depth":1,"bounds":{"left":0.76111114,"top":0.35555556,"width":0.10972222,"height":0.031111112},"on_screen":true,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"BullhornService, class","depth":4,"bounds":{"left":0.5395833,"top":0.39,"width":0.083333336,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ACCOUNT_FIELDS: array|string[] = [...], private","depth":5,"bounds":{"left":0.55277777,"top":0.41444445,"width":0.19375,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"CONTACT_FIELDS: array|string[] = [...], private","depth":5,"bounds":{"left":0.55277777,"top":0.43888888,"width":0.19305556,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ENTITY_ACCOUNT: string = 'ClientCorporation', private","depth":5,"bounds":{"left":0.55277777,"top":0.46333334,"width":0.22986111,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ENTITY_ACTIVITY: string = 'Note', private","depth":5,"bounds":{"left":0.55277777,"top":0.48777777,"width":0.17083333,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ENTITY_CONTACT: string = 'ClientContact', private","depth":5,"bounds":{"left":0.55277777,"top":0.51222223,"width":0.21180555,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ENTITY_LEAD: string = 'Candidate', private","depth":5,"bounds":{"left":0.55277777,"top":0.5366667,"width":0.17569445,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ENTITY_OPPORTUNITY: string = 'JobOrder', private","depth":5,"bounds":{"left":0.55277777,"top":0.5611111,"width":0.21319444,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"LEAD_FIELDS: array|string[] = [...], private","depth":5,"bounds":{"left":0.55277777,"top":0.58555555,"width":0.17152777,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"OPPORTUNITY_FIELDS: array|string[] = [...], private","depth":5,"bounds":{"left":0.55277777,"top":0.61,"width":0.2125,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"TASK_FIELDS: array|string[] = [...], private","depth":5,"bounds":{"left":0.55277777,"top":0.6344444,"width":0.17222223,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"TASK_VERIFICATION_CACHE_TTL: int = 86400, private","depth":5,"bounds":{"left":0.55277777,"top":0.6588889,"width":0.22847222,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"prospectPhotoPathService: ProspectPhotoPathService, parameter","depth":5,"bounds":{"left":0.55277777,"top":0.68333334,"width":0.25138888,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"userRepository: UserRepository, parameter","depth":5,"bounds":{"left":0.55277777,"top":0.7077778,"width":0.15208334,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"__construct(client: BullhornClientInterface, userRepository: UserRepository, prospectPhotoPathService: ProspectPhotoPathService) ↑BaseService, method","depth":5,"bounds":{"left":0.55277777,"top":0.7322222,"width":0.44722223,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"convertCrmData(entities: array, [userId: int|null = null]): array, method","depth":5,"bounds":{"left":0.55277777,"top":0.75666666,"width":0.27638888,"height":0.024444444},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"convertFieldType(type: null|string, specialization: null|string, inputType: null|string): string, method","depth":5,"bounds":{"left":0.55277777,"top":0.7811111,"width":0.39930555,"height":0.024444444},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"convertObjectTypeToResource(objectType: string): string, method","depth":5,"bounds":{"left":0.55277777,"top":0.8055556,"width":0.2638889,"height":0.024444444},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"convertResourceToObjectType(resource: string): string, method","depth":5,"bounds":{"left":0.55277777,"top":0.83,"width":0.2534722,"height":0.024444444},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"createTranscriptNotes(activity: Activity): void ↑RemoteEntityManipulationInterface, method","depth":5,"bounds":{"left":0.55277777,"top":0.85444444,"width":0.37430555,"height":0.024444444},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"fetchAndAssociateRelatedActivity(activity: Activity): Activity|null ↑FetchRelatedActivityInterface, public method","depth":5,"bounds":{"left":0.55277777,"top":0.8788889,"width":0.44236112,"height":0.024444444},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"filterOutOfBoundDates(rawDateCandidate: string): Carbon|null, method","depth":5,"bounds":{"left":0.55277777,"top":0.9033333,"width":0.28402779,"height":0.024444444},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"find(name: string, scopes: array): array ↑RemoteEntityLookupInterface, method","depth":5,"bounds":{"left":0.55277777,"top":0.92777777,"width":0.32222223,"height":0.024444444},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"findOpportunities(crmAccountId: null|string, crmContactId: null|string, [userId: int|null = null]): array ↑RemoteEntityLookupInterface, method","depth":5,"bounds":{"left":0.55277777,"top":0.9522222,"width":0.44722223,"height":0.024444444},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"generateActivityDescription(activity: Activity): string, method","depth":5,"bounds":{"left":0.55277777,"top":0.9766667,"width":0.23958333,"height":0.023333311},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"generateProviderUrl(providerId: string, objectType: string): null|string ↑SettingsInterface, method","depth":5,"bounds":{"left":0.55277777,"top":1.0,"width":0.3986111,"height":-0.0011111498},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getCacheKey(object: string, [userId: int|null = null]): null|string, method","depth":5,"bounds":{"left":0.55277777,"top":1.0,"width":0.28194445,"height":-0.02555561},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getDealInsightsFields(): array|string[][] ↑LayoutManagementInterface, method","depth":5,"bounds":{"left":0.55277777,"top":1.0,"width":0.31875,"height":-0.049999952},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getDefaultActivityField(activityType: string): Field ↑LayoutManagementInterface, method","depth":5,"bounds":{"left":0.55277777,"top":1.0,"width":0.36458334,"height":-0.07444441},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getDefaultFields(activityType: string): array ↑LayoutManagementInterface, method","depth":5,"bounds":{"left":0.55277777,"top":1.0,"width":0.33819443,"height":-0.098888874},"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getDefaultFollowupLayoutFields(activityType: string): array ↑BaseService, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getDisplayName(): string ↑SettingsInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getFields(crmObject: string): array ↑BaseService, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getFieldsAsString(fields: array): string, private method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getFieldTypes(): array ↑BaseService, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getOAuthAccount(user: User): SocialAccount|null ↑BaseService, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getObjectFields(objectType: string): array, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getOwnerKeySuffix([userId: int|null = null]): string, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getRecord(objectType: string, objectId: string, [fields: array|string[] = [...]]): array ↑RemoteEntityLookupInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getSupportedPlaybookTypes(): array ↑SettingsInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getTasks(objectType: string, objectId: string, opportunityId: null|string): array ↑RemoteEntityLookupInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"importPicklistValues(field: Field): array ↑SyncCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"importStages([types: array|null = null], [missingStageName: null|string = null]): Stage|null ↑SyncCrmEntitiesInterface, public method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"matchByName(name: string, [userId: int|null = null]): array|null ↑MatchCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"matchByPhone(phone: string, [rawPhoneNumber: null|string = null], [userId: int|null = null]): array|null ↑MatchCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"matchExactlyByEmail(email: string, [userId: int|null = null]): array|null ↑MatchCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"normalizeValue(fieldType: string, fieldValue: string, [internal: bool = false]): string ↑SettingsInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"saveActivity(activity: Activity): Activity ↑RemoteEntityManipulationInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"saveFollowupActivity(activity: Activity, fields: array): null|string ↑RemoteEntityManipulationInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncAccount(crmId: string): Account|null ↑SyncCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncAccounts(since: \\Carbon\\Carbon, [to: \\Carbon\\Carbon|null = null]): int ↑SyncCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncContact(crmId: string): Contact|null ↑SyncCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncContacts(since: \\Carbon\\Carbon, [to: \\Carbon\\Carbon|null = null]): int ↑SyncCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncField(field: Field): void ↑SyncCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncLead(crmId: string): Lead|null ↑SyncCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncLeads(since: \\Carbon\\Carbon, [to: \\Carbon\\Carbon|null = null], [crmProfileId: null|string = null]): int ↑SyncCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncOpportunities(parameters: array, [strategy: null|string = null]): int ↑SyncCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncOpportunity(crmId: string): Opportunity|null ↑SyncCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncOrganization(): void ↑SyncCrmMetadataInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncProfileFields(): void ↑SyncCrmMetadataInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncProfiles([userToSearch: User|null = null]): Profile|null ↑SyncCrmMetadataInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"updateRecord(objectType: string, objectId: string, data: array, [headers: array = [...]]): void ↑RemoteEntityManipulationInterface, method","depth":5,"on_screen":false,"role_description":"text"}]...
|
-3989282872089185655
|
-5101129426422577461
|
visual_change
|
accessibility
|
NULL
|
s
Inherited members (⌘R)
Anonymous Classes (⌘I)
La s
Inherited members (⌘R)
Anonymous Classes (⌘I)
Lambdas (⌘L)
BullhornService, class
ACCOUNT_FIELDS: array|string[] = [...], private
CONTACT_FIELDS: array|string[] = [...], private
ENTITY_ACCOUNT: string = 'ClientCorporation', private
ENTITY_ACTIVITY: string = 'Note', private
ENTITY_CONTACT: string = 'ClientContact', private
ENTITY_LEAD: string = 'Candidate', private
ENTITY_OPPORTUNITY: string = 'JobOrder', private
LEAD_FIELDS: array|string[] = [...], private
OPPORTUNITY_FIELDS: array|string[] = [...], private
TASK_FIELDS: array|string[] = [...], private
TASK_VERIFICATION_CACHE_TTL: int = 86400, private
prospectPhotoPathService: ProspectPhotoPathService, parameter
userRepository: UserRepository, parameter
__construct(client: BullhornClientInterface, userRepository: UserRepository, prospectPhotoPathService: ProspectPhotoPathService) ↑BaseService, method
convertCrmData(entities: array, [userId: int|null = null]): array, method
convertFieldType(type: null|string, specialization: null|string, inputType: null|string): string, method
convertObjectTypeToResource(objectType: string): string, method
convertResourceToObjectType(resource: string): string, method
createTranscriptNotes(activity: Activity): void ↑RemoteEntityManipulationInterface, method
fetchAndAssociateRelatedActivity(activity: Activity): Activity|null ↑FetchRelatedActivityInterface, public method
filterOutOfBoundDates(rawDateCandidate: string): Carbon|null, method
find(name: string, scopes: array): array ↑RemoteEntityLookupInterface, method
findOpportunities(crmAccountId: null|string, crmContactId: null|string, [userId: int|null = null]): array ↑RemoteEntityLookupInterface, method
generateActivityDescription(activity: Activity): string, method
generateProviderUrl(providerId: string, objectType: string): null|string ↑SettingsInterface, method
getCacheKey(object: string, [userId: int|null = null]): null|string, method
getDealInsightsFields(): array|string[][] ↑LayoutManagementInterface, method
getDefaultActivityField(activityType: string): Field ↑LayoutManagementInterface, method
getDefaultFields(activityType: string): array ↑LayoutManagementInterface, method
getDefaultFollowupLayoutFields(activityType: string): array ↑BaseService, method
getDisplayName(): string ↑SettingsInterface, method
getFields(crmObject: string): array ↑BaseService, method
getFieldsAsString(fields: array): string, private method
getFieldTypes(): array ↑BaseService, method
getOAuthAccount(user: User): SocialAccount|null ↑BaseService, method
getObjectFields(objectType: string): array, method
getOwnerKeySuffix([userId: int|null = null]): string, method
getRecord(objectType: string, objectId: string, [fields: array|string[] = [...]]): array ↑RemoteEntityLookupInterface, method
getSupportedPlaybookTypes(): array ↑SettingsInterface, method
getTasks(objectType: string, objectId: string, opportunityId: null|string): array ↑RemoteEntityLookupInterface, method
importPicklistValues(field: Field): array ↑SyncCrmEntitiesInterface, method
importStages([types: array|null = null], [missingStageName: null|string = null]): Stage|null ↑SyncCrmEntitiesInterface, public method
matchByName(name: string, [userId: int|null = null]): array|null ↑MatchCrmEntitiesInterface, method
matchByPhone(phone: string, [rawPhoneNumber: null|string = null], [userId: int|null = null]): array|null ↑MatchCrmEntitiesInterface, method
matchExactlyByEmail(email: string, [userId: int|null = null]): array|null ↑MatchCrmEntitiesInterface, method
normalizeValue(fieldType: string, fieldValue: string, [internal: bool = false]): string ↑SettingsInterface, method
saveActivity(activity: Activity): Activity ↑RemoteEntityManipulationInterface, method
saveFollowupActivity(activity: Activity, fields: array): null|string ↑RemoteEntityManipulationInterface, method
syncAccount(crmId: string): Account|null ↑SyncCrmEntitiesInterface, method
syncAccounts(since: \Carbon\Carbon, [to: \Carbon\Carbon|null = null]): int ↑SyncCrmEntitiesInterface, method
syncContact(crmId: string): Contact|null ↑SyncCrmEntitiesInterface, method
syncContacts(since: \Carbon\Carbon, [to: \Carbon\Carbon|null = null]): int ↑SyncCrmEntitiesInterface, method
syncField(field: Field): void ↑SyncCrmEntitiesInterface, method
syncLead(crmId: string): Lead|null ↑SyncCrmEntitiesInterface, method
syncLeads(since: \Carbon\Carbon, [to: \Carbon\Carbon|null = null], [crmProfileId: null|string = null]): int ↑SyncCrmEntitiesInterface, method
syncOpportunities(parameters: array, [strategy: null|string = null]): int ↑SyncCrmEntitiesInterface, method
syncOpportunity(crmId: string): Opportunity|null ↑SyncCrmEntitiesInterface, method
syncOrganization(): void ↑SyncCrmMetadataInterface, method
syncProfileFields(): void ↑SyncCrmMetadataInterface, method
syncProfiles([userToSearch: User|null = null]): Profile|null ↑SyncCrmMetadataInterface, method
updateRecord(objectType: string, objectId: string, data: array, [headers: array = [...]]): void ↑RemoteEntityManipulationInterface, method...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45381
|
1625
|
30
|
2026-05-14T14:33:44.720557+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769224720_m1.jpg...
|
PhpStorm
|
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelplhl100% С•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTest8• Thu 14 May 17:33:44* :QProjectvAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.php© UserAutomatedReportsController.php:=custom.log© FieldDefinitions.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php© FieldValueConverter.php© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© Salesforce/Service.phpT LogActivityTrait.php© Service.php> D CrmObjects© Pipedrive/Service.phpClose/Service.phpCopper/Service.phpBullhornService.php X© PlainTextDecorateActivity.php• DecorateActivity© ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php= .env.staging18© BaseDecorateActivity.php© PlainTextDecorateActivity.plE.envDetachActivityObject.phpRematchActivityOnCrmObjectDetach.php© MatchActivityCrmData.phpClient.php› @ Dummyv Helpers© HubspotPaginationService.phpk?phpHandleHubspotRateLimit.php1T ActivityPlaybookTrait.php© Arraylterator.php3namespace Jiminny (Services \Crm\Bullhorn;T ConnectionStateTrait.php© CrmHelperRepository.phpuse© FilterJoinedParticipants.php46+ OpportunitySyncableFieldsTv D Hubspot• AccountSyncStrategy> OJ Actions |• ContactSyncStrategy> ODTO› Fields› 0 Journal|D Metadatav C OpportunitySyncStrategy> D Concerns© HubspotLastModifiedByF© HubspotLastModifiedCre474849505152535455565758class BullhornService extends BaseService implementsBullhornInterface,SyncCrmEntitiesInterface,SyncCrmMetadataInterface,RemoteEntityManipulationInterface,FetchRelatedActivityInterface,LayoutManagementInterface,SettingsInterface,MatchCrmEntitiesInterface,RemoteEntityLookupInterface,VerifyTaskExistsInterface© HubspotLastModifiedCre© HubspotLastModifiedOpe© HubspotLastModifiedSyn© HubspotSingleSyncStrate5960private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day© HubspotSyncStrategyBa:61private const string ENTITY_LEAD = 'Candidate';© HubspotWebhookBatchSv [ Pagination62private const string ENTITY_OPPORTUNITY = 'JobOrder';© HubspotPaginationServicA DaninatinnCanfin nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]Analyzing…DGo jiminny084143 ×4 л215|•m_layout_id =2162,1661,66799,66217218219.id = 33;220221222223224id THEN •(own225226227228229230hubspot':-231232233 V= 11512582;234W Windsurf Teams 1:1UTF-8Ca 4 spaces...
|
NULL
|
-2090151520793946511
|
NULL
|
visual_change
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelplhl100% С•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTest8• Thu 14 May 17:33:44* :QProjectvAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.php© UserAutomatedReportsController.php:=custom.log© FieldDefinitions.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.phpDeleteCrmEntityTrait.phpDeleteAccountJob.php© FieldValueConverter.php© ImportActivityTypes.phpT WriteCrmTrait.php© DecorateActivity.php© Salesforce/Service.phpT LogActivityTrait.php© Service.php> D CrmObjects© Pipedrive/Service.phpClose/Service.phpCopper/Service.phpBullhornService.php X© PlainTextDecorateActivity.php• DecorateActivity© ActivityPlaybookTrait.phpCrmHelperRepository.php© AccountController.phpT IntegrationAppTrait.php= .env.staging18© BaseDecorateActivity.php© PlainTextDecorateActivity.plE.envDetachActivityObject.phpRematchActivityOnCrmObjectDetach.php© MatchActivityCrmData.phpClient.php› @ Dummyv Helpers© HubspotPaginationService.phpk?phpHandleHubspotRateLimit.php1T ActivityPlaybookTrait.php© Arraylterator.php3namespace Jiminny (Services \Crm\Bullhorn;T ConnectionStateTrait.php© CrmHelperRepository.phpuse© FilterJoinedParticipants.php46+ OpportunitySyncableFieldsTv D Hubspot• AccountSyncStrategy> OJ Actions |• ContactSyncStrategy> ODTO› Fields› 0 Journal|D Metadatav C OpportunitySyncStrategy> D Concerns© HubspotLastModifiedByF© HubspotLastModifiedCre474849505152535455565758class BullhornService extends BaseService implementsBullhornInterface,SyncCrmEntitiesInterface,SyncCrmMetadataInterface,RemoteEntityManipulationInterface,FetchRelatedActivityInterface,LayoutManagementInterface,SettingsInterface,MatchCrmEntitiesInterface,RemoteEntityLookupInterface,VerifyTaskExistsInterface© HubspotLastModifiedCre© HubspotLastModifiedOpe© HubspotLastModifiedSyn© HubspotSingleSyncStrate5960private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day© HubspotSyncStrategyBa:61private const string ENTITY_LEAD = 'Candidate';© HubspotWebhookBatchSv [ Pagination62private const string ENTITY_OPPORTUNITY = 'JobOrder';© HubspotPaginationServicA DaninatinnCanfin nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]Analyzing…DGo jiminny084143 ×4 л215|•m_layout_id =2162,1661,66799,66217218219.id = 33;220221222223224id THEN •(own225226227228229230hubspot':-231232233 V= 11512582;234W Windsurf Teams 1:1UTF-8Ca 4 spaces...
|
45380
|
NULL
|
NULL
|
NULL
|
|
45380
|
1625
|
29
|
2026-05-14T14:33:41.693591+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769221693_m1.jpg...
|
PhpStorm
|
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project Files
Preview
Filter
Open in Find Tool Win Project Files
Preview
Filter
Open in Find Tool Window
bullhorn/
Bullhorn app/Services/Crm/Bullhorn
Bullhorn tests/Unit/Services/Crm/Bullhorn
Bullhorn build/coverage/Services/Crm/Bullhorn
BullhornClient.php .../app/Services/Crm/Bullhorn/BullhornClient.php, class
BullhornInterface.php .../app/Contracts/Services/Crm/Provider/BullhornInterface.php, interface
BullhornClientInterface.php .../app/Services/Crm/Bullhorn/BullhornClientInterface.php, interface
BullhornCommandAbstract.php .../app/Console/Commands/Crm/BullhornCommandAbstract.php, abstract class
BullhornDefaultStrategy.php .../app/.../Bullhorn/ProspectSearchStrategy/BullhornDefaultStrategy.php, class
BullhornLastModifiedSyncStrategy.php .../BullhornLastModifiedSyncStrategy.php, class
BullhornLastModifiedByProfileSyncStrategy.php .../BullhornLastModifiedByProfileSyncStrategy.php, class
BullhornClient.php.html build/coverage/Services/Crm/Bullhorn
BullhornClientInterface.php.html build/coverage/Services/Crm/Bullhorn
BullhornCommandAbstract.php.html build/coverage/Console/Commands/Crm
BullhornDefaultStrategy.php.html build/coverage/Services/Crm/Bullhorn/ProspectSearchStrategy
BullhornLastModifiedSyncStrategy.php.html build/coverage/.../Crm/Bullhorn/OpportunitySyncStrategy
Bullhorn app/Services/Crm/Bullhorn
Bullhorn tests/Unit/Services/Crm/Bullhorn
Bullhorn build/coverage/Services/Crm/Bullhorn
Services/Crm/Bullhorn
Open In Right Split...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project Files","depth":2,"bounds":{"left":0.8298611,"top":0.25,"width":0.07430556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Preview","depth":2,"bounds":{"left":0.90416664,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Filter","depth":2,"bounds":{"left":0.9222222,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open in Find Tool Window","depth":2,"bounds":{"left":0.94027776,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextField","text":"bullhorn/","depth":1,"bounds":{"left":0.50555557,"top":0.29222223,"width":0.45277777,"height":0.032222223},"on_screen":true,"value":"bullhorn/","role_description":"text field","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Bullhorn app/Services/Crm/Bullhorn","depth":2,"bounds":{"left":0.49930555,"top":0.33666667,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"Bullhorn tests/Unit/Services/Crm/Bullhorn","depth":2,"bounds":{"left":0.49930555,"top":0.3611111,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"Bullhorn build/coverage/Services/Crm/Bullhorn","depth":2,"bounds":{"left":0.49930555,"top":0.38555557,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"BullhornClient.php .../app/Services/Crm/Bullhorn/BullhornClient.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.41,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"BullhornInterface.php .../app/Contracts/Services/Crm/Provider/BullhornInterface.php, interface","depth":2,"bounds":{"left":0.49930555,"top":0.43444446,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"BullhornClientInterface.php .../app/Services/Crm/Bullhorn/BullhornClientInterface.php, interface","depth":2,"bounds":{"left":0.49930555,"top":0.4588889,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"BullhornCommandAbstract.php .../app/Console/Commands/Crm/BullhornCommandAbstract.php, abstract class","depth":2,"bounds":{"left":0.49930555,"top":0.48333332,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"BullhornDefaultStrategy.php .../app/.../Bullhorn/ProspectSearchStrategy/BullhornDefaultStrategy.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.50777775,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"BullhornLastModifiedSyncStrategy.php .../BullhornLastModifiedSyncStrategy.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.5322222,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"BullhornLastModifiedByProfileSyncStrategy.php .../BullhornLastModifiedByProfileSyncStrategy.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.5566667,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"BullhornClient.php.html build/coverage/Services/Crm/Bullhorn","depth":2,"bounds":{"left":0.49930555,"top":0.58111113,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"BullhornClientInterface.php.html build/coverage/Services/Crm/Bullhorn","depth":2,"bounds":{"left":0.49930555,"top":0.60555553,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"BullhornCommandAbstract.php.html build/coverage/Console/Commands/Crm","depth":2,"bounds":{"left":0.49930555,"top":0.63,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"BullhornDefaultStrategy.php.html build/coverage/Services/Crm/Bullhorn/ProspectSearchStrategy","depth":2,"bounds":{"left":0.49930555,"top":0.65444446,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"BullhornLastModifiedSyncStrategy.php.html build/coverage/.../Crm/Bullhorn/OpportunitySyncStrategy","depth":2,"bounds":{"left":0.49930555,"top":0.6788889,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"Bullhorn app/Services/Crm/Bullhorn","depth":4,"bounds":{"left":0.49930555,"top":0.33666667,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"Bullhorn tests/Unit/Services/Crm/Bullhorn","depth":4,"bounds":{"left":0.49930555,"top":0.3611111,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"Bullhorn build/coverage/Services/Crm/Bullhorn","depth":4,"bounds":{"left":0.49930555,"top":0.38555557,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"Services/Crm/Bullhorn","depth":1,"bounds":{"left":0.51319444,"top":0.74777776,"width":0.0875,"height":0.018888889},"on_screen":true,"help_text":"Services/Crm/Bullhorn","role_description":"text"},{"role":"AXLink","text":"Open In Right Split","depth":1,"bounds":{"left":0.8673611,"top":0.74777776,"width":0.08055556,"height":0.018888889},"on_screen":true,"role_description":"link","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
2774422303295767760
|
-7342671818821146656
|
visual_change
|
accessibility
|
NULL
|
Project Files
Preview
Filter
Open in Find Tool Win Project Files
Preview
Filter
Open in Find Tool Window
bullhorn/
Bullhorn app/Services/Crm/Bullhorn
Bullhorn tests/Unit/Services/Crm/Bullhorn
Bullhorn build/coverage/Services/Crm/Bullhorn
BullhornClient.php .../app/Services/Crm/Bullhorn/BullhornClient.php, class
BullhornInterface.php .../app/Contracts/Services/Crm/Provider/BullhornInterface.php, interface
BullhornClientInterface.php .../app/Services/Crm/Bullhorn/BullhornClientInterface.php, interface
BullhornCommandAbstract.php .../app/Console/Commands/Crm/BullhornCommandAbstract.php, abstract class
BullhornDefaultStrategy.php .../app/.../Bullhorn/ProspectSearchStrategy/BullhornDefaultStrategy.php, class
BullhornLastModifiedSyncStrategy.php .../BullhornLastModifiedSyncStrategy.php, class
BullhornLastModifiedByProfileSyncStrategy.php .../BullhornLastModifiedByProfileSyncStrategy.php, class
BullhornClient.php.html build/coverage/Services/Crm/Bullhorn
BullhornClientInterface.php.html build/coverage/Services/Crm/Bullhorn
BullhornCommandAbstract.php.html build/coverage/Console/Commands/Crm
BullhornDefaultStrategy.php.html build/coverage/Services/Crm/Bullhorn/ProspectSearchStrategy
BullhornLastModifiedSyncStrategy.php.html build/coverage/.../Crm/Bullhorn/OpportunitySyncStrategy
Bullhorn app/Services/Crm/Bullhorn
Bullhorn tests/Unit/Services/Crm/Bullhorn
Bullhorn build/coverage/Services/Crm/Bullhorn
Services/Crm/Bullhorn
Open In Right Split...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45379
|
1625
|
28
|
2026-05-14T14:33:38.664867+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769218664_m1.jpg...
|
PhpStorm
|
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project Files
Preview
Filter
Open in Find Tool Win Project Files
Preview
Filter
Open in Find Tool Window
bootstrap
Open In Right Split...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project Files","depth":2,"bounds":{"left":0.8298611,"top":0.25,"width":0.07430556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Preview","depth":2,"bounds":{"left":0.90416664,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Filter","depth":2,"bounds":{"left":0.9222222,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open in Find Tool Window","depth":2,"bounds":{"left":0.94027776,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"bootstrap","depth":1,"bounds":{"left":0.51319444,"top":0.30888888,"width":0.038194444,"height":0.018888889},"on_screen":true,"help_text":"bootstrap","role_description":"text"},{"role":"AXLink","text":"Open In Right Split","depth":1,"bounds":{"left":0.8673611,"top":0.30888888,"width":0.08055556,"height":0.018888889},"on_screen":true,"role_description":"link","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-2254067575783512575
|
-9222643463564451140
|
visual_change
|
hybrid
|
NULL
|
Project Files
Preview
Filter
Open in Find Tool Win Project Files
Preview
Filter
Open in Find Tool Window
bootstrap
Open In Right Split
PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpablFV faVsco.js* #12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTest100% (C478• Thu 14 May 17:33:38QProjectv:= custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php© FieldDefinitions.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php=laravel.log© FieldValueConverter.php• DeleteCrmEntityTrait.phpDeleteAccountJob.phpImportActivityTypes.phpT WriteCrmTrait.php© Service.php© DecorateActivity.phpSF [jiminny@localhost]> D CrmObjects© Salesforce/Service.php© LogActivityTrait.phpPipedrive/Service.phpClose/Service.phpCopper/Service.php XA HS_local [jiminny@localho:W• DecorateActivity© PlainTextDecorateActivity.phpT ActivityPlaybookTrait.phpCrmHelperRepository.phpAccountController.php4 console [QAI PROD] X18© BaseDecorateActivity.php© PlainTextDecorateActivity.plT IntegrationAppTrait.php.env.staging.env© DeiAllClassesFilesSymbolsActionsTextProject Files v> Dummyv HelpersT ActivityPlaybookTrait.php521664© Arraylterator.phpT ConnectionStateTrait.php1679© CrmHelperRepository.php1680© MatchActivityCrmData.php© Client.php© HubspotPaginaclass Service extends BaseService implementsprivate function buildCallPayload(Activity Sactivity): Activity1);} else {© FilterJoinedParticipants.php1681© OpportunitySyncableFieldsT 1682v D Hubspot1683• AccountSyncStrategy1684throw new CrmException($message,code: 400):> @ Actions|1685• ContactSyncStrategy1686> ODTO1687› Fields1688> 0J Journal1689• Metadata1690v C OpportunitySyncStrategy1691> D Concerns1692© HubspotLastModifiedByF 1693© HubspotLastModifiedCre1694© HubspotLastModifiedCre1695HubspotLastModifiedOpe1696© HubspotLastModifiedSyn16971698215216if (Sthis-~getCrmType(Sactivitx~~categocx)mmllnt217Smessage = sprintf( format: "[Copper] Invalid CRM Activity Type: %S', Sactivity->category≥.218219=220221==222if ($this->getCrmType($activity->category)->value === null) 1E223Smessage = sprintf( format: '[Copper] Invalid CRM Activity Type: %s value', $activity->cate 224225)=226= 227228= 229= 230-231+252+ 233 v23408 41A3 ×4 ^•m_layout_id =2,1661,66799,66id = 33;id THEN •(ownthrow new CrmException(Smessage,code: 400):© HubspotSingleSyncStrate// Just create an activity.$cpActivity = $this->copperClient-›activities()->create(['user_id' => $this->profile->crm_provider_id,'activity_date' => $activity->scheduled_start_time->timestamp,'parent' => $this->convertActivityAssoCiations($activity),'type' => $this->convertActivityType(Sactivity->category),'details' => Sthis->generateActivityDescription(Sactivity),hubspot':= 11512582;© HubspotSyncStrategyBa:16991):© HubspotWebhookBatchS1700v [ Pagination1701© HubspotPaginationServic1702Sactivity->crm_provider_id = $cpActivityl'id'];Sactivity->saveO;A Daninstinnfanfin nhn1703=Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams1697:45UTF-8Ca 4 spaces...
|
45378
|
NULL
|
NULL
|
NULL
|
|
45378
|
1625
|
27
|
2026-05-14T14:33:35.653395+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769215653_m1.jpg...
|
PhpStorm
|
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
All Places
Preview
Filter
Open in Find Tool Window All Places
Preview
Filter
Open in Find Tool Window
bhse
HubspotPaginationServiceTest.php .../tests/.../Hubspot/Pagination/HubspotPaginationServiceTest.php, class
HubspotPaginationService.php .../app/Services/Crm/Hubspot/Pagination/HubspotPaginationService.php, class
BladeHasSectionTest.php vendor/laravel/framework/tests/View/Blade/BladeHasSectionTest.php, class
HubSpotServicePreparationException.php .../.../Crm/Hubspot/HubSpotServicePreparationException.php, exception class
HubspotDealWebhookService.php .../app/.../Crm/Hubspot/Journal/HubspotDealWebhookService.php
HubspotDealWebhookServiceTest.php .../.../Hubspot/Journal/HubspotDealWebhookServiceTest.php, class
HubspotJournalPollingService.php .../app/.../Crm/Hubspot/Journal/HubspotJournalPollingService.php, class
HubspotJournalPollingServiceTest.php .../.../Hubspot/Journal/HubspotJournalPollingServiceTest.php, class
HubspotWebhookMetricsService.php .../app/.../Hubspot/Webhook/HubspotWebhookMetricsService.php, class
HubspotWebhookMetricsServiceTest.php .../.../Webhook/HubspotWebhookMetricsServiceTest.php, class
HubspotWebhookSubscriptionService.php .../.../Journal/HubspotWebhookSubscriptionService.php, class
HubspotWebhookSubscriptionServiceTest.php .../Journal/HubspotWebhookSubscriptionServiceTest.php, class
HasAvailableSeats.php.html build/coverage/Rules
HttpSessionExpiredException.php.html build/coverage/Exceptions
ItemHydratorServiceInterface.php.html build/coverage/Component/LiveFeed/Hydrator
… more
HubspotPaginationServiceTest.php .../tests/.../Hubspot/Pagination/HubspotPaginationServiceTest.php, class
HubspotPaginationService.php .../app/Services/Crm/Hubspot/Pagination/HubspotPaginationService.php, class
BladeHasSectionTest.php vendor/laravel/framework/tests/View/Blade/BladeHasSectionTest.php, class
HubSpotServicePreparationException.php .../.../Crm/Hubspot/HubSpotServicePreparationException.php, exception class
HubspotDealWebhookService.php .../app/.../Crm/Hubspot/Journal/HubspotDealWebhookService.php
HubspotDealWebhookServiceTest.php .../.../Hubspot/Journal/HubspotDealWebhookServiceTest.php, class
HubspotJournalPollingService.php .../app/.../Crm/Hubspot/Journal/HubspotJournalPollingService.php, class
HubspotJournalPollingServiceTest.php .../.../Hubspot/Journal/HubspotJournalPollingServiceTest.php, class
HubspotWebhookMetricsService.php .../app/.../Hubspot/Webhook/HubspotWebhookMetricsService.php, class
HubspotWebhookMetricsServiceTest.php .../.../Webhook/HubspotWebhookMetricsServiceTest.php, class
HubspotWebhookSubscriptionService.php .../.../Journal/HubspotWebhookSubscriptionService.php, class
HubspotWebhookSubscriptionServiceTest.php .../Journal/HubspotWebhookSubscriptionServiceTest.php, class
HasAvailableSeats.php.html build/coverage/Rules
HttpSessionExpiredException.php.html build/coverage/Exceptions
ItemHydratorServiceInterface.php.html build/coverage/Component/LiveFeed/Hydrator
… more
Unit/Services/Crm/Hubspot/Pagination/HubspotPaginationServiceTest.php
Open In Right Split...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"All Places","depth":2,"bounds":{"left":0.8423611,"top":0.25,"width":0.061805554,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Preview","depth":2,"bounds":{"left":0.90416664,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Filter","depth":2,"bounds":{"left":0.9222222,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open in Find Tool Window","depth":2,"bounds":{"left":0.94027776,"top":0.25,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextField","text":"bhse","depth":1,"bounds":{"left":0.50555557,"top":0.29222223,"width":0.45277777,"height":0.032222223},"on_screen":true,"value":"bhse","role_description":"text field","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"HubspotPaginationServiceTest.php .../tests/.../Hubspot/Pagination/HubspotPaginationServiceTest.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.33666667,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubspotPaginationService.php .../app/Services/Crm/Hubspot/Pagination/HubspotPaginationService.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.3611111,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"BladeHasSectionTest.php vendor/laravel/framework/tests/View/Blade/BladeHasSectionTest.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.38555557,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubSpotServicePreparationException.php .../.../Crm/Hubspot/HubSpotServicePreparationException.php, exception class","depth":2,"bounds":{"left":0.49930555,"top":0.41,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubspotDealWebhookService.php .../app/.../Crm/Hubspot/Journal/HubspotDealWebhookService.php","depth":2,"bounds":{"left":0.49930555,"top":0.43444446,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubspotDealWebhookServiceTest.php .../.../Hubspot/Journal/HubspotDealWebhookServiceTest.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.4588889,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubspotJournalPollingService.php .../app/.../Crm/Hubspot/Journal/HubspotJournalPollingService.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.48333332,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubspotJournalPollingServiceTest.php .../.../Hubspot/Journal/HubspotJournalPollingServiceTest.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.50777775,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubspotWebhookMetricsService.php .../app/.../Hubspot/Webhook/HubspotWebhookMetricsService.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.5322222,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubspotWebhookMetricsServiceTest.php .../.../Webhook/HubspotWebhookMetricsServiceTest.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.5566667,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubspotWebhookSubscriptionService.php .../.../Journal/HubspotWebhookSubscriptionService.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.58111113,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubspotWebhookSubscriptionServiceTest.php .../Journal/HubspotWebhookSubscriptionServiceTest.php, class","depth":2,"bounds":{"left":0.49930555,"top":0.60555553,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HasAvailableSeats.php.html build/coverage/Rules","depth":2,"bounds":{"left":0.49930555,"top":0.63,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HttpSessionExpiredException.php.html build/coverage/Exceptions","depth":2,"bounds":{"left":0.49930555,"top":0.65444446,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ItemHydratorServiceInterface.php.html build/coverage/Component/LiveFeed/Hydrator","depth":2,"bounds":{"left":0.49930555,"top":0.6788889,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"… more","depth":2,"bounds":{"left":0.49930555,"top":0.7033333,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubspotPaginationServiceTest.php .../tests/.../Hubspot/Pagination/HubspotPaginationServiceTest.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.33666667,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubspotPaginationService.php .../app/Services/Crm/Hubspot/Pagination/HubspotPaginationService.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.3611111,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"BladeHasSectionTest.php vendor/laravel/framework/tests/View/Blade/BladeHasSectionTest.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.38555557,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubSpotServicePreparationException.php .../.../Crm/Hubspot/HubSpotServicePreparationException.php, exception class","depth":4,"bounds":{"left":0.49930555,"top":0.41,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubspotDealWebhookService.php .../app/.../Crm/Hubspot/Journal/HubspotDealWebhookService.php","depth":4,"bounds":{"left":0.49930555,"top":0.43444446,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubspotDealWebhookServiceTest.php .../.../Hubspot/Journal/HubspotDealWebhookServiceTest.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.4588889,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubspotJournalPollingService.php .../app/.../Crm/Hubspot/Journal/HubspotJournalPollingService.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.48333332,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubspotJournalPollingServiceTest.php .../.../Hubspot/Journal/HubspotJournalPollingServiceTest.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.50777775,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubspotWebhookMetricsService.php .../app/.../Hubspot/Webhook/HubspotWebhookMetricsService.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.5322222,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubspotWebhookMetricsServiceTest.php .../.../Webhook/HubspotWebhookMetricsServiceTest.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.5566667,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubspotWebhookSubscriptionService.php .../.../Journal/HubspotWebhookSubscriptionService.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.58111113,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HubspotWebhookSubscriptionServiceTest.php .../Journal/HubspotWebhookSubscriptionServiceTest.php, class","depth":4,"bounds":{"left":0.49930555,"top":0.60555553,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HasAvailableSeats.php.html build/coverage/Rules","depth":4,"bounds":{"left":0.49930555,"top":0.63,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"HttpSessionExpiredException.php.html build/coverage/Exceptions","depth":4,"bounds":{"left":0.49930555,"top":0.65444446,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"ItemHydratorServiceInterface.php.html build/coverage/Component/LiveFeed/Hydrator","depth":4,"bounds":{"left":0.49930555,"top":0.6788889,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"… more","depth":4,"bounds":{"left":0.49930555,"top":0.7033333,"width":0.4652778,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"Unit/Services/Crm/Hubspot/Pagination/HubspotPaginationServiceTest.php","depth":1,"bounds":{"left":0.51319444,"top":0.74777776,"width":0.29375,"height":0.018888889},"on_screen":true,"help_text":"Unit/Services/Crm/Hubspot/Pagination/HubspotPaginationServiceTest.php","role_description":"text"},{"role":"AXLink","text":"Open In Right Split","depth":1,"bounds":{"left":0.8673611,"top":0.74777776,"width":0.08055556,"height":0.018888889},"on_screen":true,"role_description":"link","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-8644524876484404324
|
921475024034100431
|
visual_change
|
accessibility
|
NULL
|
All Places
Preview
Filter
Open in Find Tool Window All Places
Preview
Filter
Open in Find Tool Window
bhse
HubspotPaginationServiceTest.php .../tests/.../Hubspot/Pagination/HubspotPaginationServiceTest.php, class
HubspotPaginationService.php .../app/Services/Crm/Hubspot/Pagination/HubspotPaginationService.php, class
BladeHasSectionTest.php vendor/laravel/framework/tests/View/Blade/BladeHasSectionTest.php, class
HubSpotServicePreparationException.php .../.../Crm/Hubspot/HubSpotServicePreparationException.php, exception class
HubspotDealWebhookService.php .../app/.../Crm/Hubspot/Journal/HubspotDealWebhookService.php
HubspotDealWebhookServiceTest.php .../.../Hubspot/Journal/HubspotDealWebhookServiceTest.php, class
HubspotJournalPollingService.php .../app/.../Crm/Hubspot/Journal/HubspotJournalPollingService.php, class
HubspotJournalPollingServiceTest.php .../.../Hubspot/Journal/HubspotJournalPollingServiceTest.php, class
HubspotWebhookMetricsService.php .../app/.../Hubspot/Webhook/HubspotWebhookMetricsService.php, class
HubspotWebhookMetricsServiceTest.php .../.../Webhook/HubspotWebhookMetricsServiceTest.php, class
HubspotWebhookSubscriptionService.php .../.../Journal/HubspotWebhookSubscriptionService.php, class
HubspotWebhookSubscriptionServiceTest.php .../Journal/HubspotWebhookSubscriptionServiceTest.php, class
HasAvailableSeats.php.html build/coverage/Rules
HttpSessionExpiredException.php.html build/coverage/Exceptions
ItemHydratorServiceInterface.php.html build/coverage/Component/LiveFeed/Hydrator
… more
HubspotPaginationServiceTest.php .../tests/.../Hubspot/Pagination/HubspotPaginationServiceTest.php, class
HubspotPaginationService.php .../app/Services/Crm/Hubspot/Pagination/HubspotPaginationService.php, class
BladeHasSectionTest.php vendor/laravel/framework/tests/View/Blade/BladeHasSectionTest.php, class
HubSpotServicePreparationException.php .../.../Crm/Hubspot/HubSpotServicePreparationException.php, exception class
HubspotDealWebhookService.php .../app/.../Crm/Hubspot/Journal/HubspotDealWebhookService.php
HubspotDealWebhookServiceTest.php .../.../Hubspot/Journal/HubspotDealWebhookServiceTest.php, class
HubspotJournalPollingService.php .../app/.../Crm/Hubspot/Journal/HubspotJournalPollingService.php, class
HubspotJournalPollingServiceTest.php .../.../Hubspot/Journal/HubspotJournalPollingServiceTest.php, class
HubspotWebhookMetricsService.php .../app/.../Hubspot/Webhook/HubspotWebhookMetricsService.php, class
HubspotWebhookMetricsServiceTest.php .../.../Webhook/HubspotWebhookMetricsServiceTest.php, class
HubspotWebhookSubscriptionService.php .../.../Journal/HubspotWebhookSubscriptionService.php, class
HubspotWebhookSubscriptionServiceTest.php .../Journal/HubspotWebhookSubscriptionServiceTest.php, class
HasAvailableSeats.php.html build/coverage/Rules
HttpSessionExpiredException.php.html build/coverage/Exceptions
ItemHydratorServiceInterface.php.html build/coverage/Component/LiveFeed/Hydrator
… more
Unit/Services/Crm/Hubspot/Pagination/HubspotPaginationServiceTest.php
Open In Right Split...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45377
|
1625
|
26
|
2026-05-14T14:33:28.043331+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769208043_m1.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.6645833,"top":0.027777778,"width":0.15902779,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.82361114,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.8472222,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.87083334,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.9291667,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9527778,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9763889,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
6814957943380363182
|
-8708761519200826421
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit K vabl19HandleHubspotRateLimitTest100% C8• Thu 14 May 17:33:27* :QProjectv=custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php© FieldDefinitions.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php© FieldValueConverter.php• DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© Service.php© DecorateActivity.php> D CrmObjects© Salesforce/Service.php© LogActivityTrait.php© Pipedrive/Service.php© Close/Service.phpCopper/Service.php X• DecorateActivity© PlainTextDecorateActivity.phpT ActivityPlaybookTrait.php© CrmHelperRepository.php© AccountController.php18© BaseDecorateActivity.php© PlainTextDecorateActivity.plE.env© DetachActivityObject.php> D Dummyv HelpersT ActivityPlaybookTrait.php521612© Arraylterator.phpT IntegrationAppTrait.php=.env.staging© MatchActivityCrmData.php© Client.php© HubspotPaginationService.phpclass Service extends BaseService implementspublic functionsaveActivity(Activity $activity): ActivityRematchActivityOnCrmObjectDetach.php© HandleHubspotRateLimit.php811 472 M1 м4 лT ConnectionStateTrait.php1627© CrmHelperRepository.php1628return Sactivity:© FilterJoinedParticipants.php1629+ OpportunitySyncableFieldsT1630v D Hubspot4 usages• AccountSyncStrategy> OJ Actions |16311652private function convertActivityAssociations(Activity $activity): array{...}• ContactSyncStrategy2 usages> ODTO1653private function convertActivityType(PlaybookCategory $activityType): array› Fields1654› 0 Journal1655• Metadata1656v C OpportunitySyncStrategy1657return ['category' => 'user','id'=> $this->getCrmType($activityType)->value,› D Concerns16581;© HubspotLastModifiedByF 1659}© HubspotLastModifiedCre1660© HubspotLastModifiedCre1661HubspotLastModifiedOpe1662© HubspotLastModifiedSyn1663© HubspotSingleSyncStrate/***/1 usage* @throws CrmException© HubspotSyncStrategyBa: 1664private function buildCallPayload(Activity $activity): Activity© HubspotWebhookBatchS1665-v [ Pagination1666try {© HubspotPaginationServic1667if (Sactivity->crm_provider_id) {A DaninatinnCanfin nhn1668f The activity should be loqged under the existing lask (not Activity)=Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]DGo jiminny084143 ×4 л215•m_layout_id =2162,1661,66799,66217218219=id = 33;220221==222E 223=224id THEN •(own225)=226= 227228- 229I230T231"hubspot';— 232- 233 v= 11512582;=2341653:22UTF-8Ca 4 spaces...
|
45375
|
NULL
|
NULL
|
NULL
|
|
45376
|
1626
|
17
|
2026-05-14T14:33:24.529049+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769204529_m2.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
11
72
1
4
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Copper;
use Carbon\Carbon;
use Exception;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Facades\Cache;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\CopperInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\FieldValue;
use Jiminny\Models\Crm\LayoutEntity;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\PlaybookCategory;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\UserRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\Copper\Api\Client;
use Jiminny\Services\Crm\Copper\Api\ClientFactory;
use Jiminny\Services\Crm\Copper\Exception\RequestFailedException;
use Jiminny\Services\Crm\Helpers\FilterJoinedParticipants;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Services\Crm\Copper\Traits\SearchesCrmEntities;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
class Service extends BaseService implements
CopperInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
use SearchesCrmEntities;
private const int NOTE_BODY_MAX_LENGTH = 3000000;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const array STANDARD_OPPORTUNITY_FIELDS = [
'monetary_value' => [
'label' => 'Value',
'available_on' => Field::OBJECT_OPPORTUNITY,
'type' => Field::TYPE_CURRENCY,
],
'pipeline_stage_id' => [
'label' => 'Stage',
'type' => Field::TYPE_PICKLIST,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
'close_date' => [
'label' => 'Close date',
'type' => Field::TYPE_DATE,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
'win_probability' => [
'label' => 'Win probability',
'type' => Field::TYPE_NUMBER,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
];
private const string UNSUPPORTED_OBJECT_TYPE = 'unsupported';
private const string OPPORTUNITY_STATUS_OPEN = 'Open';
private const string OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE = 'Opportunity import failed';
private const string RESOURCE_UPDATE_FAILED_ERROR_MESSAGE = 'Failed to update resource';
private FieldValueConverter $fieldValueConverter;
private ClientFactory $clientFactory;
private ?Client $copperClient = null;
public function __construct(
ClientFactory $clientFactory,
FieldValueConverter $fieldValueConverter,
private readonly UserRepository $userRepository,
private readonly ProspectPhotoPathService $prospectPhotoPathService,
private readonly CrmEntityRepository $crmEntityRepository
) {
parent::__construct();
$this->clientFactory = $clientFactory;
$this->fieldValueConverter = $fieldValueConverter;
}
public function getDisplayName(): string
{
return 'Copper';
}
/**
* Get the CRM entity repository (used by SearchesCrmEntities trait)
*/
protected function getCrmEntityRepository(): CrmEntityRepository
{
return $this->crmEntityRepository;
}
public function getMinimumApiVersion(): string
{
return Client::MIN_API_VERSION;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_COPPER);
}
public function setUser(User $user): void
{
$this->configureSentryScope($user);
$this->team = $user->getTeam();
$this->teamService->setTeam($user->getTeam());
$this->setConfiguration($user->getTeam()->getCrmConfiguration());
// Reset state.
$this->profile = $user->getProfile();
if (! $this->profile instanceof Profile) {
// Try to fetch their profile, maybe it was not yet imported?
$this->profile = $this->getProfile($user);
}
}
public function setConfiguration(Configuration $configuration): void
{
$this->config = $configuration;
$this->copperClient = $this->clientFactory->create($configuration);
if ($this->team === null) {
$this->team = $configuration->getTeam();
}
}
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return $this->fieldValueConverter->convertFromCrm($fieldType, $fieldValue);
}
private function mapObjectType(string $objectType): string
{
$objectType = strtolower($objectType);
switch ($objectType) {
case Field::OBJECT_TASK:
case Field::OBJECT_OPPORTUNITY:
case Field::OBJECT_LEAD:
$mappedType = $objectType;
break;
case Field::OBJECT_ACCOUNT:
$mappedType = 'company';
break;
case Field::OBJECT_CONTACT:
$mappedType = 'person';
break;
default:
$mappedType = self::UNSUPPORTED_OBJECT_TYPE;
break;
}
return $mappedType;
}
/**
* @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact
*/
protected function getFields(string $crmObject): array
{
$mappedObjectType = $this->mapObjectType($crmObject);
if (! $this->isSupportedObjectType($mappedObjectType)) {
return [];
}
$customFields = $this->copperClient->fields()->all();
$filteredFields = array_filter(
$customFields,
static fn ($field) => in_array($mappedObjectType, $field['available_on'], true)
);
return array_map(
fn (array $property) => [
'name' => $property['id'],
'label' => $property['name'],
'type' => $this->convertFieldType($property['data_type']),
],
$filteredFields
);
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {
$defaultFields = FieldDefinitions::defaultTaskFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldFilters = FieldDefinitions::taskFollowupFieldsFilter();
foreach ($fieldFilters as $data) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
public function syncFields(): void
{
$this->syncStandardFields();
$this->syncCustomFields();
}
public function syncField(Field $field): void
{
if ($field->getCrmProviderId() === 'type') {
/**
* This field is a special case, it is not a custom field and is not returned by the Copper API.
*
* The field is created manually during layout setup.
*
* @see getDefaultFields()
*
* There is a separate endpoint to get the activity types.
* @see importPicklistValues()
*/
return;
}
if ($field->getCrmProviderId() === 'pipeline_stage_id') {
// Not a custom type
return;
}
$crmField = $this->copperClient->fields()->find($field->getCrmProviderId());
$field->label = $crmField['name'];
$field->type = $this->convertFieldType($crmField['data_type']);
$field->save();
}
/**
* @param string $fieldType How the data should be input
*/
private function convertFieldType(string $fieldType): string
{
$fieldType = strtolower($fieldType);
switch ($fieldType) {
case 'dropdown':
$convertedType = Field::TYPE_PICKLIST;
break;
case 'string':
$convertedType = Field::TYPE_TEXT;
break;
case 'float':
case 'percentage':
$convertedType = Field::TYPE_NUMBER;
break;
case 'text':
$convertedType = Field::TYPE_TEXTAREA;
break;
case 'checkbox':
$convertedType = Field::TYPE_BOOLEAN;
break;
case Field::TYPE_DATE:
case Field::TYPE_CURRENCY:
case Field::TYPE_URL:
$convertedType = $fieldType;
break;
default:
$convertedType = Field::TYPE_UNSUPPORTED;
break;
}
return $convertedType;
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$fieldValues = [];
if ($field->object_type === 'opportunity' && $field->crm_provider_id === 'pipeline_stage_id') {
return $this->importFieldValuesForDealInsights($field);
}
$values = [];
if ($field->object_type === Field::OBJECT_TASK && $field->crm_provider_id === 'type') {
$activityTypes = $this->copperClient->activityTypes()->all();
/**
* We ignore "system" activity types, disabled activity types and the "Note" activity type.
*/
$activityTypes = array_filter(
$activityTypes['user'],
fn (array $activityType) => ! $activityType['is_disabled'] && $activityType['id'] !== 0
);
// Import all activity values.
$i = 0;
foreach ($activityTypes as $activityType) {
$values[] = [
'value' => $activityType['id'],
'label' => mb_strimwidth($activityType['name'], 0, Field::LABEL_MAX_LENGTH),
'sequence' => $i++,
];
}
} else {
// We just check for the field in the custom definitions.
$crmField = $this->copperClient->fields()->find($field->crm_provider_id);
// Import all values.
foreach ($crmField['options'] as $option) {
$values[] = [
'value' => $option['id'],
'label' => mb_strimwidth($option['name'], 0, 191),
'sequence' => $option['rank'],
];
}
}
// Take the existing set of field values.
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
// For all current values, upsert the field.
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
$key = array_search($value['value'], $fieldsToPurge, false);
if ($key !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
return $fieldValues;
}
/**
*
* @return FieldValue[]
*/
private function importFieldValuesForDealInsights(Field $field): array
{
$fieldValues = [];
$pipelines = $this->copperClient->pipelines()->all();
foreach ($pipelines as $pipeline) {
foreach ($pipeline['stages'] as $i => $dealStage) {
$fieldValues[] = $field->values()->updateOrCreate(
['value' => $dealStage['id']],
[
'label' => $dealStage['name'],
'sequence' => $i,
]
);
}
}
return $fieldValues;
}
/**
* @inheritdoc
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
$missingStage = null;
foreach ($types as $type) {
if ($type === Stage::TYPE_LEAD) {
$statuses = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leadStatuses()->all()
);
if (count($statuses) > 0) {
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => BusinessProcess::TYPE_LEAD,
], [
'team_id' => $this->team->id,
'name' => BusinessProcess::TYPE_LEAD,
'type' => BusinessProcess::TYPE_LEAD,
'is_selectable' => true,
]);
// A record type is really a clone of the business process, used to store which record uses which pipeline.
$this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => BusinessProcess::TYPE_LEAD,
], [
'team_id' => $this->team->id,
'name' => BusinessProcess::TYPE_LEAD,
'is_selectable' => true,
'business_process_id' => $businessProcess->id ?? null,
]);
$leadStatuses = [];
foreach ($statuses as $status) {
// Upsert all statuses for the team.
$status = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $status['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($status['name'], 0, 50),
'label' => mb_strimwidth($status['name'], 0, 191),
'type' => Stage::TYPE_LEAD,
'sequence' => $status['order'],
'is_selectable' => true,
]);
if ($missingStageName && $missingStageName === $status['id']) {
$missingStage = $status;
}
$leadStatuses[] = $status['id'];
}
$businessProcess->stages()->sync($leadStatuses);
}
} else {
// We create a business process to contain the pipeline, and later store all stages against it.
foreach ($this->copperClient->pipelines()->all() as $pipeline) {
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => $pipeline['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($pipeline['name'], 0, 150),
'type' => BusinessProcess::TYPE_OPPORTUNITY,
'is_selectable' => true,
]);
// A record type is really a clone of the business process, used to store which record uses which pipeline.
$this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => $pipeline['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($pipeline['name'], 0, 150),
'is_selectable' => true,
'business_process_id' => $businessProcess->id ?? null,
]);
$stages = [];
foreach ($pipeline['stages'] as $i => $dealStage) {
// Upsert all stages for the team.
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $dealStage['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($dealStage['name'], 0, 50),
'label' => mb_strimwidth($dealStage['name'], 0, 191),
'type' => Stage::TYPE_OPPORTUNITY,
'sequence' => $i,
'is_selectable' => true,
'probability' => $dealStage['win_probability'],
]);
if ($missingStageName && $missingStageName === $dealStage['id']) {
$missingStage = $stage;
}
$stages[] = $stage['id'];
}
$businessProcess->stages()->sync($stages);
}
}
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$cpLeads = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->paginate([
'minimum_modified_date' => $since->timestamp,
'sort_by' => 'date_modified',
])
);
foreach ($cpLeads as $cpLead) {
// Only sync if previously imported.
if ($this->hasLead($cpLead['id']) === false) {
$this->importLead($cpLead);
$syncCount++;
}
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
$cpLead = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->find($crmId)
);
if (\count($cpLead) === 0) {
return null;
}
return $this->importLead($cpLead);
}
/**
* @inheritdoc
*/
private function importLead($crmData): ?Lead
{
$countryCode = null;
if (! empty($crmData['address']) && isset($crmData['address']['country'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$mobilePhone = $parsedNumber = null;
if (! empty($crmData['phone_numbers'])) {
foreach ($crmData['phone_numbers'] as $phoneNumber) {
if ($phoneNumber['category'] === 'mobile') {
$mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);
} else {
$parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);
}
}
}
$name = $crmData['name'];
if (empty($crmData['company_name'])) {
$company = 'Unknown';
} else {
$company = mb_strimwidth($crmData['company_name'], 0, 191);
}
$domain = null;
if (empty($crmData['websites']) === false) {
$domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$email = null;
if (empty($crmData['email']) === false) {
$email = mb_strimwidth($crmData['email']['email'], 0, 80);
}
$stage = $this->config
->stages()
->where('crm_provider_id', (string) $crmData['status_id'])
->where('type', Stage::TYPE_LEAD)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status_id']);
}
if (! $stage instanceof Stage) {
return null;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($name, 0, 191),
'company' => $company,
'domain' => $domain,
'title' => $crmData['title'] ? mb_strimwidth($crmData['title'], 0, 128) : null,
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'mobile_phone' => $mobilePhone,
'stage_id' => $stage->id,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Lead::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'country_code' => $countryCode,
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$cpAccounts = $this->copperClient->accounts()->paginate([
'minimum_modified_date' => $since->timestamp,
'sort_by' => 'date_modified',
]);
foreach ($cpAccounts as $cpAccount) {
// Only sync if previously imported.
if ($this->hasAccount($cpAccount['id'])) {
$this->importAccount($cpAccount);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
$cpAccount = $this->copperClient->accounts()->find($crmId);
if (empty($cpAccount)) {
return null;
}
return $this->importAccount($cpAccount);
}
/**
* @inheritdoc
*/
private function importAccount($crmData): Account
{
$countryCode = null;
if (empty($crmData['address']) === false && $crmData['address']['country']) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$name = $crmData['name'];
$parsedNumber = null;
foreach ($crmData['phone_numbers'] as $phoneNumber) {
$parsedNumber = parsePhoneNumber($countryCode, $phoneNumber['number']);
}
$domain = null;
if (empty($crmData['websites']) === false) {
$domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Account::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'country_code' => $countryCode,
'domain' => $domain,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->copperClient,
]);
$strategies = $strategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
try {
foreach ($strategies as $syncStrategy) {
foreach ($syncStrategy->fetchOpportunities($parameters) as $opportunityData) {
$this->importOpportunity($opportunityData);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
$this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => $exception->getMessage(),
]);
}
return $syncCount;
}
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->copperClient,
]);
$strategy = $strategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
$parameters['crm_id'] = $crmId;
$cpOpportunity = $strategy->fetchOpportunities($parameters);
return $this->importOpportunity($cpOpportunity);
}
private function importOpportunity($crmData): ?Opportunity
{
$companyId = (string) $crmData['company_id'];
if (empty($companyId)) {
$this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => 'No company id',
]);
return null;
}
$account = $this->config->accounts()->where('crm_provider_id', $companyId)->first();
if ($account === null) {
$account = $this->syncAccount($companyId);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', (string) $crmData['pipeline_id'])
->first();
if ($businessProcess === null) {
// It is possible for some deals to not be in a pipeline.
$this->logger->warning(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => 'Missing pipeline',
]);
return null;
}
$stage = $businessProcess
->stages()
->where('crm_provider_id', (string) $crmData['pipeline_stage_id'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
$this->logger->info('Stage not found, importing', [
'pipeline_id' => $crmData['pipeline_id'],
'stage_id' => $crmData['pipeline_stage_id'],
]);
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['pipeline_stage_id']);
}
$recordType = $businessProcess->recordTypes()->first();
$closeDate = null;
$isClosed = $crmData['status'] !== self::OPPORTUNITY_STATUS_OPEN;
if ($crmData['close_date']) {
$closeDate = Carbon::parse($crmData['close_date'])->format('Y-m-d');
}
$data = [
'team_id' => $this->team->getId(),
'account_id' => $account->id,
'user_id' => $profile->user_id ?? null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($crmData['name'], 0, 128),
'value' => $crmData['monetary_value'],
'currency_code' => CurrencyFormatter::formatCode($crmData['monetary_unit']),
'close_date' => $closeDate,
'is_closed' => $isClosed,
'is_won' => $crmData['status'] === 'Won',
'stage_id' => $stage->id,
'record_type_id' => $recordType->id ?? null,
'remotely_created_at' => $crmData['date_created'],
];
/** @var Opportunity $opportunity */
$opportunity = $this->config
->opportunities()
->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data)
;
// import external fields into crm_field_data if present
$dealInsightsFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData($crmData, $dealInsightsFields, $opportunity->id);
return $opportunity;
}
/**
* @param array<string, mixed> $opportunityData
* @param string[] $dealInsightsFields
*/
public function importOpportunityCrmFieldData(
array $opportunityData,
array $dealInsightsFields,
int $opportunityId
): void {
foreach ($dealInsightsFields as $fieldName) {
$field = $this->config->fields()->with('entities')
->where('crm_provider_id', $fieldName)
->where('object_type', Field::OBJECT_OPPORTUNITY)
->first();
if (! $field instanceof Field) {
$this->logger->warning('Field not found', [
'field' => $fieldName,
'opportunity_id' => $opportunityId,
]);
continue;
}
$entity = $field->getEntities()->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$fieldValue = $this->extractFieldValue($opportunityData, $fieldName);
$normalizedValue = $this->normalizeValue($field->getType(), (string) $fieldValue, true);
$field->data()
->updateOrCreate([
'crm_layout_entity_id' => $entity->id,
'crm_field_id' => $field->id,
'object_type' => 'opportunity',
'object_id' => $opportunityId,
], ['value' => $normalizedValue])
;
}
}
/**
* @inheritdoc
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$cpContacts = $this->copperClient->contacts()->paginate([
'minimum_interaction_date' => $since->timestamp,
'sort_by' => 'date_modified',
]);
foreach ($cpContacts as $cpContact) {
// Only sync if previously imported.
if ($this->hasContact($cpContact['id'])) {
$this->importContact($cpContact);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
throw $exception;
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncContact(string $crmId): ?Contact
{
$cpContact = $this->copperClient->contacts()->find($crmId);
if (empty($cpContact)) {
return null;
}
return $this->importContact($cpContact);
}
/**
* @inheritdoc
*/
private function importContact($crmData): Contact
{
$account = null;
if ($crmData['company_id']) {
$account = $this->team
->crm
->accounts()
->where('crm_provider_id', (string) $crmData['company_id'])
->first();
if ($account === null) {
$account = $this->syncAccount($crmData['company_id']);
}
}
$countryCode = null;
if (empty($crmData['address']) === false && $crmData['address']['country']) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$mobilePhone = $parsedNumber = null;
foreach ($crmData['phone_numbers'] as $phoneNumber) {
if ($phoneNumber['category'] === 'mobile') {
$mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);
} else {
$parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);
}
}
$email = null;
if (empty($crmData['emails']) === false) {
$email = mb_strimwidth($crmData['emails'][0]['email'], 0, 80);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => $crmData['name'],
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'mobile_phone' => $mobilePhone ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'title' => $crmData['title'],
'country_code' => $countryCode,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Contact::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function buildContactPhone(?string $countryCode, ?string $number): ?array
{
if ($number) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($number, 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
return $parsedNumber;
}
private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string
{
return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;
}
/**
* @inheritdoc
*/
public function syncOrganization(): void
{
$organization = $this->copperClient->organisation()->all();
if ($this->config->crm_provider_id !== $organization['id']) {
$this->config->update(['crm_provider_id' => $organization['id']]);
}
}
private function syncCustomFields(): void
{
foreach ($this->getFieldTypes() as $fieldType) {
$currentFields = $this->getFields($fieldType);
foreach ($currentFields as $field) {
/** @var Field $field */
$field = $this->config->fields()->updateOrCreate([
'crm_provider_id' => $field['name'],
'object_type' => $fieldType,
], [
'label' => mb_strimwidth($field['label'], 0, Field::LABEL_MAX_LENGTH),
'type' => $field['type'],
]);
if ($field->getType() === Field::TYPE_PICKLIST) {
$this->importPicklistValues($field);
}
}
}
$this->config->save();
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
parent::OBJECT_LEAD,
parent::OBJECT_ACCOUNT,
parent::OBJECT_CONTACT,
parent::OBJECT_OPPORTUNITY,
];
}
/**
* @inheritdoc
*/
public function syncProfiles(?User $userToSearch = null): ?Profile
{
$profiles = $this->copperClient->users()->all();
foreach ($profiles as $profile) {
$user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);
// Only import profiles for users we have locally.
if ($user) {
$profile = $user->crmProfile()->updateOrCreate([
'crm_configuration_id' => $this->config->id,
'crm_provider_id' => $profile['id'],
]);
if ($userToSearch && $userToSearch->id === $user->id) {
return $profile;
}
}
}
return null;
}
/**
* @inheritdoc
*/
public function syncProfileFields(): void
{
$fieldTypes = [
'task',
'lead',
'account',
'contact',
'opportunity',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields(ucfirst($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))
);
if (\count($changedFields) > 0) {
$fields = implode(',', $newFields);
$this->logger->debug(
ucfirst($fieldType)
. ' fields changed from '
. $this->profile->{$fieldType . '_fields'}
. ' to: '
. $fields
);
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (\Exception $exception) {
$this->logger->error('No access to ' . $fieldType . ' object, skipping...');
continue;
}
}
$this->profile->save();
}
/**
* @inheritdoc
*/
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$scopeValues = array_map(fn ($scope) => is_string($scope) ? $scope : $scope->value, $scopes);
$cacheKey = sprintf('copper-search-%d-%s-%s-%d-%d', $this->team->id, $name, implode('-', $scopeValues), $count, $offset);
return Cache::remember($cacheKey, 300, function () use ($name, $scopes, $count, $offset) {
// Try local search first
$localResults = $this->searchLocally($name, $scopes, $count, $offset);
// If no local results, fall back to remote API search
if (empty($localResults)) {
return $this->searchRemotely($name, $scopes, $count, $offset);
}
return $localResults;
});
}
/**
* @inheritdoc
*/
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$params = [
'company_ids' => [$account->crm_provider_id],
'status_ids' => [0], // The integer values are 0, 1, 2, 3, for "Open", "Won", "Lost", and "Abandoned".
'sort_by' => 'date_modified',
'sort_direction' => 'desc',
];
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort_by'] = 'date_modified';
$params['sort_direction'] = 'desc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort_by'] = 'date_created';
$params['sort_direction'] = 'desc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort_by'] = 'date_created';
$params['sort_direction'] = 'asc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort_by'] = 'date_modified';
$params['sort_direction'] = 'desc';
$params['status_ids'] = [0, 1, 2, 3];
}
$cpOpportunities = $this->copperClient->opportunities()->search($params);
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
foreach ($cpOpportunities as $cpOpportunity) {
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', (string) $cpOpportunity['pipeline_id'])
->first();
if ($businessProcess === null) {
// Import it.
$businessProcess = $this->importStages(
[Stage::TYPE_OPPORTUNITY],
$cpOpportunity['pipeline_stage_id']
);
}
$stage = $businessProcess
->stages()
->where('crm_provider_id', (string) $cpOpportunity['pipeline_stage_id'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $cpOpportunity['pipeline_stage_id']);
}
$recordType = $businessProcess->recordTypes()->first();
$record = [
'crmId' => $cpOpportunity['id'],
'name' => $cpOpportunity['name'],
'value' => currency_format($cpOpportunity['monetary_value'], $cpOpportunity['monetary_unit']),
'won' => $cpOpportunity['status'] === 'Won',
'stage' => [
'id' => $stage->id_string,
'name' => $stage->name,
],
'recordType' => [
'id' => $recordType->id_string,
'name' => $recordType->name,
],
];
if ($ownerId && isset($cpOpportunity['assignee_id']) && $cpOpportunity['assignee_id'] === $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
/**
* @inheritdoc
*/
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = $cpTasks = [];
switch ($objectType) {
case 'lead':
$cpTasks = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->relatedTasks($objectId)
);
break;
case 'account':
$cpTasks = $this->copperClient->accounts()->relatedTasks($objectId);
break;
case 'contact':
if ($opportunityId) {
$cpTasks = $this->copperClient->opportunities()->relatedTasks($opportunityId);
} elseif ($objectType === 'contact') {
$cpTasks = $this->copperClient->contacts()->relatedTasks($objectId);
}
break;
}
foreach ($cpTasks as $cpTask) {
// We only get the ID itself returned, so pull out the full object.
try {
$cpTask = $this->copperClient->tasks()->find($cpTask['id']);
} catch (Exception $exception) {
$this->logger->error('[Copper] Error fetching task', [
'resource_id' => $cpTask['id'],
'error' => $exception->getMessage(),
]);
continue;
}
// Only allow open tasks.
if ($cpTask['status'] === 'Open') {
$data[] = [
'crmId' => $cpTask['id'],
'subject' => $cpTask['name'],
'due' => $cpTask['due_date']
? Carbon::createFromTimestamp($cpTask['due_date'])->format('Y-m-d\TH:i:sO')
: null,
'type' => null,
];
}
}
return $data;
}
/**
* Try to find email address in CRM service
*
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchExactlyByEmail(string $email, ?int $userId = null): ?array
{
$cpObjectType = 'contact';
$cpObjects = $this->copperClient->contacts()->search([
'emails' => $email,
'sort_by' => 'date_modified',
'sort_direction' => 'desc',
]);
if (empty($cpObjects)) {
$cpObjectType = 'lead';
$cpObjects = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->search([
'emails' => ...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.66456115,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.67586434,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.6871675,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.7150931,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.72639626,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.73769945,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"11","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"72","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Copper;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse GuzzleHttp\\Exception\\ClientException;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\CopperInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\FieldValue;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\PlaybookCategory;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\UserRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\Copper\\Api\\Client;\nuse Jiminny\\Services\\Crm\\Copper\\Api\\ClientFactory;\nuse Jiminny\\Services\\Crm\\Copper\\Exception\\RequestFailedException;\nuse Jiminny\\Services\\Crm\\Helpers\\FilterJoinedParticipants;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Services\\Crm\\Copper\\Traits\\SearchesCrmEntities;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\n\nclass Service extends BaseService implements\n CopperInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n use SearchesCrmEntities;\n private const int NOTE_BODY_MAX_LENGTH = 3000000;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const array STANDARD_OPPORTUNITY_FIELDS = [\n 'monetary_value' => [\n 'label' => 'Value',\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n 'type' => Field::TYPE_CURRENCY,\n ],\n 'pipeline_stage_id' => [\n 'label' => 'Stage',\n 'type' => Field::TYPE_PICKLIST,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n 'close_date' => [\n 'label' => 'Close date',\n 'type' => Field::TYPE_DATE,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n 'win_probability' => [\n 'label' => 'Win probability',\n 'type' => Field::TYPE_NUMBER,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n ];\n private const string UNSUPPORTED_OBJECT_TYPE = 'unsupported';\n private const string OPPORTUNITY_STATUS_OPEN = 'Open';\n private const string OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE = 'Opportunity import failed';\n private const string RESOURCE_UPDATE_FAILED_ERROR_MESSAGE = 'Failed to update resource';\n\n private FieldValueConverter $fieldValueConverter;\n private ClientFactory $clientFactory;\n private ?Client $copperClient = null;\n\n public function __construct(\n ClientFactory $clientFactory,\n FieldValueConverter $fieldValueConverter,\n private readonly UserRepository $userRepository,\n private readonly ProspectPhotoPathService $prospectPhotoPathService,\n private readonly CrmEntityRepository $crmEntityRepository\n ) {\n parent::__construct();\n\n $this->clientFactory = $clientFactory;\n $this->fieldValueConverter = $fieldValueConverter;\n }\n\n public function getDisplayName(): string\n {\n return 'Copper';\n }\n\n /**\n * Get the CRM entity repository (used by SearchesCrmEntities trait)\n */\n protected function getCrmEntityRepository(): CrmEntityRepository\n {\n return $this->crmEntityRepository;\n }\n\n public function getMinimumApiVersion(): string\n {\n return Client::MIN_API_VERSION;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_COPPER);\n }\n\n public function setUser(User $user): void\n {\n $this->configureSentryScope($user);\n\n $this->team = $user->getTeam();\n $this->teamService->setTeam($user->getTeam());\n $this->setConfiguration($user->getTeam()->getCrmConfiguration());\n\n // Reset state.\n $this->profile = $user->getProfile();\n\n if (! $this->profile instanceof Profile) {\n // Try to fetch their profile, maybe it was not yet imported?\n $this->profile = $this->getProfile($user);\n }\n }\n\n public function setConfiguration(Configuration $configuration): void\n {\n $this->config = $configuration;\n $this->copperClient = $this->clientFactory->create($configuration);\n\n if ($this->team === null) {\n $this->team = $configuration->getTeam();\n }\n }\n\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return $this->fieldValueConverter->convertFromCrm($fieldType, $fieldValue);\n }\n\n private function mapObjectType(string $objectType): string\n {\n $objectType = strtolower($objectType);\n\n switch ($objectType) {\n case Field::OBJECT_TASK:\n case Field::OBJECT_OPPORTUNITY:\n case Field::OBJECT_LEAD:\n $mappedType = $objectType;\n\n break;\n case Field::OBJECT_ACCOUNT:\n $mappedType = 'company';\n\n break;\n case Field::OBJECT_CONTACT:\n $mappedType = 'person';\n\n break;\n default:\n $mappedType = self::UNSUPPORTED_OBJECT_TYPE;\n\n break;\n }\n\n return $mappedType;\n }\n\n /**\n * @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact\n */\n protected function getFields(string $crmObject): array\n {\n $mappedObjectType = $this->mapObjectType($crmObject);\n\n if (! $this->isSupportedObjectType($mappedObjectType)) {\n return [];\n }\n\n $customFields = $this->copperClient->fields()->all();\n\n $filteredFields = array_filter(\n $customFields,\n static fn ($field) => in_array($mappedObjectType, $field['available_on'], true)\n );\n\n return array_map(\n fn (array $property) => [\n 'name' => $property['id'],\n 'label' => $property['name'],\n 'type' => $this->convertFieldType($property['data_type']),\n ],\n $filteredFields\n );\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {\n $defaultFields = FieldDefinitions::defaultTaskFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n $fieldFilters = FieldDefinitions::taskFollowupFieldsFilter();\n\n foreach ($fieldFilters as $data) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n public function syncFields(): void\n {\n $this->syncStandardFields();\n $this->syncCustomFields();\n }\n\n public function syncField(Field $field): void\n {\n if ($field->getCrmProviderId() === 'type') {\n /**\n * This field is a special case, it is not a custom field and is not returned by the Copper API.\n *\n * The field is created manually during layout setup.\n *\n * @see getDefaultFields()\n *\n * There is a separate endpoint to get the activity types.\n * @see importPicklistValues()\n */\n return;\n }\n\n if ($field->getCrmProviderId() === 'pipeline_stage_id') {\n // Not a custom type\n return;\n }\n\n $crmField = $this->copperClient->fields()->find($field->getCrmProviderId());\n $field->label = $crmField['name'];\n $field->type = $this->convertFieldType($crmField['data_type']);\n\n $field->save();\n }\n\n /**\n * @param string $fieldType How the data should be input\n */\n private function convertFieldType(string $fieldType): string\n {\n $fieldType = strtolower($fieldType);\n\n switch ($fieldType) {\n case 'dropdown':\n $convertedType = Field::TYPE_PICKLIST;\n\n break;\n case 'string':\n $convertedType = Field::TYPE_TEXT;\n\n break;\n case 'float':\n case 'percentage':\n $convertedType = Field::TYPE_NUMBER;\n\n break;\n case 'text':\n $convertedType = Field::TYPE_TEXTAREA;\n\n break;\n case 'checkbox':\n $convertedType = Field::TYPE_BOOLEAN;\n\n break;\n case Field::TYPE_DATE:\n case Field::TYPE_CURRENCY:\n case Field::TYPE_URL:\n $convertedType = $fieldType;\n\n break;\n default:\n $convertedType = Field::TYPE_UNSUPPORTED;\n\n break;\n }\n\n return $convertedType;\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $fieldValues = [];\n\n if ($field->object_type === 'opportunity' && $field->crm_provider_id === 'pipeline_stage_id') {\n return $this->importFieldValuesForDealInsights($field);\n }\n\n $values = [];\n\n if ($field->object_type === Field::OBJECT_TASK && $field->crm_provider_id === 'type') {\n $activityTypes = $this->copperClient->activityTypes()->all();\n\n /**\n * We ignore \"system\" activity types, disabled activity types and the \"Note\" activity type.\n */\n $activityTypes = array_filter(\n $activityTypes['user'],\n fn (array $activityType) => ! $activityType['is_disabled'] && $activityType['id'] !== 0\n );\n\n // Import all activity values.\n $i = 0;\n foreach ($activityTypes as $activityType) {\n $values[] = [\n 'value' => $activityType['id'],\n 'label' => mb_strimwidth($activityType['name'], 0, Field::LABEL_MAX_LENGTH),\n 'sequence' => $i++,\n ];\n }\n } else {\n // We just check for the field in the custom definitions.\n $crmField = $this->copperClient->fields()->find($field->crm_provider_id);\n\n // Import all values.\n foreach ($crmField['options'] as $option) {\n $values[] = [\n 'value' => $option['id'],\n 'label' => mb_strimwidth($option['name'], 0, 191),\n 'sequence' => $option['rank'],\n ];\n }\n }\n\n // Take the existing set of field values.\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n // For all current values, upsert the field.\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n $key = array_search($value['value'], $fieldsToPurge, false);\n if ($key !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n\n return $fieldValues;\n }\n\n /**\n *\n * @return FieldValue[]\n */\n private function importFieldValuesForDealInsights(Field $field): array\n {\n $fieldValues = [];\n $pipelines = $this->copperClient->pipelines()->all();\n\n foreach ($pipelines as $pipeline) {\n foreach ($pipeline['stages'] as $i => $dealStage) {\n $fieldValues[] = $field->values()->updateOrCreate(\n ['value' => $dealStage['id']],\n [\n 'label' => $dealStage['name'],\n 'sequence' => $i,\n ]\n );\n }\n }\n\n return $fieldValues;\n }\n\n /**\n * @inheritdoc\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n $missingStage = null;\n\n foreach ($types as $type) {\n if ($type === Stage::TYPE_LEAD) {\n $statuses = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leadStatuses()->all()\n );\n\n if (count($statuses) > 0) {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => BusinessProcess::TYPE_LEAD,\n ], [\n 'team_id' => $this->team->id,\n 'name' => BusinessProcess::TYPE_LEAD,\n 'type' => BusinessProcess::TYPE_LEAD,\n 'is_selectable' => true,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => BusinessProcess::TYPE_LEAD,\n ], [\n 'team_id' => $this->team->id,\n 'name' => BusinessProcess::TYPE_LEAD,\n 'is_selectable' => true,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $leadStatuses = [];\n foreach ($statuses as $status) {\n // Upsert all statuses for the team.\n $status = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $status['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($status['name'], 0, 50),\n 'label' => mb_strimwidth($status['name'], 0, 191),\n 'type' => Stage::TYPE_LEAD,\n 'sequence' => $status['order'],\n 'is_selectable' => true,\n ]);\n\n if ($missingStageName && $missingStageName === $status['id']) {\n $missingStage = $status;\n }\n\n $leadStatuses[] = $status['id'];\n }\n\n $businessProcess->stages()->sync($leadStatuses);\n }\n } else {\n // We create a business process to contain the pipeline, and later store all stages against it.\n foreach ($this->copperClient->pipelines()->all() as $pipeline) {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $pipeline['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline['name'], 0, 150),\n 'type' => BusinessProcess::TYPE_OPPORTUNITY,\n 'is_selectable' => true,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $pipeline['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline['name'], 0, 150),\n 'is_selectable' => true,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $stages = [];\n\n foreach ($pipeline['stages'] as $i => $dealStage) {\n // Upsert all stages for the team.\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $dealStage['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($dealStage['name'], 0, 50),\n 'label' => mb_strimwidth($dealStage['name'], 0, 191),\n 'type' => Stage::TYPE_OPPORTUNITY,\n 'sequence' => $i,\n 'is_selectable' => true,\n 'probability' => $dealStage['win_probability'],\n ]);\n\n if ($missingStageName && $missingStageName === $dealStage['id']) {\n $missingStage = $stage;\n }\n\n $stages[] = $stage['id'];\n }\n\n $businessProcess->stages()->sync($stages);\n }\n }\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n\n $cpLeads = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->paginate([\n 'minimum_modified_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ])\n );\n\n foreach ($cpLeads as $cpLead) {\n // Only sync if previously imported.\n if ($this->hasLead($cpLead['id']) === false) {\n $this->importLead($cpLead);\n $syncCount++;\n }\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n $cpLead = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->find($crmId)\n );\n\n if (\\count($cpLead) === 0) {\n return null;\n }\n\n return $this->importLead($cpLead);\n }\n\n /**\n * @inheritdoc\n */\n private function importLead($crmData): ?Lead\n {\n $countryCode = null;\n if (! empty($crmData['address']) && isset($crmData['address']['country'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $mobilePhone = $parsedNumber = null;\n if (! empty($crmData['phone_numbers'])) {\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n if ($phoneNumber['category'] === 'mobile') {\n $mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);\n } else {\n $parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);\n }\n }\n }\n\n $name = $crmData['name'];\n\n if (empty($crmData['company_name'])) {\n $company = 'Unknown';\n } else {\n $company = mb_strimwidth($crmData['company_name'], 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['websites']) === false) {\n $domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $email = null;\n if (empty($crmData['email']) === false) {\n $email = mb_strimwidth($crmData['email']['email'], 0, 80);\n }\n\n $stage = $this->config\n ->stages()\n ->where('crm_provider_id', (string) $crmData['status_id'])\n ->where('type', Stage::TYPE_LEAD)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status_id']);\n }\n\n if (! $stage instanceof Stage) {\n return null;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($name, 0, 191),\n 'company' => $company,\n 'domain' => $domain,\n 'title' => $crmData['title'] ? mb_strimwidth($crmData['title'], 0, 128) : null,\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'mobile_phone' => $mobilePhone,\n 'stage_id' => $stage->id,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Lead::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'country_code' => $countryCode,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $cpAccounts = $this->copperClient->accounts()->paginate([\n 'minimum_modified_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ]);\n\n foreach ($cpAccounts as $cpAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($cpAccount['id'])) {\n $this->importAccount($cpAccount);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n $cpAccount = $this->copperClient->accounts()->find($crmId);\n\n if (empty($cpAccount)) {\n return null;\n }\n\n return $this->importAccount($cpAccount);\n }\n\n /**\n * @inheritdoc\n */\n private function importAccount($crmData): Account\n {\n $countryCode = null;\n if (empty($crmData['address']) === false && $crmData['address']['country']) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $name = $crmData['name'];\n\n $parsedNumber = null;\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n $parsedNumber = parsePhoneNumber($countryCode, $phoneNumber['number']);\n }\n\n $domain = null;\n if (empty($crmData['websites']) === false) {\n $domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Account::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'country_code' => $countryCode,\n 'domain' => $domain,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->copperClient,\n ]);\n $strategies = $strategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n\n try {\n foreach ($strategies as $syncStrategy) {\n foreach ($syncStrategy->fetchOpportunities($parameters) as $opportunityData) {\n $this->importOpportunity($opportunityData);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n $this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => $exception->getMessage(),\n ]);\n }\n\n return $syncCount;\n }\n\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->copperClient,\n ]);\n $strategy = $strategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n $parameters['crm_id'] = $crmId;\n\n $cpOpportunity = $strategy->fetchOpportunities($parameters);\n\n return $this->importOpportunity($cpOpportunity);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n $companyId = (string) $crmData['company_id'];\n\n if (empty($companyId)) {\n $this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => 'No company id',\n ]);\n\n return null;\n }\n\n $account = $this->config->accounts()->where('crm_provider_id', $companyId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($companyId);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', (string) $crmData['pipeline_id'])\n ->first();\n\n if ($businessProcess === null) {\n // It is possible for some deals to not be in a pipeline.\n $this->logger->warning(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => 'Missing pipeline',\n ]);\n\n return null;\n }\n\n $stage = $businessProcess\n ->stages()\n ->where('crm_provider_id', (string) $crmData['pipeline_stage_id'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n $this->logger->info('Stage not found, importing', [\n 'pipeline_id' => $crmData['pipeline_id'],\n 'stage_id' => $crmData['pipeline_stage_id'],\n ]);\n\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['pipeline_stage_id']);\n }\n\n $recordType = $businessProcess->recordTypes()->first();\n $closeDate = null;\n $isClosed = $crmData['status'] !== self::OPPORTUNITY_STATUS_OPEN;\n\n if ($crmData['close_date']) {\n $closeDate = Carbon::parse($crmData['close_date'])->format('Y-m-d');\n }\n\n $data = [\n 'team_id' => $this->team->getId(),\n 'account_id' => $account->id,\n 'user_id' => $profile->user_id ?? null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($crmData['name'], 0, 128),\n 'value' => $crmData['monetary_value'],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['monetary_unit']),\n 'close_date' => $closeDate,\n 'is_closed' => $isClosed,\n 'is_won' => $crmData['status'] === 'Won',\n 'stage_id' => $stage->id,\n 'record_type_id' => $recordType->id ?? null,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n /** @var Opportunity $opportunity */\n $opportunity = $this->config\n ->opportunities()\n ->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data)\n ;\n\n // import external fields into crm_field_data if present\n $dealInsightsFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData($crmData, $dealInsightsFields, $opportunity->id);\n\n return $opportunity;\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n * @param string[] $dealInsightsFields\n */\n public function importOpportunityCrmFieldData(\n array $opportunityData,\n array $dealInsightsFields,\n int $opportunityId\n ): void {\n foreach ($dealInsightsFields as $fieldName) {\n $field = $this->config->fields()->with('entities')\n ->where('crm_provider_id', $fieldName)\n ->where('object_type', Field::OBJECT_OPPORTUNITY)\n ->first();\n\n if (! $field instanceof Field) {\n $this->logger->warning('Field not found', [\n 'field' => $fieldName,\n 'opportunity_id' => $opportunityId,\n ]);\n\n continue;\n }\n\n $entity = $field->getEntities()->first();\n\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $fieldValue = $this->extractFieldValue($opportunityData, $fieldName);\n $normalizedValue = $this->normalizeValue($field->getType(), (string) $fieldValue, true);\n\n $field->data()\n ->updateOrCreate([\n 'crm_layout_entity_id' => $entity->id,\n 'crm_field_id' => $field->id,\n 'object_type' => 'opportunity',\n 'object_id' => $opportunityId,\n ], ['value' => $normalizedValue])\n ;\n }\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $cpContacts = $this->copperClient->contacts()->paginate([\n 'minimum_interaction_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ]);\n\n foreach ($cpContacts as $cpContact) {\n // Only sync if previously imported.\n if ($this->hasContact($cpContact['id'])) {\n $this->importContact($cpContact);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n throw $exception;\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n $cpContact = $this->copperClient->contacts()->find($crmId);\n\n if (empty($cpContact)) {\n return null;\n }\n\n return $this->importContact($cpContact);\n }\n\n /**\n * @inheritdoc\n */\n private function importContact($crmData): Contact\n {\n $account = null;\n if ($crmData['company_id']) {\n $account = $this->team\n ->crm\n ->accounts()\n ->where('crm_provider_id', (string) $crmData['company_id'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['company_id']);\n }\n }\n\n $countryCode = null;\n if (empty($crmData['address']) === false && $crmData['address']['country']) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $mobilePhone = $parsedNumber = null;\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n if ($phoneNumber['category'] === 'mobile') {\n $mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);\n } else {\n $parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);\n }\n }\n\n $email = null;\n if (empty($crmData['emails']) === false) {\n $email = mb_strimwidth($crmData['emails'][0]['email'], 0, 80);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => $crmData['name'],\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'mobile_phone' => $mobilePhone ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'title' => $crmData['title'],\n 'country_code' => $countryCode,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Contact::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function buildContactPhone(?string $countryCode, ?string $number): ?array\n {\n if ($number) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($number, 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n return $parsedNumber;\n }\n\n private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string\n {\n return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n $organization = $this->copperClient->organisation()->all();\n\n if ($this->config->crm_provider_id !== $organization['id']) {\n $this->config->update(['crm_provider_id' => $organization['id']]);\n }\n }\n\n private function syncCustomFields(): void\n {\n foreach ($this->getFieldTypes() as $fieldType) {\n $currentFields = $this->getFields($fieldType);\n\n foreach ($currentFields as $field) {\n /** @var Field $field */\n $field = $this->config->fields()->updateOrCreate([\n 'crm_provider_id' => $field['name'],\n 'object_type' => $fieldType,\n ], [\n 'label' => mb_strimwidth($field['label'], 0, Field::LABEL_MAX_LENGTH),\n 'type' => $field['type'],\n ]);\n\n if ($field->getType() === Field::TYPE_PICKLIST) {\n $this->importPicklistValues($field);\n }\n }\n }\n\n $this->config->save();\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n parent::OBJECT_LEAD,\n parent::OBJECT_ACCOUNT,\n parent::OBJECT_CONTACT,\n parent::OBJECT_OPPORTUNITY,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $profiles = $this->copperClient->users()->all();\n\n foreach ($profiles as $profile) {\n $user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);\n\n // Only import profiles for users we have locally.\n if ($user) {\n $profile = $user->crmProfile()->updateOrCreate([\n 'crm_configuration_id' => $this->config->id,\n 'crm_provider_id' => $profile['id'],\n ]);\n\n if ($userToSearch && $userToSearch->id === $user->id) {\n return $profile;\n }\n }\n }\n\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'task',\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields(ucfirst($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))\n );\n\n if (\\count($changedFields) > 0) {\n $fields = implode(',', $newFields);\n $this->logger->debug(\n ucfirst($fieldType)\n . ' fields changed from '\n . $this->profile->{$fieldType . '_fields'}\n . ' to: '\n . $fields\n );\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (\\Exception $exception) {\n $this->logger->error('No access to ' . $fieldType . ' object, skipping...');\n\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $scopeValues = array_map(fn ($scope) => is_string($scope) ? $scope : $scope->value, $scopes);\n $cacheKey = sprintf('copper-search-%d-%s-%s-%d-%d', $this->team->id, $name, implode('-', $scopeValues), $count, $offset);\n\n return Cache::remember($cacheKey, 300, function () use ($name, $scopes, $count, $offset) {\n // Try local search first\n $localResults = $this->searchLocally($name, $scopes, $count, $offset);\n\n // If no local results, fall back to remote API search\n if (empty($localResults)) {\n return $this->searchRemotely($name, $scopes, $count, $offset);\n }\n\n return $localResults;\n });\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $params = [\n 'company_ids' => [$account->crm_provider_id],\n 'status_ids' => [0], // The integer values are 0, 1, 2, 3, for \"Open\", \"Won\", \"Lost\", and \"Abandoned\".\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ];\n\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort_by'] = 'date_modified';\n $params['sort_direction'] = 'desc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort_by'] = 'date_created';\n $params['sort_direction'] = 'desc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort_by'] = 'date_created';\n $params['sort_direction'] = 'asc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort_by'] = 'date_modified';\n $params['sort_direction'] = 'desc';\n $params['status_ids'] = [0, 1, 2, 3];\n }\n\n $cpOpportunities = $this->copperClient->opportunities()->search($params);\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n foreach ($cpOpportunities as $cpOpportunity) {\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', (string) $cpOpportunity['pipeline_id'])\n ->first();\n\n if ($businessProcess === null) {\n // Import it.\n $businessProcess = $this->importStages(\n [Stage::TYPE_OPPORTUNITY],\n $cpOpportunity['pipeline_stage_id']\n );\n }\n\n $stage = $businessProcess\n ->stages()\n ->where('crm_provider_id', (string) $cpOpportunity['pipeline_stage_id'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $cpOpportunity['pipeline_stage_id']);\n }\n\n $recordType = $businessProcess->recordTypes()->first();\n\n $record = [\n 'crmId' => $cpOpportunity['id'],\n 'name' => $cpOpportunity['name'],\n 'value' => currency_format($cpOpportunity['monetary_value'], $cpOpportunity['monetary_unit']),\n 'won' => $cpOpportunity['status'] === 'Won',\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n\n if ($ownerId && isset($cpOpportunity['assignee_id']) && $cpOpportunity['assignee_id'] === $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $cpTasks = [];\n\n switch ($objectType) {\n case 'lead':\n $cpTasks = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->relatedTasks($objectId)\n );\n\n break;\n\n case 'account':\n $cpTasks = $this->copperClient->accounts()->relatedTasks($objectId);\n\n break;\n case 'contact':\n if ($opportunityId) {\n $cpTasks = $this->copperClient->opportunities()->relatedTasks($opportunityId);\n } elseif ($objectType === 'contact') {\n $cpTasks = $this->copperClient->contacts()->relatedTasks($objectId);\n }\n\n break;\n }\n\n foreach ($cpTasks as $cpTask) {\n // We only get the ID itself returned, so pull out the full object.\n try {\n $cpTask = $this->copperClient->tasks()->find($cpTask['id']);\n } catch (Exception $exception) {\n $this->logger->error('[Copper] Error fetching task', [\n 'resource_id' => $cpTask['id'],\n 'error' => $exception->getMessage(),\n ]);\n\n continue;\n }\n\n // Only allow open tasks.\n if ($cpTask['status'] === 'Open') {\n $data[] = [\n 'crmId' => $cpTask['id'],\n 'subject' => $cpTask['name'],\n 'due' => $cpTask['due_date']\n ? Carbon::createFromTimestamp($cpTask['due_date'])->format('Y-m-d\\TH:i:sO')\n : null,\n 'type' => null,\n ];\n }\n }\n\n return $data;\n }\n\n /**\n * Try to find email address in CRM service\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $cpObjectType = 'contact';\n\n $cpObjects = $this->copperClient->contacts()->search([\n 'emails' => $email,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (empty($cpObjects)) {\n $cpObjectType = 'lead';\n $cpObjects = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'emails' => $email,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (empty($cpObjects)) {\n return null;\n }\n\n // Search returns an array of results, but we only want the first\n $cpObject = reset($cpObjects);\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember === false) {\n $cpObjectType = 'contact';\n $cpObject = $this->copperClient->contacts()->search([\n 'phone_number' => $phone,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (\\count($cpObject) === 0) {\n $cpObjectType = 'lead';\n $cpObject = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'phone_number' => $phone,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (empty($cpObject)) {\n return null;\n }\n\n $cpObject = reset($cpObject);\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n return null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n $result = \\Cache::remember($this->team->id . $name, 60, function () use ($name, $userId) {\n $cpObjectType = 'contact';\n $cpObject = $this->copperClient->contacts()->search([\n 'name' => $name,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (\\count($cpObject) === 0) {\n $cpObjectType = 'lead';\n $cpObject = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'name' => $name,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (! empty($cpObject)) {\n $cpObject = reset($cpObject);\n }\n\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n private function convertCrmData(array $object, string $objectType, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n if ($objectType === 'lead') {\n $lead = $this->importLead($object);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } else {\n $contact = $this->importContact($object);\n $account = $contact->account;\n\n if ($contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $cpOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact->crm_provider_id,\n $userId,\n );\n\n if (! empty($cpOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($cpOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n } catch (\\Exception $e) {\n // Nothing to see here.\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n public function saveActivity(Activity $activity): Activity\n {\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n $activity = $this->buildCallPayload($activity);\n\n break;\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildTextMessagePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n private function convertActivityAssociations(Activity $activity): array\n {\n if ($activity->lead) {\n $type = 'lead';\n $id = $activity->lead->crm_provider_id;\n } elseif ($activity->contact) {\n $type = 'person';\n $id = $activity->contact->crm_provider_id;\n } elseif ($activity->opportunity) {\n $type = 'opportunity';\n $id = $activity->opportunity->crm_provider_id;\n } else {\n $type = 'company';\n $id = $activity->account->crm_provider_id;\n }\n\n return [\n 'type' => $type,\n 'id' => $id,\n ];\n }\n\n private function convertActivityType(PlaybookCategory $activityType): array\n {\n return [\n 'category' => 'user',\n 'id' => $this->getCrmType($activityType)->value,\n ];\n }\n\n /**\n * @throws CrmException\n */\n private function buildCallPayload(Activity $activity): Activity\n {\n try {\n if ($activity->crm_provider_id) {\n // The activity should be logged under the existing Task (not Activity).\n $newActivityType = $this->getCrmType($activity->category);\n if ($newActivityType === null) {\n $message = sprintf('[Copper] invalid CRM Custom Activity Type: %s', $activity->category);\n\n throw new CrmException($message, 400);\n }\n $this->copperClient->tasks()->update($activity->crm_provider_id, [\n 'status' => 'Completed',\n 'custom_activity_type_id' => $newActivityType->value,\n 'details' => $this->generateActivityDescription($activity),\n ]);\n } else {\n if ($this->getCrmType($activity->category) === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n if ($this->getCrmType($activity->category)->value === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n // Just create an activity.\n $cpActivity = $this->copperClient->activities()->create([\n 'user_id' => $this->profile->crm_provider_id,\n 'activity_date' => $activity->scheduled_start_time->timestamp,\n 'parent' => $this->convertActivityAssociations($activity),\n 'type' => $this->convertActivityType($activity->category),\n 'details' => $this->generateActivityDescription($activity),\n ]);\n\n $activity->crm_provider_id = $cpActivity['id'];\n $activity->save();\n }\n } catch (ClientException $exception) {\n //Log all errors to Sentry\n \\Sentry::captureException($exception);\n\n $response = $exception->getResponse();\n\n $responseBody = $response->getBody();\n $message = $responseBody;\n $errorCode = $response->getStatusCode();\n\n $jsonResponse = json_decode($responseBody, true);\n if (isset($jsonResponse[0]['message'])) {\n $message = $jsonResponse[0]['message'];\n }\n\n throw new CrmException($message, $errorCode);\n }\n\n return $activity;\n }\n\n private function buildTextMessagePayload(Activity $activity): Activity\n {\n if ($this->getCrmType($activity->category) === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n if ($this->getCrmType($activity->category)->value === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n $cpActivity = $this->copperClient->activities()->create([\n 'user_id' => $this->profile->crm_provider_id,\n 'activity_date' => $activity->created_at->timestamp,\n 'parent' => $this->convertActivityAssociations($activity),\n 'type' => $this->convertActivityType($activity->category),\n 'details' => $this->generateActivityDescription($activity),\n ]);\n\n $activity->crm_provider_id = $cpActivity['id'];\n $activity->save();\n\n return $activity;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = '';\n\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n $description = 'Jiminny Call Summary' . PHP_EOL . PHP_EOL;\n $description .= 'Call Duration: ' . $activity->duration_for_humans . PHP_EOL . PHP_EOL;\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= 'Dialed: ' . $activity->to->phone_number . PHP_EOL . PHP_EOL;\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= 'Notetaker removed from this meeting' . PHP_EOL . PHP_EOL;\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= 'Notetaker did not join due to recording consent not being provided by attendees' . PHP_EOL . PHP_EOL;\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= 'Review Activity:' . PHP_EOL . $playbackUrl . PHP_EOL . PHP_EOL;\n }\n\n if ($activity->getCrmType() === Activity::TYPE_CONFERENCE) {\n $description .= 'Attendees:'\n . PHP_EOL\n . (new FilterJoinedParticipants())->toString($activity);\n }\n\n if (\\count($activity->notes) > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Notes: ' . PHP_EOL;\n\n foreach ($activity->notes as $note) {\n $nTime = (int) ceil($note->time);\n $time = ($nTime > 3600) ? gmdate('H:i:s', $nTime) : gmdate('i:s', $nTime);\n $description .= $time . ' ' . $note->note . PHP_EOL;\n }\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Coaching Chat: ' . PHP_EOL;\n\n foreach ($messages->get() as $message) {\n $description .= $message->participant->name . ': ' . $message->message . PHP_EOL;\n }\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Customer Chat: ' . PHP_EOL;\n\n foreach ($messages->get() as $message) {\n $description .= $message->participant->name . ': ' . $message->message . PHP_EOL;\n }\n }\n\n if ($activity->summary) {\n $description .= PHP_EOL . PHP_EOL . 'Summary: ' . PHP_EOL . $activity->summary;\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $description = $activity->description;\n\n break;\n }\n\n return $description;\n }\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // This is the user provided activity subject field.\n if (empty($fields['type'])) {\n return null;\n }\n\n $reminder = null;\n if (empty($fields['reminder_date']) === false) {\n $formatReminder = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['reminder_date']);\n $reminder = $formatReminder->getTimestamp();\n }\n\n $due = null;\n if (empty($fields['due_date']) === false) {\n $formatDue = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['due_date']);\n $due = $formatDue->getTimestamp();\n }\n\n $data = [\n 'custom_activity_type_id' => $fields['type'],\n 'status' => 'Open',\n 'assignee_id' => $this->profile->crm_provider_id,\n 'due_date' => $due,\n 'details' => $fields['details'] ?? '',\n 'reminder_date' => $reminder,\n 'name' => $fields['name'] ?? 'Follow-up',\n 'related_resource' => $this->convertActivityAssociations($activity),\n 'custom_fields' => $this->fetchCustomFieldData($activity, Field::OBJECT_TASK),\n ];\n\n // We don't actually create a corresponding activity object on our side yet.\n return $this->copperClient->tasks()->create($data)['id'];\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws \\Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // Generate activity transcription.\n $transcriptionData = $this->generateTranscription($activity);\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $transcripts = mb_strimwidth($transcriptionData, 0, static::NOTE_BODY_MAX_LENGTH);\n\n $data = [\n 'user_id' => $this->profile->crm_provider_id,\n 'type' => [\n 'category' => 'user',\n 'id' => 0, // This creates a note.\n ],\n 'activity_date' => time(),\n 'details' => $transcripts,\n 'parent' => $this->convertActivityAssociations($activity),\n ];\n\n $cpActivity = $this->copperClient->activities()->create($data);\n\n // Store CRM Activity ID in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $cpActivity['id'];\n $transcription->save();\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n if ($crmObject instanceof Lead) {\n $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->update($crmObject->crm_provider_id, [\n 'status_id' => $stage->crm_provider_id,\n ])\n );\n } else {\n $this->copperClient->opportunities()->update($crmObject->crm_provider_id, [\n 'pipeline_stage_id' => $stage->crm_provider_id,\n ]);\n }\n }\n\n public function prepareValueForUpdate(array $params): array\n {\n return [$params['fieldName'] => $params['fieldValue']];\n }\n\n /*\n * @inheritdoc\n */\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $preparedData = $data;\n\n if ($objectType === Field::OBJECT_OPPORTUNITY) {\n $preparedData = $this->prepareOpportunityFieldsForUpdate($data);\n }\n\n try {\n $this->copperClient\n ->createResourceFromObjectType($objectType)\n ->update($objectId, $preparedData)\n ;\n } catch (Exception $e) {\n $this->logger->error(self::RESOURCE_UPDATE_FAILED_ERROR_MESSAGE, [\n 'resource_id' => $objectId,\n 'data' => $preparedData,\n 'error' => $e->getMessage(),\n ]);\n\n throw new CrmException(self::RESOURCE_UPDATE_FAILED_ERROR_MESSAGE, $e->getCode(), $e);\n }\n }\n\n /**\n * @param array<string,string> $fieldData\n *\n * @throws CrmException\n *\n * @return array<string,array<int,array<string,bool|float|int|string|null>>|bool|float|int|string|null>\n */\n private function prepareOpportunityFieldsForUpdate(array $fieldData): array\n {\n $preparedData = [];\n $customFields = [];\n\n foreach ($fieldData as $fieldName => $fieldValue) {\n $field = $this->config\n ->fields()\n ->where('crm_provider_id', $fieldName)\n ->first();\n\n if (! $field instanceof Field) {\n throw new CrmException('Field not found');\n }\n\n $convertedValue = $this->fieldValueConverter->convertToCrm($field->getType(), $fieldValue);\n\n if ($this->isStandardField($fieldName)) {\n $preparedData[$fieldName] = $convertedValue;\n\n continue;\n }\n\n $customFields[] = [\n 'custom_field_definition_id' => $fieldName,\n 'value' => $convertedValue,\n ];\n }\n\n if (! empty($customFields)) {\n $preparedData['custom_fields'] = $customFields;\n }\n\n return $preparedData;\n }\n\n /*\n * @inheritdoc\n */\n public function getRecord(string $objectType, string $objectId, array $fields = []): array\n {\n return $this->copperClient->createResourceFromObjectType($objectType)->find($objectId);\n }\n\n private function fetchCustomFieldData(Activity $activity, string $objectType): array\n {\n $payload = [];\n\n $fieldData = FieldData::where([\n 'object_id' => $activity->id,\n ])->whereHas('field', function ($query) use ($objectType) {\n $query->where('object_type', $objectType);\n })->get();\n\n foreach ($fieldData as $data) {\n // Add the field and value to the payload.\n $payload += [\n 'custom_field_definition_id' => $data->field->crm_provider_id,\n 'value' => $data->value,\n ];\n }\n\n return $payload;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $baseUrl = 'https://app.prosperworks.com/companies/' . $this->config->crm_provider_id . '/app#/';\n switch ($objectType) {\n case 'lead':\n $url = $baseUrl . 'leads/' . $providerId;\n\n break;\n\n case 'account':\n $url = $baseUrl . 'organization/' . $providerId;\n\n break;\n\n case 'contact':\n $url = $baseUrl . 'contact/' . $providerId;\n\n break;\n\n case 'opportunity':\n $url = $baseUrl . 'deal/' . $providerId;\n\n break;\n\n default:\n case 'task':\n case 'activity':\n // Sadly we can't deeplink to these in Copper UI.\n $url = null;\n }\n\n return $url;\n }\n\n /**\n * Generate transcription for the activity.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! ($this->config->store_transcript)) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n return $this->transcriptionService\n ->findTranscriptionByActivity($activity)\n ->map(static function (array $transcriptionSegment): string {\n return $transcriptionSegment['formattedStartsAt'] . ' | ' . $transcriptionSegment['transcript'];\n })\n ->implode(PHP_EOL);\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n *\n * @return int|string|bool|float|null\n */\n private function extractFieldValue(array $opportunityData, string $fieldName)\n {\n $fieldValue = $this->isStandardField($fieldName)\n ? $opportunityData[$fieldName]\n : $this->resolveCustomFieldFromOpportunityData($opportunityData, $fieldName);\n\n if (is_array($fieldValue)) {\n $fieldValue = implode(', ', $fieldValue);\n }\n\n return $fieldValue;\n }\n\n private function isStandardField(string $fieldName): bool\n {\n return array_key_exists($fieldName, self::STANDARD_OPPORTUNITY_FIELDS);\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n *\n * @return string|int|float|bool|null|array<string, mixed>\n */\n private function resolveCustomFieldFromOpportunityData(array $opportunityData, string $fieldName)\n {\n $fieldData = array_filter(\n $opportunityData['custom_fields'],\n static fn ($field) => (string) $field['custom_field_definition_id'] === $fieldName\n );\n\n return array_pop($fieldData)['value'] ?? '';\n }\n\n private function isSupportedObjectType(string $objectType): bool\n {\n return $objectType !== self::UNSUPPORTED_OBJECT_TYPE;\n }\n\n private function syncStandardFields(): void\n {\n foreach (self::STANDARD_OPPORTUNITY_FIELDS as $fieldId => $fieldData) {\n $this->config->fields()->updateOrCreate([\n 'crm_provider_id' => mb_strimwidth($fieldId, 0, 128),\n 'object_type' => Field::OBJECT_OPPORTUNITY,\n ], [\n 'label' => mb_strimwidth($fieldData['label'], 0, Field::LABEL_MAX_LENGTH),\n 'type' => $fieldData['type'],\n ]);\n }\n\n $this->importStages([Stage::TYPE_OPPORTUNITY]);\n }\n\n private function requestWithExceptionHandling(\\Closure $apiRequest): iterable\n {\n try {\n return $apiRequest();\n } catch (\\Exception $exception) {\n if ($exception->getCode() === 403) {\n // Object might not be supported\n return [];\n }\n\n \\Sentry::captureException($exception);\n\n return [];\n }\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n if ($this->copperClient === null) {\n return false;\n }\n\n $task = $this->copperClient->tasks()->find($crmProviderId);\n\n return ! empty($task);\n } catch (HttpNotFoundException) {\n // Task not found in CRM - this is expected and permanent\n $this->logger->info('[Copper] Task not found during verification', [\n 'task_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n } catch (RequestFailedException $e) {\n // Handle 404 responses from Copper API\n if ($e->getCode() === 404) {\n $this->logger->info('[Copper] Task not found during verification (404)', [\n 'task_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n\n // Re-throw other Copper exceptions for retry\n throw $e;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Copper;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse GuzzleHttp\\Exception\\ClientException;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\CopperInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\FieldValue;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\PlaybookCategory;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\UserRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\Copper\\Api\\Client;\nuse Jiminny\\Services\\Crm\\Copper\\Api\\ClientFactory;\nuse Jiminny\\Services\\Crm\\Copper\\Exception\\RequestFailedException;\nuse Jiminny\\Services\\Crm\\Helpers\\FilterJoinedParticipants;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Services\\Crm\\Copper\\Traits\\SearchesCrmEntities;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\n\nclass Service extends BaseService implements\n CopperInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n use SearchesCrmEntities;\n private const int NOTE_BODY_MAX_LENGTH = 3000000;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const array STANDARD_OPPORTUNITY_FIELDS = [\n 'monetary_value' => [\n 'label' => 'Value',\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n 'type' => Field::TYPE_CURRENCY,\n ],\n 'pipeline_stage_id' => [\n 'label' => 'Stage',\n 'type' => Field::TYPE_PICKLIST,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n 'close_date' => [\n 'label' => 'Close date',\n 'type' => Field::TYPE_DATE,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n 'win_probability' => [\n 'label' => 'Win probability',\n 'type' => Field::TYPE_NUMBER,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n ];\n private const string UNSUPPORTED_OBJECT_TYPE = 'unsupported';\n private const string OPPORTUNITY_STATUS_OPEN = 'Open';\n private const string OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE = 'Opportunity import failed';\n private const string RESOURCE_UPDATE_FAILED_ERROR_MESSAGE = 'Failed to update resource';\n\n private FieldValueConverter $fieldValueConverter;\n private ClientFactory $clientFactory;\n private ?Client $copperClient = null;\n\n public function __construct(\n ClientFactory $clientFactory,\n FieldValueConverter $fieldValueConverter,\n private readonly UserRepository $userRepository,\n private readonly ProspectPhotoPathService $prospectPhotoPathService,\n private readonly CrmEntityRepository $crmEntityRepository\n ) {\n parent::__construct();\n\n $this->clientFactory = $clientFactory;\n $this->fieldValueConverter = $fieldValueConverter;\n }\n\n public function getDisplayName(): string\n {\n return 'Copper';\n }\n\n /**\n * Get the CRM entity repository (used by SearchesCrmEntities trait)\n */\n protected function getCrmEntityRepository(): CrmEntityRepository\n {\n return $this->crmEntityRepository;\n }\n\n public function getMinimumApiVersion(): string\n {\n return Client::MIN_API_VERSION;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_COPPER);\n }\n\n public function setUser(User $user): void\n {\n $this->configureSentryScope($user);\n\n $this->team = $user->getTeam();\n $this->teamService->setTeam($user->getTeam());\n $this->setConfiguration($user->getTeam()->getCrmConfiguration());\n\n // Reset state.\n $this->profile = $user->getProfile();\n\n if (! $this->profile instanceof Profile) {\n // Try to fetch their profile, maybe it was not yet imported?\n $this->profile = $this->getProfile($user);\n }\n }\n\n public function setConfiguration(Configuration $configuration): void\n {\n $this->config = $configuration;\n $this->copperClient = $this->clientFactory->create($configuration);\n\n if ($this->team === null) {\n $this->team = $configuration->getTeam();\n }\n }\n\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return $this->fieldValueConverter->convertFromCrm($fieldType, $fieldValue);\n }\n\n private function mapObjectType(string $objectType): string\n {\n $objectType = strtolower($objectType);\n\n switch ($objectType) {\n case Field::OBJECT_TASK:\n case Field::OBJECT_OPPORTUNITY:\n case Field::OBJECT_LEAD:\n $mappedType = $objectType;\n\n break;\n case Field::OBJECT_ACCOUNT:\n $mappedType = 'company';\n\n break;\n case Field::OBJECT_CONTACT:\n $mappedType = 'person';\n\n break;\n default:\n $mappedType = self::UNSUPPORTED_OBJECT_TYPE;\n\n break;\n }\n\n return $mappedType;\n }\n\n /**\n * @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact\n */\n protected function getFields(string $crmObject): array\n {\n $mappedObjectType = $this->mapObjectType($crmObject);\n\n if (! $this->isSupportedObjectType($mappedObjectType)) {\n return [];\n }\n\n $customFields = $this->copperClient->fields()->all();\n\n $filteredFields = array_filter(\n $customFields,\n static fn ($field) => in_array($mappedObjectType, $field['available_on'], true)\n );\n\n return array_map(\n fn (array $property) => [\n 'name' => $property['id'],\n 'label' => $property['name'],\n 'type' => $this->convertFieldType($property['data_type']),\n ],\n $filteredFields\n );\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {\n $defaultFields = FieldDefinitions::defaultTaskFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n $fieldFilters = FieldDefinitions::taskFollowupFieldsFilter();\n\n foreach ($fieldFilters as $data) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n public function syncFields(): void\n {\n $this->syncStandardFields();\n $this->syncCustomFields();\n }\n\n public function syncField(Field $field): void\n {\n if ($field->getCrmProviderId() === 'type') {\n /**\n * This field is a special case, it is not a custom field and is not returned by the Copper API.\n *\n * The field is created manually during layout setup.\n *\n * @see getDefaultFields()\n *\n * There is a separate endpoint to get the activity types.\n * @see importPicklistValues()\n */\n return;\n }\n\n if ($field->getCrmProviderId() === 'pipeline_stage_id') {\n // Not a custom type\n return;\n }\n\n $crmField = $this->copperClient->fields()->find($field->getCrmProviderId());\n $field->label = $crmField['name'];\n $field->type = $this->convertFieldType($crmField['data_type']);\n\n $field->save();\n }\n\n /**\n * @param string $fieldType How the data should be input\n */\n private function convertFieldType(string $fieldType): string\n {\n $fieldType = strtolower($fieldType);\n\n switch ($fieldType) {\n case 'dropdown':\n $convertedType = Field::TYPE_PICKLIST;\n\n break;\n case 'string':\n $convertedType = Field::TYPE_TEXT;\n\n break;\n case 'float':\n case 'percentage':\n $convertedType = Field::TYPE_NUMBER;\n\n break;\n case 'text':\n $convertedType = Field::TYPE_TEXTAREA;\n\n break;\n case 'checkbox':\n $convertedType = Field::TYPE_BOOLEAN;\n\n break;\n case Field::TYPE_DATE:\n case Field::TYPE_CURRENCY:\n case Field::TYPE_URL:\n $convertedType = $fieldType;\n\n break;\n default:\n $convertedType = Field::TYPE_UNSUPPORTED;\n\n break;\n }\n\n return $convertedType;\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $fieldValues = [];\n\n if ($field->object_type === 'opportunity' && $field->crm_provider_id === 'pipeline_stage_id') {\n return $this->importFieldValuesForDealInsights($field);\n }\n\n $values = [];\n\n if ($field->object_type === Field::OBJECT_TASK && $field->crm_provider_id === 'type') {\n $activityTypes = $this->copperClient->activityTypes()->all();\n\n /**\n * We ignore \"system\" activity types, disabled activity types and the \"Note\" activity type.\n */\n $activityTypes = array_filter(\n $activityTypes['user'],\n fn (array $activityType) => ! $activityType['is_disabled'] && $activityType['id'] !== 0\n );\n\n // Import all activity values.\n $i = 0;\n foreach ($activityTypes as $activityType) {\n $values[] = [\n 'value' => $activityType['id'],\n 'label' => mb_strimwidth($activityType['name'], 0, Field::LABEL_MAX_LENGTH),\n 'sequence' => $i++,\n ];\n }\n } else {\n // We just check for the field in the custom definitions.\n $crmField = $this->copperClient->fields()->find($field->crm_provider_id);\n\n // Import all values.\n foreach ($crmField['options'] as $option) {\n $values[] = [\n 'value' => $option['id'],\n 'label' => mb_strimwidth($option['name'], 0, 191),\n 'sequence' => $option['rank'],\n ];\n }\n }\n\n // Take the existing set of field values.\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n // For all current values, upsert the field.\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n $key = array_search($value['value'], $fieldsToPurge, false);\n if ($key !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n\n return $fieldValues;\n }\n\n /**\n *\n * @return FieldValue[]\n */\n private function importFieldValuesForDealInsights(Field $field): array\n {\n $fieldValues = [];\n $pipelines = $this->copperClient->pipelines()->all();\n\n foreach ($pipelines as $pipeline) {\n foreach ($pipeline['stages'] as $i => $dealStage) {\n $fieldValues[] = $field->values()->updateOrCreate(\n ['value' => $dealStage['id']],\n [\n 'label' => $dealStage['name'],\n 'sequence' => $i,\n ]\n );\n }\n }\n\n return $fieldValues;\n }\n\n /**\n * @inheritdoc\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n $missingStage = null;\n\n foreach ($types as $type) {\n if ($type === Stage::TYPE_LEAD) {\n $statuses = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leadStatuses()->all()\n );\n\n if (count($statuses) > 0) {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => BusinessProcess::TYPE_LEAD,\n ], [\n 'team_id' => $this->team->id,\n 'name' => BusinessProcess::TYPE_LEAD,\n 'type' => BusinessProcess::TYPE_LEAD,\n 'is_selectable' => true,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => BusinessProcess::TYPE_LEAD,\n ], [\n 'team_id' => $this->team->id,\n 'name' => BusinessProcess::TYPE_LEAD,\n 'is_selectable' => true,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $leadStatuses = [];\n foreach ($statuses as $status) {\n // Upsert all statuses for the team.\n $status = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $status['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($status['name'], 0, 50),\n 'label' => mb_strimwidth($status['name'], 0, 191),\n 'type' => Stage::TYPE_LEAD,\n 'sequence' => $status['order'],\n 'is_selectable' => true,\n ]);\n\n if ($missingStageName && $missingStageName === $status['id']) {\n $missingStage = $status;\n }\n\n $leadStatuses[] = $status['id'];\n }\n\n $businessProcess->stages()->sync($leadStatuses);\n }\n } else {\n // We create a business process to contain the pipeline, and later store all stages against it.\n foreach ($this->copperClient->pipelines()->all() as $pipeline) {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $pipeline['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline['name'], 0, 150),\n 'type' => BusinessProcess::TYPE_OPPORTUNITY,\n 'is_selectable' => true,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $pipeline['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline['name'], 0, 150),\n 'is_selectable' => true,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $stages = [];\n\n foreach ($pipeline['stages'] as $i => $dealStage) {\n // Upsert all stages for the team.\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $dealStage['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($dealStage['name'], 0, 50),\n 'label' => mb_strimwidth($dealStage['name'], 0, 191),\n 'type' => Stage::TYPE_OPPORTUNITY,\n 'sequence' => $i,\n 'is_selectable' => true,\n 'probability' => $dealStage['win_probability'],\n ]);\n\n if ($missingStageName && $missingStageName === $dealStage['id']) {\n $missingStage = $stage;\n }\n\n $stages[] = $stage['id'];\n }\n\n $businessProcess->stages()->sync($stages);\n }\n }\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n\n $cpLeads = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->paginate([\n 'minimum_modified_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ])\n );\n\n foreach ($cpLeads as $cpLead) {\n // Only sync if previously imported.\n if ($this->hasLead($cpLead['id']) === false) {\n $this->importLead($cpLead);\n $syncCount++;\n }\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n $cpLead = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->find($crmId)\n );\n\n if (\\count($cpLead) === 0) {\n return null;\n }\n\n return $this->importLead($cpLead);\n }\n\n /**\n * @inheritdoc\n */\n private function importLead($crmData): ?Lead\n {\n $countryCode = null;\n if (! empty($crmData['address']) && isset($crmData['address']['country'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $mobilePhone = $parsedNumber = null;\n if (! empty($crmData['phone_numbers'])) {\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n if ($phoneNumber['category'] === 'mobile') {\n $mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);\n } else {\n $parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);\n }\n }\n }\n\n $name = $crmData['name'];\n\n if (empty($crmData['company_name'])) {\n $company = 'Unknown';\n } else {\n $company = mb_strimwidth($crmData['company_name'], 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['websites']) === false) {\n $domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $email = null;\n if (empty($crmData['email']) === false) {\n $email = mb_strimwidth($crmData['email']['email'], 0, 80);\n }\n\n $stage = $this->config\n ->stages()\n ->where('crm_provider_id', (string) $crmData['status_id'])\n ->where('type', Stage::TYPE_LEAD)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status_id']);\n }\n\n if (! $stage instanceof Stage) {\n return null;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($name, 0, 191),\n 'company' => $company,\n 'domain' => $domain,\n 'title' => $crmData['title'] ? mb_strimwidth($crmData['title'], 0, 128) : null,\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'mobile_phone' => $mobilePhone,\n 'stage_id' => $stage->id,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Lead::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'country_code' => $countryCode,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $cpAccounts = $this->copperClient->accounts()->paginate([\n 'minimum_modified_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ]);\n\n foreach ($cpAccounts as $cpAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($cpAccount['id'])) {\n $this->importAccount($cpAccount);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n $cpAccount = $this->copperClient->accounts()->find($crmId);\n\n if (empty($cpAccount)) {\n return null;\n }\n\n return $this->importAccount($cpAccount);\n }\n\n /**\n * @inheritdoc\n */\n private function importAccount($crmData): Account\n {\n $countryCode = null;\n if (empty($crmData['address']) === false && $crmData['address']['country']) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $name = $crmData['name'];\n\n $parsedNumber = null;\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n $parsedNumber = parsePhoneNumber($countryCode, $phoneNumber['number']);\n }\n\n $domain = null;\n if (empty($crmData['websites']) === false) {\n $domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Account::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'country_code' => $countryCode,\n 'domain' => $domain,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->copperClient,\n ]);\n $strategies = $strategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n\n try {\n foreach ($strategies as $syncStrategy) {\n foreach ($syncStrategy->fetchOpportunities($parameters) as $opportunityData) {\n $this->importOpportunity($opportunityData);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n $this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => $exception->getMessage(),\n ]);\n }\n\n return $syncCount;\n }\n\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->copperClient,\n ]);\n $strategy = $strategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n $parameters['crm_id'] = $crmId;\n\n $cpOpportunity = $strategy->fetchOpportunities($parameters);\n\n return $this->importOpportunity($cpOpportunity);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n $companyId = (string) $crmData['company_id'];\n\n if (empty($companyId)) {\n $this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => 'No company id',\n ]);\n\n return null;\n }\n\n $account = $this->config->accounts()->where('crm_provider_id', $companyId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($companyId);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', (string) $crmData['pipeline_id'])\n ->first();\n\n if ($businessProcess === null) {\n // It is possible for some deals to not be in a pipeline.\n $this->logger->warning(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => 'Missing pipeline',\n ]);\n\n return null;\n }\n\n $stage = $businessProcess\n ->stages()\n ->where('crm_provider_id', (string) $crmData['pipeline_stage_id'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n $this->logger->info('Stage not found, importing', [\n 'pipeline_id' => $crmData['pipeline_id'],\n 'stage_id' => $crmData['pipeline_stage_id'],\n ]);\n\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['pipeline_stage_id']);\n }\n\n $recordType = $businessProcess->recordTypes()->first();\n $closeDate = null;\n $isClosed = $crmData['status'] !== self::OPPORTUNITY_STATUS_OPEN;\n\n if ($crmData['close_date']) {\n $closeDate = Carbon::parse($crmData['close_date'])->format('Y-m-d');\n }\n\n $data = [\n 'team_id' => $this->team->getId(),\n 'account_id' => $account->id,\n 'user_id' => $profile->user_id ?? null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($crmData['name'], 0, 128),\n 'value' => $crmData['monetary_value'],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['monetary_unit']),\n 'close_date' => $closeDate,\n 'is_closed' => $isClosed,\n 'is_won' => $crmData['status'] === 'Won',\n 'stage_id' => $stage->id,\n 'record_type_id' => $recordType->id ?? null,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n /** @var Opportunity $opportunity */\n $opportunity = $this->config\n ->opportunities()\n ->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data)\n ;\n\n // import external fields into crm_field_data if present\n $dealInsightsFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData($crmData, $dealInsightsFields, $opportunity->id);\n\n return $opportunity;\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n * @param string[] $dealInsightsFields\n */\n public function importOpportunityCrmFieldData(\n array $opportunityData,\n array $dealInsightsFields,\n int $opportunityId\n ): void {\n foreach ($dealInsightsFields as $fieldName) {\n $field = $this->config->fields()->with('entities')\n ->where('crm_provider_id', $fieldName)\n ->where('object_type', Field::OBJECT_OPPORTUNITY)\n ->first();\n\n if (! $field instanceof Field) {\n $this->logger->warning('Field not found', [\n 'field' => $fieldName,\n 'opportunity_id' => $opportunityId,\n ]);\n\n continue;\n }\n\n $entity = $field->getEntities()->first();\n\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $fieldValue = $this->extractFieldValue($opportunityData, $fieldName);\n $normalizedValue = $this->normalizeValue($field->getType(), (string) $fieldValue, true);\n\n $field->data()\n ->updateOrCreate([\n 'crm_layout_entity_id' => $entity->id,\n 'crm_field_id' => $field->id,\n 'object_type' => 'opportunity',\n 'object_id' => $opportunityId,\n ], ['value' => $normalizedValue])\n ;\n }\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $cpContacts = $this->copperClient->contacts()->paginate([\n 'minimum_interaction_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ]);\n\n foreach ($cpContacts as $cpContact) {\n // Only sync if previously imported.\n if ($this->hasContact($cpContact['id'])) {\n $this->importContact($cpContact);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n throw $exception;\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n $cpContact = $this->copperClient->contacts()->find($crmId);\n\n if (empty($cpContact)) {\n return null;\n }\n\n return $this->importContact($cpContact);\n }\n\n /**\n * @inheritdoc\n */\n private function importContact($crmData): Contact\n {\n $account = null;\n if ($crmData['company_id']) {\n $account = $this->team\n ->crm\n ->accounts()\n ->where('crm_provider_id', (string) $crmData['company_id'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['company_id']);\n }\n }\n\n $countryCode = null;\n if (empty($crmData['address']) === false && $crmData['address']['country']) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $mobilePhone = $parsedNumber = null;\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n if ($phoneNumber['category'] === 'mobile') {\n $mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);\n } else {\n $parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);\n }\n }\n\n $email = null;\n if (empty($crmData['emails']) === false) {\n $email = mb_strimwidth($crmData['emails'][0]['email'], 0, 80);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => $crmData['name'],\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'mobile_phone' => $mobilePhone ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'title' => $crmData['title'],\n 'country_code' => $countryCode,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Contact::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function buildContactPhone(?string $countryCode, ?string $number): ?array\n {\n if ($number) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($number, 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n return $parsedNumber;\n }\n\n private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string\n {\n return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n $organization = $this->copperClient->organisation()->all();\n\n if ($this->config->crm_provider_id !== $organization['id']) {\n $this->config->update(['crm_provider_id' => $organization['id']]);\n }\n }\n\n private function syncCustomFields(): void\n {\n foreach ($this->getFieldTypes() as $fieldType) {\n $currentFields = $this->getFields($fieldType);\n\n foreach ($currentFields as $field) {\n /** @var Field $field */\n $field = $this->config->fields()->updateOrCreate([\n 'crm_provider_id' => $field['name'],\n 'object_type' => $fieldType,\n ], [\n 'label' => mb_strimwidth($field['label'], 0, Field::LABEL_MAX_LENGTH),\n 'type' => $field['type'],\n ]);\n\n if ($field->getType() === Field::TYPE_PICKLIST) {\n $this->importPicklistValues($field);\n }\n }\n }\n\n $this->config->save();\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n parent::OBJECT_LEAD,\n parent::OBJECT_ACCOUNT,\n parent::OBJECT_CONTACT,\n parent::OBJECT_OPPORTUNITY,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $profiles = $this->copperClient->users()->all();\n\n foreach ($profiles as $profile) {\n $user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);\n\n // Only import profiles for users we have locally.\n if ($user) {\n $profile = $user->crmProfile()->updateOrCreate([\n 'crm_configuration_id' => $this->config->id,\n 'crm_provider_id' => $profile['id'],\n ]);\n\n if ($userToSearch && $userToSearch->id === $user->id) {\n return $profile;\n }\n }\n }\n\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'task',\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields(ucfirst($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))\n );\n\n if (\\count($changedFields) > 0) {\n $fields = implode(',', $newFields);\n $this->logger->debug(\n ucfirst($fieldType)\n . ' fields changed from '\n . $this->profile->{$fieldType . '_fields'}\n . ' to: '\n . $fields\n );\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (\\Exception $exception) {\n $this->logger->error('No access to ' . $fieldType . ' object, skipping...');\n\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $scopeValues = array_map(fn ($scope) => is_string($scope) ? $scope : $scope->value, $scopes);\n $cacheKey = sprintf('copper-search-%d-%s-%s-%d-%d', $this->team->id, $name, implode('-', $scopeValues), $count, $offset);\n\n return Cache::remember($cacheKey, 300, function () use ($name, $scopes, $count, $offset) {\n // Try local search first\n $localResults = $this->searchLocally($name, $scopes, $count, $offset);\n\n // If no local results, fall back to remote API search\n if (empty($localResults)) {\n return $this->searchRemotely($name, $scopes, $count, $offset);\n }\n\n return $localResults;\n });\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $params = [\n 'company_ids' => [$account->crm_provider_id],\n 'status_ids' => [0], // The integer values are 0, 1, 2, 3, for \"Open\", \"Won\", \"Lost\", and \"Abandoned\".\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ];\n\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort_by'] = 'date_modified';\n $params['sort_direction'] = 'desc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort_by'] = 'date_created';\n $params['sort_direction'] = 'desc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort_by'] = 'date_created';\n $params['sort_direction'] = 'asc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort_by'] = 'date_modified';\n $params['sort_direction'] = 'desc';\n $params['status_ids'] = [0, 1, 2, 3];\n }\n\n $cpOpportunities = $this->copperClient->opportunities()->search($params);\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n foreach ($cpOpportunities as $cpOpportunity) {\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', (string) $cpOpportunity['pipeline_id'])\n ->first();\n\n if ($businessProcess === null) {\n // Import it.\n $businessProcess = $this->importStages(\n [Stage::TYPE_OPPORTUNITY],\n $cpOpportunity['pipeline_stage_id']\n );\n }\n\n $stage = $businessProcess\n ->stages()\n ->where('crm_provider_id', (string) $cpOpportunity['pipeline_stage_id'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $cpOpportunity['pipeline_stage_id']);\n }\n\n $recordType = $businessProcess->recordTypes()->first();\n\n $record = [\n 'crmId' => $cpOpportunity['id'],\n 'name' => $cpOpportunity['name'],\n 'value' => currency_format($cpOpportunity['monetary_value'], $cpOpportunity['monetary_unit']),\n 'won' => $cpOpportunity['status'] === 'Won',\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n\n if ($ownerId && isset($cpOpportunity['assignee_id']) && $cpOpportunity['assignee_id'] === $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $cpTasks = [];\n\n switch ($objectType) {\n case 'lead':\n $cpTasks = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->relatedTasks($objectId)\n );\n\n break;\n\n case 'account':\n $cpTasks = $this->copperClient->accounts()->relatedTasks($objectId);\n\n break;\n case 'contact':\n if ($opportunityId) {\n $cpTasks = $this->copperClient->opportunities()->relatedTasks($opportunityId);\n } elseif ($objectType === 'contact') {\n $cpTasks = $this->copperClient->contacts()->relatedTasks($objectId);\n }\n\n break;\n }\n\n foreach ($cpTasks as $cpTask) {\n // We only get the ID itself returned, so pull out the full object.\n try {\n $cpTask = $this->copperClient->tasks()->find($cpTask['id']);\n } catch (Exception $exception) {\n $this->logger->error('[Copper] Error fetching task', [\n 'resource_id' => $cpTask['id'],\n 'error' => $exception->getMessage(),\n ]);\n\n continue;\n }\n\n // Only allow open tasks.\n if ($cpTask['status'] === 'Open') {\n $data[] = [\n 'crmId' => $cpTask['id'],\n 'subject' => $cpTask['name'],\n 'due' => $cpTask['due_date']\n ? Carbon::createFromTimestamp($cpTask['due_date'])->format('Y-m-d\\TH:i:sO')\n : null,\n 'type' => null,\n ];\n }\n }\n\n return $data;\n }\n\n /**\n * Try to find email address in CRM service\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $cpObjectType = 'contact';\n\n $cpObjects = $this->copperClient->contacts()->search([\n 'emails' => $email,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (empty($cpObjects)) {\n $cpObjectType = 'lead';\n $cpObjects = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'emails' => $email,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (empty($cpObjects)) {\n return null;\n }\n\n // Search returns an array of results, but we only want the first\n $cpObject = reset($cpObjects);\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember === false) {\n $cpObjectType = 'contact';\n $cpObject = $this->copperClient->contacts()->search([\n 'phone_number' => $phone,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (\\count($cpObject) === 0) {\n $cpObjectType = 'lead';\n $cpObject = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'phone_number' => $phone,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (empty($cpObject)) {\n return null;\n }\n\n $cpObject = reset($cpObject);\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n return null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n $result = \\Cache::remember($this->team->id . $name, 60, function () use ($name, $userId) {\n $cpObjectType = 'contact';\n $cpObject = $this->copperClient->contacts()->search([\n 'name' => $name,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (\\count($cpObject) === 0) {\n $cpObjectType = 'lead';\n $cpObject = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'name' => $name,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (! empty($cpObject)) {\n $cpObject = reset($cpObject);\n }\n\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n private function convertCrmData(array $object, string $objectType, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n if ($objectType === 'lead') {\n $lead = $this->importLead($object);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } else {\n $contact = $this->importContact($object);\n $account = $contact->account;\n\n if ($contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $cpOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact->crm_provider_id,\n $userId,\n );\n\n if (! empty($cpOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($cpOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n } catch (\\Exception $e) {\n // Nothing to see here.\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n public function saveActivity(Activity $activity): Activity\n {\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n $activity = $this->buildCallPayload($activity);\n\n break;\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildTextMessagePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n private function convertActivityAssociations(Activity $activity): array\n {\n if ($activity->lead) {\n $type = 'lead';\n $id = $activity->lead->crm_provider_id;\n } elseif ($activity->contact) {\n $type = 'person';\n $id = $activity->contact->crm_provider_id;\n } elseif ($activity->opportunity) {\n $type = 'opportunity';\n $id = $activity->opportunity->crm_provider_id;\n } else {\n $type = 'company';\n $id = $activity->account->crm_provider_id;\n }\n\n return [\n 'type' => $type,\n 'id' => $id,\n ];\n }\n\n private function convertActivityType(PlaybookCategory $activityType): array\n {\n return [\n 'category' => 'user',\n 'id' => $this->getCrmType($activityType)->value,\n ];\n }\n\n /**\n * @throws CrmException\n */\n private function buildCallPayload(Activity $activity): Activity\n {\n try {\n if ($activity->crm_provider_id) {\n // The activity should be logged under the existing Task (not Activity).\n $newActivityType = $this->getCrmType($activity->category);\n if ($newActivityType === null) {\n $message = sprintf('[Copper] invalid CRM Custom Activity Type: %s', $activity->category);\n\n throw new CrmException($message, 400);\n }\n $this->copperClient->tasks()->update($activity->crm_provider_id, [\n 'status' => 'Completed',\n 'custom_activity_type_id' => $newActivityType->value,\n 'details' => $this->generateActivityDescription($activity),\n ]);\n } else {\n if ($this->getCrmType($activity->category) === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n if ($this->getCrmType($activity->category)->value === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n // Just create an activity.\n $cpActivity = $this->copperClient->activities()->create([\n 'user_id' => $this->profile->crm_provider_id,\n 'activity_date' => $activity->scheduled_start_time->timestamp,\n 'parent' => $this->convertActivityAssociations($activity),\n 'type' => $this->convertActivityType($activity->category),\n 'details' => $this->generateActivityDescription($activity),\n ]);\n\n $activity->crm_provider_id = $cpActivity['id'];\n $activity->save();\n }\n } catch (ClientException $exception) {\n //Log all errors to Sentry\n \\Sentry::captureException($exception);\n\n $response = $exception->getResponse();\n\n $responseBody = $response->getBody();\n $message = $responseBody;\n $errorCode = $response->getStatusCode();\n\n $jsonResponse = json_decode($responseBody, true);\n if (isset($jsonResponse[0]['message'])) {\n $message = $jsonResponse[0]['message'];\n }\n\n throw new CrmException($message, $errorCode);\n }\n\n return $activity;\n }\n\n private function buildTextMessagePayload(Activity $activity): Activity\n {\n if ($this->getCrmType($activity->category) === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n if ($this->getCrmType($activity->category)->value === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n $cpActivity = $this->copperClient->activities()->create([\n 'user_id' => $this->profile->crm_provider_id,\n 'activity_date' => $activity->created_at->timestamp,\n 'parent' => $this->convertActivityAssociations($activity),\n 'type' => $this->convertActivityType($activity->category),\n 'details' => $this->generateActivityDescription($activity),\n ]);\n\n $activity->crm_provider_id = $cpActivity['id'];\n $activity->save();\n\n return $activity;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = '';\n\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n $description = 'Jiminny Call Summary' . PHP_EOL . PHP_EOL;\n $description .= 'Call Duration: ' . $activity->duration_for_humans . PHP_EOL . PHP_EOL;\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= 'Dialed: ' . $activity->to->phone_number . PHP_EOL . PHP_EOL;\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= 'Notetaker removed from this meeting' . PHP_EOL . PHP_EOL;\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= 'Notetaker did not join due to recording consent not being provided by attendees' . PHP_EOL . PHP_EOL;\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= 'Review Activity:' . PHP_EOL . $playbackUrl . PHP_EOL . PHP_EOL;\n }\n\n if ($activity->getCrmType() === Activity::TYPE_CONFERENCE) {\n $description .= 'Attendees:'\n . PHP_EOL\n . (new FilterJoinedParticipants())->toString($activity);\n }\n\n if (\\count($activity->notes) > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Notes: ' . PHP_EOL;\n\n foreach ($activity->notes as $note) {\n $nTime = (int) ceil($note->time);\n $time = ($nTime > 3600) ? gmdate('H:i:s', $nTime) : gmdate('i:s', $nTime);\n $description .= $time . ' ' . $note->note . PHP_EOL;\n }\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Coaching Chat: ' . PHP_EOL;\n\n foreach ($messages->get() as $message) {\n $description .= $message->participant->name . ': ' . $message->message . PHP_EOL;\n }\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Customer Chat: ' . PHP_EOL;\n\n foreach ($messages->get() as $message) {\n $description .= $message->participant->name . ': ' . $message->message . PHP_EOL;\n }\n }\n\n if ($activity->summary) {\n $description .= PHP_EOL . PHP_EOL . 'Summary: ' . PHP_EOL . $activity->summary;\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $description = $activity->description;\n\n break;\n }\n\n return $description;\n }\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // This is the user provided activity subject field.\n if (empty($fields['type'])) {\n return null;\n }\n\n $reminder = null;\n if (empty($fields['reminder_date']) === false) {\n $formatReminder = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['reminder_date']);\n $reminder = $formatReminder->getTimestamp();\n }\n\n $due = null;\n if (empty($fields['due_date']) === false) {\n $formatDue = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['due_date']);\n $due = $formatDue->getTimestamp();\n }\n\n $data = [\n 'custom_activity_type_id' => $fields['type'],\n 'status' => 'Open',\n 'assignee_id' => $this->profile->crm_provider_id,\n 'due_date' => $due,\n 'details' => $fields['details'] ?? '',\n 'reminder_date' => $reminder,\n 'name' => $fields['name'] ?? 'Follow-up',\n 'related_resource' => $this->convertActivityAssociations($activity),\n 'custom_fields' => $this->fetchCustomFieldData($activity, Field::OBJECT_TASK),\n ];\n\n // We don't actually create a corresponding activity object on our side yet.\n return $this->copperClient->tasks()->create($data)['id'];\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws \\Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // Generate activity transcription.\n $transcriptionData = $this->generateTranscription($activity);\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $transcripts = mb_strimwidth($transcriptionData, 0, static::NOTE_BODY_MAX_LENGTH);\n\n $data = [\n 'user_id' => $this->profile->crm_provider_id,\n 'type' => [\n 'category' => 'user',\n 'id' => 0, // This creates a note.\n ],\n 'activity_date' => time(),\n 'details' => $transcripts,\n 'parent' => $this->convertActivityAssociations($activity),\n ];\n\n $cpActivity = $this->copperClient->activities()->create($data);\n\n // Store CRM Activity ID in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $cpActivity['id'];\n $transcription->save();\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n if ($crmObject instanceof Lead) {\n $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->update($crmObject->crm_provider_id, [\n 'status_id' => $stage->crm_provider_id,\n ])\n );\n } else {\n $this->copperClient->opportunities()->update($crmObject->crm_provider_id, [\n 'pipeline_stage_id' => $stage->crm_provider_id,\n ]);\n }\n }\n\n public function prepareValueForUpdate(array $params): array\n {\n return [$params['fieldName'] => $params['fieldValue']];\n }\n\n /*\n * @inheritdoc\n */\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $preparedData = $data;\n\n if ($objectType === Field::OBJECT_OPPORTUNITY) {\n $preparedData = $this->prepareOpportunityFieldsForUpdate($data);\n }\n\n try {\n $this->copperClient\n ->createResourceFromObjectType($objectType)\n ->update($objectId, $preparedData)\n ;\n } catch (Exception $e) {\n $this->logger->error(self::RESOURCE_UPDATE_FAILED_ERROR_MESSAGE, [\n 'resource_id' => $objectId,\n 'data' => $preparedData,\n 'error' => $e->getMessage(),\n ]);\n\n throw new CrmException(self::RESOURCE_UPDATE_FAILED_ERROR_MESSAGE, $e->getCode(), $e);\n }\n }\n\n /**\n * @param array<string,string> $fieldData\n *\n * @throws CrmException\n *\n * @return array<string,array<int,array<string,bool|float|int|string|null>>|bool|float|int|string|null>\n */\n private function prepareOpportunityFieldsForUpdate(array $fieldData): array\n {\n $preparedData = [];\n $customFields = [];\n\n foreach ($fieldData as $fieldName => $fieldValue) {\n $field = $this->config\n ->fields()\n ->where('crm_provider_id', $fieldName)\n ->first();\n\n if (! $field instanceof Field) {\n throw new CrmException('Field not found');\n }\n\n $convertedValue = $this->fieldValueConverter->convertToCrm($field->getType(), $fieldValue);\n\n if ($this->isStandardField($fieldName)) {\n $preparedData[$fieldName] = $convertedValue;\n\n continue;\n }\n\n $customFields[] = [\n 'custom_field_definition_id' => $fieldName,\n 'value' => $convertedValue,\n ];\n }\n\n if (! empty($customFields)) {\n $preparedData['custom_fields'] = $customFields;\n }\n\n return $preparedData;\n }\n\n /*\n * @inheritdoc\n */\n public function getRecord(string $objectType, string $objectId, array $fields = []): array\n {\n return $this->copperClient->createResourceFromObjectType($objectType)->find($objectId);\n }\n\n private function fetchCustomFieldData(Activity $activity, string $objectType): array\n {\n $payload = [];\n\n $fieldData = FieldData::where([\n 'object_id' => $activity->id,\n ])->whereHas('field', function ($query) use ($objectType) {\n $query->where('object_type', $objectType);\n })->get();\n\n foreach ($fieldData as $data) {\n // Add the field and value to the payload.\n $payload += [\n 'custom_field_definition_id' => $data->field->crm_provider_id,\n 'value' => $data->value,\n ];\n }\n\n return $payload;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $baseUrl = 'https://app.prosperworks.com/companies/' . $this->config->crm_provider_id . '/app#/';\n switch ($objectType) {\n case 'lead':\n $url = $baseUrl . 'leads/' . $providerId;\n\n break;\n\n case 'account':\n $url = $baseUrl . 'organization/' . $providerId;\n\n break;\n\n case 'contact':\n $url = $baseUrl . 'contact/' . $providerId;\n\n break;\n\n case 'opportunity':\n $url = $baseUrl . 'deal/' . $providerId;\n\n break;\n\n default:\n case 'task':\n case 'activity':\n // Sadly we can't deeplink to these in Copper UI.\n $url = null;\n }\n\n return $url;\n }\n\n /**\n * Generate transcription for the activity.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! ($this->config->store_transcript)) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n return $this->transcriptionService\n ->findTranscriptionByActivity($activity)\n ->map(static function (array $transcriptionSegment): string {\n return $transcriptionSegment['formattedStartsAt'] . ' | ' . $transcriptionSegment['transcript'];\n })\n ->implode(PHP_EOL);\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n *\n * @return int|string|bool|float|null\n */\n private function extractFieldValue(array $opportunityData, string $fieldName)\n {\n $fieldValue = $this->isStandardField($fieldName)\n ? $opportunityData[$fieldName]\n : $this->resolveCustomFieldFromOpportunityData($opportunityData, $fieldName);\n\n if (is_array($fieldValue)) {\n $fieldValue = implode(', ', $fieldValue);\n }\n\n return $fieldValue;\n }\n\n private function isStandardField(string $fieldName): bool\n {\n return array_key_exists($fieldName, self::STANDARD_OPPORTUNITY_FIELDS);\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n *\n * @return string|int|float|bool|null|array<string, mixed>\n */\n private function resolveCustomFieldFromOpportunityData(array $opportunityData, string $fieldName)\n {\n $fieldData = array_filter(\n $opportunityData['custom_fields'],\n static fn ($field) => (string) $field['custom_field_definition_id'] === $fieldName\n );\n\n return array_pop($fieldData)['value'] ?? '';\n }\n\n private function isSupportedObjectType(string $objectType): bool\n {\n return $objectType !== self::UNSUPPORTED_OBJECT_TYPE;\n }\n\n private function syncStandardFields(): void\n {\n foreach (self::STANDARD_OPPORTUNITY_FIELDS as $fieldId => $fieldData) {\n $this->config->fields()->updateOrCreate([\n 'crm_provider_id' => mb_strimwidth($fieldId, 0, 128),\n 'object_type' => Field::OBJECT_OPPORTUNITY,\n ], [\n 'label' => mb_strimwidth($fieldData['label'], 0, Field::LABEL_MAX_LENGTH),\n 'type' => $fieldData['type'],\n ]);\n }\n\n $this->importStages([Stage::TYPE_OPPORTUNITY]);\n }\n\n private function requestWithExceptionHandling(\\Closure $apiRequest): iterable\n {\n try {\n return $apiRequest();\n } catch (\\Exception $exception) {\n if ($exception->getCode() === 403) {\n // Object might not be supported\n return [];\n }\n\n \\Sentry::captureException($exception);\n\n return [];\n }\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n if ($this->copperClient === null) {\n return false;\n }\n\n $task = $this->copperClient->tasks()->find($crmProviderId);\n\n return ! empty($task);\n } catch (HttpNotFoundException) {\n // Task not found in CRM - this is expected and permanent\n $this->logger->info('[Copper] Task not found during verification', [\n 'task_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n } catch (RequestFailedException $e) {\n // Handle 404 responses from Copper API\n if ($e->getCode() === 404) {\n $this->logger->info('[Copper] Task not found during verification (404)', [\n 'task_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n\n // Re-throw other Copper exceptions for retry\n throw $e;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","depth":4,"on_screen":true,"value":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.28224733,"top":1.0,"width":0.024268618,"height":-0.04788506},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Expand Selected","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Collapse All","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Options","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
8957564869086018857
|
-7959665055215941403
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
11
72
1
4
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Copper;
use Carbon\Carbon;
use Exception;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Facades\Cache;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\CopperInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\FieldValue;
use Jiminny\Models\Crm\LayoutEntity;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\PlaybookCategory;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\UserRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\Copper\Api\Client;
use Jiminny\Services\Crm\Copper\Api\ClientFactory;
use Jiminny\Services\Crm\Copper\Exception\RequestFailedException;
use Jiminny\Services\Crm\Helpers\FilterJoinedParticipants;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Services\Crm\Copper\Traits\SearchesCrmEntities;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
class Service extends BaseService implements
CopperInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
use SearchesCrmEntities;
private const int NOTE_BODY_MAX_LENGTH = 3000000;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const array STANDARD_OPPORTUNITY_FIELDS = [
'monetary_value' => [
'label' => 'Value',
'available_on' => Field::OBJECT_OPPORTUNITY,
'type' => Field::TYPE_CURRENCY,
],
'pipeline_stage_id' => [
'label' => 'Stage',
'type' => Field::TYPE_PICKLIST,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
'close_date' => [
'label' => 'Close date',
'type' => Field::TYPE_DATE,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
'win_probability' => [
'label' => 'Win probability',
'type' => Field::TYPE_NUMBER,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
];
private const string UNSUPPORTED_OBJECT_TYPE = 'unsupported';
private const string OPPORTUNITY_STATUS_OPEN = 'Open';
private const string OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE = 'Opportunity import failed';
private const string RESOURCE_UPDATE_FAILED_ERROR_MESSAGE = 'Failed to update resource';
private FieldValueConverter $fieldValueConverter;
private ClientFactory $clientFactory;
private ?Client $copperClient = null;
public function __construct(
ClientFactory $clientFactory,
FieldValueConverter $fieldValueConverter,
private readonly UserRepository $userRepository,
private readonly ProspectPhotoPathService $prospectPhotoPathService,
private readonly CrmEntityRepository $crmEntityRepository
) {
parent::__construct();
$this->clientFactory = $clientFactory;
$this->fieldValueConverter = $fieldValueConverter;
}
public function getDisplayName(): string
{
return 'Copper';
}
/**
* Get the CRM entity repository (used by SearchesCrmEntities trait)
*/
protected function getCrmEntityRepository(): CrmEntityRepository
{
return $this->crmEntityRepository;
}
public function getMinimumApiVersion(): string
{
return Client::MIN_API_VERSION;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_COPPER);
}
public function setUser(User $user): void
{
$this->configureSentryScope($user);
$this->team = $user->getTeam();
$this->teamService->setTeam($user->getTeam());
$this->setConfiguration($user->getTeam()->getCrmConfiguration());
// Reset state.
$this->profile = $user->getProfile();
if (! $this->profile instanceof Profile) {
// Try to fetch their profile, maybe it was not yet imported?
$this->profile = $this->getProfile($user);
}
}
public function setConfiguration(Configuration $configuration): void
{
$this->config = $configuration;
$this->copperClient = $this->clientFactory->create($configuration);
if ($this->team === null) {
$this->team = $configuration->getTeam();
}
}
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return $this->fieldValueConverter->convertFromCrm($fieldType, $fieldValue);
}
private function mapObjectType(string $objectType): string
{
$objectType = strtolower($objectType);
switch ($objectType) {
case Field::OBJECT_TASK:
case Field::OBJECT_OPPORTUNITY:
case Field::OBJECT_LEAD:
$mappedType = $objectType;
break;
case Field::OBJECT_ACCOUNT:
$mappedType = 'company';
break;
case Field::OBJECT_CONTACT:
$mappedType = 'person';
break;
default:
$mappedType = self::UNSUPPORTED_OBJECT_TYPE;
break;
}
return $mappedType;
}
/**
* @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact
*/
protected function getFields(string $crmObject): array
{
$mappedObjectType = $this->mapObjectType($crmObject);
if (! $this->isSupportedObjectType($mappedObjectType)) {
return [];
}
$customFields = $this->copperClient->fields()->all();
$filteredFields = array_filter(
$customFields,
static fn ($field) => in_array($mappedObjectType, $field['available_on'], true)
);
return array_map(
fn (array $property) => [
'name' => $property['id'],
'label' => $property['name'],
'type' => $this->convertFieldType($property['data_type']),
],
$filteredFields
);
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {
$defaultFields = FieldDefinitions::defaultTaskFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldFilters = FieldDefinitions::taskFollowupFieldsFilter();
foreach ($fieldFilters as $data) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
public function syncFields(): void
{
$this->syncStandardFields();
$this->syncCustomFields();
}
public function syncField(Field $field): void
{
if ($field->getCrmProviderId() === 'type') {
/**
* This field is a special case, it is not a custom field and is not returned by the Copper API.
*
* The field is created manually during layout setup.
*
* @see getDefaultFields()
*
* There is a separate endpoint to get the activity types.
* @see importPicklistValues()
*/
return;
}
if ($field->getCrmProviderId() === 'pipeline_stage_id') {
// Not a custom type
return;
}
$crmField = $this->copperClient->fields()->find($field->getCrmProviderId());
$field->label = $crmField['name'];
$field->type = $this->convertFieldType($crmField['data_type']);
$field->save();
}
/**
* @param string $fieldType How the data should be input
*/
private function convertFieldType(string $fieldType): string
{
$fieldType = strtolower($fieldType);
switch ($fieldType) {
case 'dropdown':
$convertedType = Field::TYPE_PICKLIST;
break;
case 'string':
$convertedType = Field::TYPE_TEXT;
break;
case 'float':
case 'percentage':
$convertedType = Field::TYPE_NUMBER;
break;
case 'text':
$convertedType = Field::TYPE_TEXTAREA;
break;
case 'checkbox':
$convertedType = Field::TYPE_BOOLEAN;
break;
case Field::TYPE_DATE:
case Field::TYPE_CURRENCY:
case Field::TYPE_URL:
$convertedType = $fieldType;
break;
default:
$convertedType = Field::TYPE_UNSUPPORTED;
break;
}
return $convertedType;
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$fieldValues = [];
if ($field->object_type === 'opportunity' && $field->crm_provider_id === 'pipeline_stage_id') {
return $this->importFieldValuesForDealInsights($field);
}
$values = [];
if ($field->object_type === Field::OBJECT_TASK && $field->crm_provider_id === 'type') {
$activityTypes = $this->copperClient->activityTypes()->all();
/**
* We ignore "system" activity types, disabled activity types and the "Note" activity type.
*/
$activityTypes = array_filter(
$activityTypes['user'],
fn (array $activityType) => ! $activityType['is_disabled'] && $activityType['id'] !== 0
);
// Import all activity values.
$i = 0;
foreach ($activityTypes as $activityType) {
$values[] = [
'value' => $activityType['id'],
'label' => mb_strimwidth($activityType['name'], 0, Field::LABEL_MAX_LENGTH),
'sequence' => $i++,
];
}
} else {
// We just check for the field in the custom definitions.
$crmField = $this->copperClient->fields()->find($field->crm_provider_id);
// Import all values.
foreach ($crmField['options'] as $option) {
$values[] = [
'value' => $option['id'],
'label' => mb_strimwidth($option['name'], 0, 191),
'sequence' => $option['rank'],
];
}
}
// Take the existing set of field values.
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
// For all current values, upsert the field.
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
$key = array_search($value['value'], $fieldsToPurge, false);
if ($key !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
return $fieldValues;
}
/**
*
* @return FieldValue[]
*/
private function importFieldValuesForDealInsights(Field $field): array
{
$fieldValues = [];
$pipelines = $this->copperClient->pipelines()->all();
foreach ($pipelines as $pipeline) {
foreach ($pipeline['stages'] as $i => $dealStage) {
$fieldValues[] = $field->values()->updateOrCreate(
['value' => $dealStage['id']],
[
'label' => $dealStage['name'],
'sequence' => $i,
]
);
}
}
return $fieldValues;
}
/**
* @inheritdoc
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
$missingStage = null;
foreach ($types as $type) {
if ($type === Stage::TYPE_LEAD) {
$statuses = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leadStatuses()->all()
);
if (count($statuses) > 0) {
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => BusinessProcess::TYPE_LEAD,
], [
'team_id' => $this->team->id,
'name' => BusinessProcess::TYPE_LEAD,
'type' => BusinessProcess::TYPE_LEAD,
'is_selectable' => true,
]);
// A record type is really a clone of the business process, used to store which record uses which pipeline.
$this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => BusinessProcess::TYPE_LEAD,
], [
'team_id' => $this->team->id,
'name' => BusinessProcess::TYPE_LEAD,
'is_selectable' => true,
'business_process_id' => $businessProcess->id ?? null,
]);
$leadStatuses = [];
foreach ($statuses as $status) {
// Upsert all statuses for the team.
$status = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $status['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($status['name'], 0, 50),
'label' => mb_strimwidth($status['name'], 0, 191),
'type' => Stage::TYPE_LEAD,
'sequence' => $status['order'],
'is_selectable' => true,
]);
if ($missingStageName && $missingStageName === $status['id']) {
$missingStage = $status;
}
$leadStatuses[] = $status['id'];
}
$businessProcess->stages()->sync($leadStatuses);
}
} else {
// We create a business process to contain the pipeline, and later store all stages against it.
foreach ($this->copperClient->pipelines()->all() as $pipeline) {
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => $pipeline['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($pipeline['name'], 0, 150),
'type' => BusinessProcess::TYPE_OPPORTUNITY,
'is_selectable' => true,
]);
// A record type is really a clone of the business process, used to store which record uses which pipeline.
$this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => $pipeline['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($pipeline['name'], 0, 150),
'is_selectable' => true,
'business_process_id' => $businessProcess->id ?? null,
]);
$stages = [];
foreach ($pipeline['stages'] as $i => $dealStage) {
// Upsert all stages for the team.
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $dealStage['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($dealStage['name'], 0, 50),
'label' => mb_strimwidth($dealStage['name'], 0, 191),
'type' => Stage::TYPE_OPPORTUNITY,
'sequence' => $i,
'is_selectable' => true,
'probability' => $dealStage['win_probability'],
]);
if ($missingStageName && $missingStageName === $dealStage['id']) {
$missingStage = $stage;
}
$stages[] = $stage['id'];
}
$businessProcess->stages()->sync($stages);
}
}
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$cpLeads = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->paginate([
'minimum_modified_date' => $since->timestamp,
'sort_by' => 'date_modified',
])
);
foreach ($cpLeads as $cpLead) {
// Only sync if previously imported.
if ($this->hasLead($cpLead['id']) === false) {
$this->importLead($cpLead);
$syncCount++;
}
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
$cpLead = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->find($crmId)
);
if (\count($cpLead) === 0) {
return null;
}
return $this->importLead($cpLead);
}
/**
* @inheritdoc
*/
private function importLead($crmData): ?Lead
{
$countryCode = null;
if (! empty($crmData['address']) && isset($crmData['address']['country'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$mobilePhone = $parsedNumber = null;
if (! empty($crmData['phone_numbers'])) {
foreach ($crmData['phone_numbers'] as $phoneNumber) {
if ($phoneNumber['category'] === 'mobile') {
$mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);
} else {
$parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);
}
}
}
$name = $crmData['name'];
if (empty($crmData['company_name'])) {
$company = 'Unknown';
} else {
$company = mb_strimwidth($crmData['company_name'], 0, 191);
}
$domain = null;
if (empty($crmData['websites']) === false) {
$domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$email = null;
if (empty($crmData['email']) === false) {
$email = mb_strimwidth($crmData['email']['email'], 0, 80);
}
$stage = $this->config
->stages()
->where('crm_provider_id', (string) $crmData['status_id'])
->where('type', Stage::TYPE_LEAD)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status_id']);
}
if (! $stage instanceof Stage) {
return null;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($name, 0, 191),
'company' => $company,
'domain' => $domain,
'title' => $crmData['title'] ? mb_strimwidth($crmData['title'], 0, 128) : null,
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'mobile_phone' => $mobilePhone,
'stage_id' => $stage->id,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Lead::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'country_code' => $countryCode,
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$cpAccounts = $this->copperClient->accounts()->paginate([
'minimum_modified_date' => $since->timestamp,
'sort_by' => 'date_modified',
]);
foreach ($cpAccounts as $cpAccount) {
// Only sync if previously imported.
if ($this->hasAccount($cpAccount['id'])) {
$this->importAccount($cpAccount);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
$cpAccount = $this->copperClient->accounts()->find($crmId);
if (empty($cpAccount)) {
return null;
}
return $this->importAccount($cpAccount);
}
/**
* @inheritdoc
*/
private function importAccount($crmData): Account
{
$countryCode = null;
if (empty($crmData['address']) === false && $crmData['address']['country']) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$name = $crmData['name'];
$parsedNumber = null;
foreach ($crmData['phone_numbers'] as $phoneNumber) {
$parsedNumber = parsePhoneNumber($countryCode, $phoneNumber['number']);
}
$domain = null;
if (empty($crmData['websites']) === false) {
$domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Account::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'country_code' => $countryCode,
'domain' => $domain,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->copperClient,
]);
$strategies = $strategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
try {
foreach ($strategies as $syncStrategy) {
foreach ($syncStrategy->fetchOpportunities($parameters) as $opportunityData) {
$this->importOpportunity($opportunityData);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
$this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => $exception->getMessage(),
]);
}
return $syncCount;
}
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->copperClient,
]);
$strategy = $strategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
$parameters['crm_id'] = $crmId;
$cpOpportunity = $strategy->fetchOpportunities($parameters);
return $this->importOpportunity($cpOpportunity);
}
private function importOpportunity($crmData): ?Opportunity
{
$companyId = (string) $crmData['company_id'];
if (empty($companyId)) {
$this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => 'No company id',
]);
return null;
}
$account = $this->config->accounts()->where('crm_provider_id', $companyId)->first();
if ($account === null) {
$account = $this->syncAccount($companyId);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', (string) $crmData['pipeline_id'])
->first();
if ($businessProcess === null) {
// It is possible for some deals to not be in a pipeline.
$this->logger->warning(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => 'Missing pipeline',
]);
return null;
}
$stage = $businessProcess
->stages()
->where('crm_provider_id', (string) $crmData['pipeline_stage_id'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
$this->logger->info('Stage not found, importing', [
'pipeline_id' => $crmData['pipeline_id'],
'stage_id' => $crmData['pipeline_stage_id'],
]);
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['pipeline_stage_id']);
}
$recordType = $businessProcess->recordTypes()->first();
$closeDate = null;
$isClosed = $crmData['status'] !== self::OPPORTUNITY_STATUS_OPEN;
if ($crmData['close_date']) {
$closeDate = Carbon::parse($crmData['close_date'])->format('Y-m-d');
}
$data = [
'team_id' => $this->team->getId(),
'account_id' => $account->id,
'user_id' => $profile->user_id ?? null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($crmData['name'], 0, 128),
'value' => $crmData['monetary_value'],
'currency_code' => CurrencyFormatter::formatCode($crmData['monetary_unit']),
'close_date' => $closeDate,
'is_closed' => $isClosed,
'is_won' => $crmData['status'] === 'Won',
'stage_id' => $stage->id,
'record_type_id' => $recordType->id ?? null,
'remotely_created_at' => $crmData['date_created'],
];
/** @var Opportunity $opportunity */
$opportunity = $this->config
->opportunities()
->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data)
;
// import external fields into crm_field_data if present
$dealInsightsFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData($crmData, $dealInsightsFields, $opportunity->id);
return $opportunity;
}
/**
* @param array<string, mixed> $opportunityData
* @param string[] $dealInsightsFields
*/
public function importOpportunityCrmFieldData(
array $opportunityData,
array $dealInsightsFields,
int $opportunityId
): void {
foreach ($dealInsightsFields as $fieldName) {
$field = $this->config->fields()->with('entities')
->where('crm_provider_id', $fieldName)
->where('object_type', Field::OBJECT_OPPORTUNITY)
->first();
if (! $field instanceof Field) {
$this->logger->warning('Field not found', [
'field' => $fieldName,
'opportunity_id' => $opportunityId,
]);
continue;
}
$entity = $field->getEntities()->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$fieldValue = $this->extractFieldValue($opportunityData, $fieldName);
$normalizedValue = $this->normalizeValue($field->getType(), (string) $fieldValue, true);
$field->data()
->updateOrCreate([
'crm_layout_entity_id' => $entity->id,
'crm_field_id' => $field->id,
'object_type' => 'opportunity',
'object_id' => $opportunityId,
], ['value' => $normalizedValue])
;
}
}
/**
* @inheritdoc
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$cpContacts = $this->copperClient->contacts()->paginate([
'minimum_interaction_date' => $since->timestamp,
'sort_by' => 'date_modified',
]);
foreach ($cpContacts as $cpContact) {
// Only sync if previously imported.
if ($this->hasContact($cpContact['id'])) {
$this->importContact($cpContact);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
throw $exception;
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncContact(string $crmId): ?Contact
{
$cpContact = $this->copperClient->contacts()->find($crmId);
if (empty($cpContact)) {
return null;
}
return $this->importContact($cpContact);
}
/**
* @inheritdoc
*/
private function importContact($crmData): Contact
{
$account = null;
if ($crmData['company_id']) {
$account = $this->team
->crm
->accounts()
->where('crm_provider_id', (string) $crmData['company_id'])
->first();
if ($account === null) {
$account = $this->syncAccount($crmData['company_id']);
}
}
$countryCode = null;
if (empty($crmData['address']) === false && $crmData['address']['country']) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$mobilePhone = $parsedNumber = null;
foreach ($crmData['phone_numbers'] as $phoneNumber) {
if ($phoneNumber['category'] === 'mobile') {
$mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);
} else {
$parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);
}
}
$email = null;
if (empty($crmData['emails']) === false) {
$email = mb_strimwidth($crmData['emails'][0]['email'], 0, 80);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => $crmData['name'],
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'mobile_phone' => $mobilePhone ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'title' => $crmData['title'],
'country_code' => $countryCode,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Contact::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function buildContactPhone(?string $countryCode, ?string $number): ?array
{
if ($number) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($number, 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
return $parsedNumber;
}
private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string
{
return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;
}
/**
* @inheritdoc
*/
public function syncOrganization(): void
{
$organization = $this->copperClient->organisation()->all();
if ($this->config->crm_provider_id !== $organization['id']) {
$this->config->update(['crm_provider_id' => $organization['id']]);
}
}
private function syncCustomFields(): void
{
foreach ($this->getFieldTypes() as $fieldType) {
$currentFields = $this->getFields($fieldType);
foreach ($currentFields as $field) {
/** @var Field $field */
$field = $this->config->fields()->updateOrCreate([
'crm_provider_id' => $field['name'],
'object_type' => $fieldType,
], [
'label' => mb_strimwidth($field['label'], 0, Field::LABEL_MAX_LENGTH),
'type' => $field['type'],
]);
if ($field->getType() === Field::TYPE_PICKLIST) {
$this->importPicklistValues($field);
}
}
}
$this->config->save();
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
parent::OBJECT_LEAD,
parent::OBJECT_ACCOUNT,
parent::OBJECT_CONTACT,
parent::OBJECT_OPPORTUNITY,
];
}
/**
* @inheritdoc
*/
public function syncProfiles(?User $userToSearch = null): ?Profile
{
$profiles = $this->copperClient->users()->all();
foreach ($profiles as $profile) {
$user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);
// Only import profiles for users we have locally.
if ($user) {
$profile = $user->crmProfile()->updateOrCreate([
'crm_configuration_id' => $this->config->id,
'crm_provider_id' => $profile['id'],
]);
if ($userToSearch && $userToSearch->id === $user->id) {
return $profile;
}
}
}
return null;
}
/**
* @inheritdoc
*/
public function syncProfileFields(): void
{
$fieldTypes = [
'task',
'lead',
'account',
'contact',
'opportunity',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields(ucfirst($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))
);
if (\count($changedFields) > 0) {
$fields = implode(',', $newFields);
$this->logger->debug(
ucfirst($fieldType)
. ' fields changed from '
. $this->profile->{$fieldType . '_fields'}
. ' to: '
. $fields
);
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (\Exception $exception) {
$this->logger->error('No access to ' . $fieldType . ' object, skipping...');
continue;
}
}
$this->profile->save();
}
/**
* @inheritdoc
*/
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$scopeValues = array_map(fn ($scope) => is_string($scope) ? $scope : $scope->value, $scopes);
$cacheKey = sprintf('copper-search-%d-%s-%s-%d-%d', $this->team->id, $name, implode('-', $scopeValues), $count, $offset);
return Cache::remember($cacheKey, 300, function () use ($name, $scopes, $count, $offset) {
// Try local search first
$localResults = $this->searchLocally($name, $scopes, $count, $offset);
// If no local results, fall back to remote API search
if (empty($localResults)) {
return $this->searchRemotely($name, $scopes, $count, $offset);
}
return $localResults;
});
}
/**
* @inheritdoc
*/
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$params = [
'company_ids' => [$account->crm_provider_id],
'status_ids' => [0], // The integer values are 0, 1, 2, 3, for "Open", "Won", "Lost", and "Abandoned".
'sort_by' => 'date_modified',
'sort_direction' => 'desc',
];
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort_by'] = 'date_modified';
$params['sort_direction'] = 'desc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort_by'] = 'date_created';
$params['sort_direction'] = 'desc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort_by'] = 'date_created';
$params['sort_direction'] = 'asc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort_by'] = 'date_modified';
$params['sort_direction'] = 'desc';
$params['status_ids'] = [0, 1, 2, 3];
}
$cpOpportunities = $this->copperClient->opportunities()->search($params);
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
foreach ($cpOpportunities as $cpOpportunity) {
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', (string) $cpOpportunity['pipeline_id'])
->first();
if ($businessProcess === null) {
// Import it.
$businessProcess = $this->importStages(
[Stage::TYPE_OPPORTUNITY],
$cpOpportunity['pipeline_stage_id']
);
}
$stage = $businessProcess
->stages()
->where('crm_provider_id', (string) $cpOpportunity['pipeline_stage_id'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $cpOpportunity['pipeline_stage_id']);
}
$recordType = $businessProcess->recordTypes()->first();
$record = [
'crmId' => $cpOpportunity['id'],
'name' => $cpOpportunity['name'],
'value' => currency_format($cpOpportunity['monetary_value'], $cpOpportunity['monetary_unit']),
'won' => $cpOpportunity['status'] === 'Won',
'stage' => [
'id' => $stage->id_string,
'name' => $stage->name,
],
'recordType' => [
'id' => $recordType->id_string,
'name' => $recordType->name,
],
];
if ($ownerId && isset($cpOpportunity['assignee_id']) && $cpOpportunity['assignee_id'] === $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
/**
* @inheritdoc
*/
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = $cpTasks = [];
switch ($objectType) {
case 'lead':
$cpTasks = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->relatedTasks($objectId)
);
break;
case 'account':
$cpTasks = $this->copperClient->accounts()->relatedTasks($objectId);
break;
case 'contact':
if ($opportunityId) {
$cpTasks = $this->copperClient->opportunities()->relatedTasks($opportunityId);
} elseif ($objectType === 'contact') {
$cpTasks = $this->copperClient->contacts()->relatedTasks($objectId);
}
break;
}
foreach ($cpTasks as $cpTask) {
// We only get the ID itself returned, so pull out the full object.
try {
$cpTask = $this->copperClient->tasks()->find($cpTask['id']);
} catch (Exception $exception) {
$this->logger->error('[Copper] Error fetching task', [
'resource_id' => $cpTask['id'],
'error' => $exception->getMessage(),
]);
continue;
}
// Only allow open tasks.
if ($cpTask['status'] === 'Open') {
$data[] = [
'crmId' => $cpTask['id'],
'subject' => $cpTask['name'],
'due' => $cpTask['due_date']
? Carbon::createFromTimestamp($cpTask['due_date'])->format('Y-m-d\TH:i:sO')
: null,
'type' => null,
];
}
}
return $data;
}
/**
* Try to find email address in CRM service
*
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchExactlyByEmail(string $email, ?int $userId = null): ?array
{
$cpObjectType = 'contact';
$cpObjects = $this->copperClient->contacts()->search([
'emails' => $email,
'sort_by' => 'date_modified',
'sort_direction' => 'desc',
]);
if (empty($cpObjects)) {
$cpObjectType = 'lead';
$cpObjects = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->search([
'emails' => ...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45375
|
1625
|
25
|
2026-05-14T14:33:24.529049+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769204529_m1.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
11
72
1
4
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Copper;
use Carbon\Carbon;
use Exception;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Facades\Cache;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\CopperInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\FieldValue;
use Jiminny\Models\Crm\LayoutEntity;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\PlaybookCategory;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\UserRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\Copper\Api\Client;
use Jiminny\Services\Crm\Copper\Api\ClientFactory;
use Jiminny\Services\Crm\Copper\Exception\RequestFailedException;
use Jiminny\Services\Crm\Helpers\FilterJoinedParticipants;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Services\Crm\Copper\Traits\SearchesCrmEntities;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
class Service extends BaseService implements
CopperInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
use SearchesCrmEntities;
private const int NOTE_BODY_MAX_LENGTH = 3000000;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const array STANDARD_OPPORTUNITY_FIELDS = [
'monetary_value' => [
'label' => 'Value',
'available_on' => Field::OBJECT_OPPORTUNITY,
'type' => Field::TYPE_CURRENCY,
],
'pipeline_stage_id' => [
'label' => 'Stage',
'type' => Field::TYPE_PICKLIST,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
'close_date' => [
'label' => 'Close date',
'type' => Field::TYPE_DATE,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
'win_probability' => [
'label' => 'Win probability',
'type' => Field::TYPE_NUMBER,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
];
private const string UNSUPPORTED_OBJECT_TYPE = 'unsupported';
private const string OPPORTUNITY_STATUS_OPEN = 'Open';
private const string OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE = 'Opportunity import failed';
private const string RESOURCE_UPDATE_FAILED_ERROR_MESSAGE = 'Failed to update resource';
private FieldValueConverter $fieldValueConverter;
private ClientFactory $clientFactory;
private ?Client $copperClient = null;
public function __construct(
ClientFactory $clientFactory,
FieldValueConverter $fieldValueConverter,
private readonly UserRepository $userRepository,
private readonly ProspectPhotoPathService $prospectPhotoPathService,
private readonly CrmEntityRepository $crmEntityRepository
) {
parent::__construct();
$this->clientFactory = $clientFactory;
$this->fieldValueConverter = $fieldValueConverter;
}
public function getDisplayName(): string
{
return 'Copper';
}
/**
* Get the CRM entity repository (used by SearchesCrmEntities trait)
*/
protected function getCrmEntityRepository(): CrmEntityRepository
{
return $this->crmEntityRepository;
}
public function getMinimumApiVersion(): string
{
return Client::MIN_API_VERSION;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_COPPER);
}
public function setUser(User $user): void
{
$this->configureSentryScope($user);
$this->team = $user->getTeam();
$this->teamService->setTeam($user->getTeam());
$this->setConfiguration($user->getTeam()->getCrmConfiguration());
// Reset state.
$this->profile = $user->getProfile();
if (! $this->profile instanceof Profile) {
// Try to fetch their profile, maybe it was not yet imported?
$this->profile = $this->getProfile($user);
}
}
public function setConfiguration(Configuration $configuration): void
{
$this->config = $configuration;
$this->copperClient = $this->clientFactory->create($configuration);
if ($this->team === null) {
$this->team = $configuration->getTeam();
}
}
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return $this->fieldValueConverter->convertFromCrm($fieldType, $fieldValue);
}
private function mapObjectType(string $objectType): string
{
$objectType = strtolower($objectType);
switch ($objectType) {
case Field::OBJECT_TASK:
case Field::OBJECT_OPPORTUNITY:
case Field::OBJECT_LEAD:
$mappedType = $objectType;
break;
case Field::OBJECT_ACCOUNT:
$mappedType = 'company';
break;
case Field::OBJECT_CONTACT:
$mappedType = 'person';
break;
default:
$mappedType = self::UNSUPPORTED_OBJECT_TYPE;
break;
}
return $mappedType;
}
/**
* @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact
*/
protected function getFields(string $crmObject): array
{
$mappedObjectType = $this->mapObjectType($crmObject);
if (! $this->isSupportedObjectType($mappedObjectType)) {
return [];
}
$customFields = $this->copperClient->fields()->all();
$filteredFields = array_filter(
$customFields,
static fn ($field) => in_array($mappedObjectType, $field['available_on'], true)
);
return array_map(
fn (array $property) => [
'name' => $property['id'],
'label' => $property['name'],
'type' => $this->convertFieldType($property['data_type']),
],
$filteredFields
);
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {
$defaultFields = FieldDefinitions::defaultTaskFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldFilters = FieldDefinitions::taskFollowupFieldsFilter();
foreach ($fieldFilters as $data) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
public function syncFields(): void
{
$this->syncStandardFields();
$this->syncCustomFields();
}
public function syncField(Field $field): void
{
if ($field->getCrmProviderId() === 'type') {
/**
* This field is a special case, it is not a custom field and is not returned by the Copper API.
*
* The field is created manually during layout setup.
*
* @see getDefaultFields()
*
* There is a separate endpoint to get the activity types.
* @see importPicklistValues()
*/
return;
}
if ($field->getCrmProviderId() === 'pipeline_stage_id') {
// Not a custom type
return;
}
$crmField = $this->copperClient->fields()->find($field->getCrmProviderId());
$field->label = $crmField['name'];
$field->type = $this->convertFieldType($crmField['data_type']);
$field->save();
}
/**
* @param string $fieldType How the data should be input
*/
private function convertFieldType(string $fieldType): string
{
$fieldType = strtolower($fieldType);
switch ($fieldType) {
case 'dropdown':
$convertedType = Field::TYPE_PICKLIST;
break;
case 'string':
$convertedType = Field::TYPE_TEXT;
break;
case 'float':
case 'percentage':
$convertedType = Field::TYPE_NUMBER;
break;
case 'text':
$convertedType = Field::TYPE_TEXTAREA;
break;
case 'checkbox':
$convertedType = Field::TYPE_BOOLEAN;
break;
case Field::TYPE_DATE:
case Field::TYPE_CURRENCY:
case Field::TYPE_URL:
$convertedType = $fieldType;
break;
default:
$convertedType = Field::TYPE_UNSUPPORTED;
break;
}
return $convertedType;
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$fieldValues = [];
if ($field->object_type === 'opportunity' && $field->crm_provider_id === 'pipeline_stage_id') {
return $this->importFieldValuesForDealInsights($field);
}
$values = [];
if ($field->object_type === Field::OBJECT_TASK && $field->crm_provider_id === 'type') {
$activityTypes = $this->copperClient->activityTypes()->all();
/**
* We ignore "system" activity types, disabled activity types and the "Note" activity type.
*/
$activityTypes = array_filter(
$activityTypes['user'],
fn (array $activityType) => ! $activityType['is_disabled'] && $activityType['id'] !== 0
);
// Import all activity values.
$i = 0;
foreach ($activityTypes as $activityType) {
$values[] = [
'value' => $activityType['id'],
'label' => mb_strimwidth($activityType['name'], 0, Field::LABEL_MAX_LENGTH),
'sequence' => $i++,
];
}
} else {
// We just check for the field in the custom definitions.
$crmField = $this->copperClient->fields()->find($field->crm_provider_id);
// Import all values.
foreach ($crmField['options'] as $option) {
$values[] = [
'value' => $option['id'],
'label' => mb_strimwidth($option['name'], 0, 191),
'sequence' => $option['rank'],
];
}
}
// Take the existing set of field values.
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
// For all current values, upsert the field.
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
$key = array_search($value['value'], $fieldsToPurge, false);
if ($key !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
return $fieldValues;
}
/**
*
* @return FieldValue[]
*/
private function importFieldValuesForDealInsights(Field $field): array
{
$fieldValues = [];
$pipelines = $this->copperClient->pipelines()->all();
foreach ($pipelines as $pipeline) {
foreach ($pipeline['stages'] as $i => $dealStage) {
$fieldValues[] = $field->values()->updateOrCreate(
['value' => $dealStage['id']],
[
'label' => $dealStage['name'],
'sequence' => $i,
]
);
}
}
return $fieldValues;
}
/**
* @inheritdoc
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
$missingStage = null;
foreach ($types as $type) {
if ($type === Stage::TYPE_LEAD) {
$statuses = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leadStatuses()->all()
);
if (count($statuses) > 0) {
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => BusinessProcess::TYPE_LEAD,
], [
'team_id' => $this->team->id,
'name' => BusinessProcess::TYPE_LEAD,
'type' => BusinessProcess::TYPE_LEAD,
'is_selectable' => true,
]);
// A record type is really a clone of the business process, used to store which record uses which pipeline.
$this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => BusinessProcess::TYPE_LEAD,
], [
'team_id' => $this->team->id,
'name' => BusinessProcess::TYPE_LEAD,
'is_selectable' => true,
'business_process_id' => $businessProcess->id ?? null,
]);
$leadStatuses = [];
foreach ($statuses as $status) {
// Upsert all statuses for the team.
$status = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $status['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($status['name'], 0, 50),
'label' => mb_strimwidth($status['name'], 0, 191),
'type' => Stage::TYPE_LEAD,
'sequence' => $status['order'],
'is_selectable' => true,
]);
if ($missingStageName && $missingStageName === $status['id']) {
$missingStage = $status;
}
$leadStatuses[] = $status['id'];
}
$businessProcess->stages()->sync($leadStatuses);
}
} else {
// We create a business process to contain the pipeline, and later store all stages against it.
foreach ($this->copperClient->pipelines()->all() as $pipeline) {
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => $pipeline['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($pipeline['name'], 0, 150),
'type' => BusinessProcess::TYPE_OPPORTUNITY,
'is_selectable' => true,
]);
// A record type is really a clone of the business process, used to store which record uses which pipeline.
$this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => $pipeline['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($pipeline['name'], 0, 150),
'is_selectable' => true,
'business_process_id' => $businessProcess->id ?? null,
]);
$stages = [];
foreach ($pipeline['stages'] as $i => $dealStage) {
// Upsert all stages for the team.
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $dealStage['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($dealStage['name'], 0, 50),
'label' => mb_strimwidth($dealStage['name'], 0, 191),
'type' => Stage::TYPE_OPPORTUNITY,
'sequence' => $i,
'is_selectable' => true,
'probability' => $dealStage['win_probability'],
]);
if ($missingStageName && $missingStageName === $dealStage['id']) {
$missingStage = $stage;
}
$stages[] = $stage['id'];
}
$businessProcess->stages()->sync($stages);
}
}
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$cpLeads = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->paginate([
'minimum_modified_date' => $since->timestamp,
'sort_by' => 'date_modified',
])
);
foreach ($cpLeads as $cpLead) {
// Only sync if previously imported.
if ($this->hasLead($cpLead['id']) === false) {
$this->importLead($cpLead);
$syncCount++;
}
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
$cpLead = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->find($crmId)
);
if (\count($cpLead) === 0) {
return null;
}
return $this->importLead($cpLead);
}
/**
* @inheritdoc
*/
private function importLead($crmData): ?Lead
{
$countryCode = null;
if (! empty($crmData['address']) && isset($crmData['address']['country'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$mobilePhone = $parsedNumber = null;
if (! empty($crmData['phone_numbers'])) {
foreach ($crmData['phone_numbers'] as $phoneNumber) {
if ($phoneNumber['category'] === 'mobile') {
$mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);
} else {
$parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);
}
}
}
$name = $crmData['name'];
if (empty($crmData['company_name'])) {
$company = 'Unknown';
} else {
$company = mb_strimwidth($crmData['company_name'], 0, 191);
}
$domain = null;
if (empty($crmData['websites']) === false) {
$domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$email = null;
if (empty($crmData['email']) === false) {
$email = mb_strimwidth($crmData['email']['email'], 0, 80);
}
$stage = $this->config
->stages()
->where('crm_provider_id', (string) $crmData['status_id'])
->where('type', Stage::TYPE_LEAD)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status_id']);
}
if (! $stage instanceof Stage) {
return null;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($name, 0, 191),
'company' => $company,
'domain' => $domain,
'title' => $crmData['title'] ? mb_strimwidth($crmData['title'], 0, 128) : null,
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'mobile_phone' => $mobilePhone,
'stage_id' => $stage->id,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Lead::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'country_code' => $countryCode,
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$cpAccounts = $this->copperClient->accounts()->paginate([
'minimum_modified_date' => $since->timestamp,
'sort_by' => 'date_modified',
]);
foreach ($cpAccounts as $cpAccount) {
// Only sync if previously imported.
if ($this->hasAccount($cpAccount['id'])) {
$this->importAccount($cpAccount);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
$cpAccount = $this->copperClient->accounts()->find($crmId);
if (empty($cpAccount)) {
return null;
}
return $this->importAccount($cpAccount);
}
/**
* @inheritdoc
*/
private function importAccount($crmData): Account
{
$countryCode = null;
if (empty($crmData['address']) === false && $crmData['address']['country']) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$name = $crmData['name'];
$parsedNumber = null;
foreach ($crmData['phone_numbers'] as $phoneNumber) {
$parsedNumber = parsePhoneNumber($countryCode, $phoneNumber['number']);
}
$domain = null;
if (empty($crmData['websites']) === false) {
$domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Account::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'country_code' => $countryCode,
'domain' => $domain,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->copperClient,
]);
$strategies = $strategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
try {
foreach ($strategies as $syncStrategy) {
foreach ($syncStrategy->fetchOpportunities($parameters) as $opportunityData) {
$this->importOpportunity($opportunityData);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
$this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => $exception->getMessage(),
]);
}
return $syncCount;
}
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->copperClient,
]);
$strategy = $strategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
$parameters['crm_id'] = $crmId;
$cpOpportunity = $strategy->fetchOpportunities($parameters);
return $this->importOpportunity($cpOpportunity);
}
private function importOpportunity($crmData): ?Opportunity
{
$companyId = (string) $crmData['company_id'];
if (empty($companyId)) {
$this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => 'No company id',
]);
return null;
}
$account = $this->config->accounts()->where('crm_provider_id', $companyId)->first();
if ($account === null) {
$account = $this->syncAccount($companyId);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', (string) $crmData['pipeline_id'])
->first();
if ($businessProcess === null) {
// It is possible for some deals to not be in a pipeline.
$this->logger->warning(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => 'Missing pipeline',
]);
return null;
}
$stage = $businessProcess
->stages()
->where('crm_provider_id', (string) $crmData['pipeline_stage_id'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
$this->logger->info('Stage not found, importing', [
'pipeline_id' => $crmData['pipeline_id'],
'stage_id' => $crmData['pipeline_stage_id'],
]);
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['pipeline_stage_id']);
}
$recordType = $businessProcess->recordTypes()->first();
$closeDate = null;
$isClosed = $crmData['status'] !== self::OPPORTUNITY_STATUS_OPEN;
if ($crmData['close_date']) {
$closeDate = Carbon::parse($crmData['close_date'])->format('Y-m-d');
}
$data = [
'team_id' => $this->team->getId(),
'account_id' => $account->id,
'user_id' => $profile->user_id ?? null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($crmData['name'], 0, 128),
'value' => $crmData['monetary_value'],
'currency_code' => CurrencyFormatter::formatCode($crmData['monetary_unit']),
'close_date' => $closeDate,
'is_closed' => $isClosed,
'is_won' => $crmData['status'] === 'Won',
'stage_id' => $stage->id,
'record_type_id' => $recordType->id ?? null,
'remotely_created_at' => $crmData['date_created'],
];
/** @var Opportunity $opportunity */
$opportunity = $this->config
->opportunities()
->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data)
;
// import external fields into crm_field_data if present
$dealInsightsFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData($crmData, $dealInsightsFields, $opportunity->id);
return $opportunity;
}
/**
* @param array<string, mixed> $opportunityData
* @param string[] $dealInsightsFields
*/
public function importOpportunityCrmFieldData(
array $opportunityData,
array $dealInsightsFields,
int $opportunityId
): void {
foreach ($dealInsightsFields as $fieldName) {
$field = $this->config->fields()->with('entities')
->where('crm_provider_id', $fieldName)
->where('object_type', Field::OBJECT_OPPORTUNITY)
->first();
if (! $field instanceof Field) {
$this->logger->warning('Field not found', [
'field' => $fieldName,
'opportunity_id' => $opportunityId,
]);
continue;
}
$entity = $field->getEntities()->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$fieldValue = $this->extractFieldValue($opportunityData, $fieldName);
$normalizedValue = $this->normalizeValue($field->getType(), (string) $fieldValue, true);
$field->data()
->updateOrCreate([
'crm_layout_entity_id' => $entity->id,
'crm_field_id' => $field->id,
'object_type' => 'opportunity',
'object_id' => $opportunityId,
], ['value' => $normalizedValue])
;
}
}
/**
* @inheritdoc
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$cpContacts = $this->copperClient->contacts()->paginate([
'minimum_interaction_date' => $since->timestamp,
'sort_by' => 'date_modified',
]);
foreach ($cpContacts as $cpContact) {
// Only sync if previously imported.
if ($this->hasContact($cpContact['id'])) {
$this->importContact($cpContact);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
throw $exception;
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncContact(string $crmId): ?Contact
{
$cpContact = $this->copperClient->contacts()->find($crmId);
if (empty($cpContact)) {
return null;
}
return $this->importContact($cpContact);
}
/**
* @inheritdoc
*/
private function importContact($crmData): Contact
{
$account = null;
if ($crmData['company_id']) {
$account = $this->team
->crm
->accounts()
->where('crm_provider_id', (string) $crmData['company_id'])
->first();
if ($account === null) {
$account = $this->syncAccount($crmData['company_id']);
}
}
$countryCode = null;
if (empty($crmData['address']) === false && $crmData['address']['country']) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$mobilePhone = $parsedNumber = null;
foreach ($crmData['phone_numbers'] as $phoneNumber) {
if ($phoneNumber['category'] === 'mobile') {
$mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);
} else {
$parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);
}
}
$email = null;
if (empty($crmData['emails']) === false) {
$email = mb_strimwidth($crmData['emails'][0]['email'], 0, 80);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => $crmData['name'],
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'mobile_phone' => $mobilePhone ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'title' => $crmData['title'],
'country_code' => $countryCode,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Contact::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function buildContactPhone(?string $countryCode, ?string $number): ?array
{
if ($number) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($number, 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
return $parsedNumber;
}
private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string
{
return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;
}
/**
* @inheritdoc
*/
public function syncOrganization(): void
{
$organization = $this->copperClient->organisation()->all();
if ($this->config->crm_provider_id !== $organization['id']) {
$this->config->update(['crm_provider_id' => $organization['id']]);
}
}
private function syncCustomFields(): void
{
foreach ($this->getFieldTypes() as $fieldType) {
$currentFields = $this->getFields($fieldType);
foreach ($currentFields as $field) {
/** @var Field $field */
$field = $this->config->fields()->updateOrCreate([
'crm_provider_id' => $field['name'],
'object_type' => $fieldType,
], [
'label' => mb_strimwidth($field['label'], 0, Field::LABEL_MAX_LENGTH),
'type' => $field['type'],
]);
if ($field->getType() === Field::TYPE_PICKLIST) {
$this->importPicklistValues($field);
}
}
}
$this->config->save();
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
parent::OBJECT_LEAD,
parent::OBJECT_ACCOUNT,
parent::OBJECT_CONTACT,
parent::OBJECT_OPPORTUNITY,
];
}
/**
* @inheritdoc
*/
public function syncProfiles(?User $userToSearch = null): ?Profile
{
$profiles = $this->copperClient->users()->all();
foreach ($profiles as $profile) {
$user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);
// Only import profiles for users we have locally.
if ($user) {
$profile = $user->crmProfile()->updateOrCreate([
'crm_configuration_id' => $this->config->id,
'crm_provider_id' => $profile['id'],
]);
if ($userToSearch && $userToSearch->id === $user->id) {
return $profile;
}
}
}
return null;
}
/**
* @inheritdoc
*/
public function syncProfileFields(): void
{
$fieldTypes = [
'task',
'lead',
'account',
'contact',
'opportunity',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields(ucfirst($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))
);
if (\count($changedFields) > 0) {
$fields = implode(',', $newFields);
$this->logger->debug(
ucfirst($fieldType)
. ' fields changed from '
. $this->profile->{$fieldType . '_fields'}
. ' to: '
. $fields
);
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (\Exception $exception) {
$this->logger->error('No access to ' . $fieldType . ' object, skipping...');
continue;
}
}
$this->profile->save();
}
/**
* @inheritdoc
*/
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$scopeValues = array_map(fn ($scope) => is_string($scope) ? $scope : $scope->value, $scopes);
$cacheKey = sprintf('copper-search-%d-%s-%s-%d-%d', $this->team->id, $name, implode('-', $scopeValues), $count, $offset);
return Cache::remember($cacheKey, 300, function () use ($name, $scopes, $count, $offset) {
// Try local search first
$localResults = $this->searchLocally($name, $scopes, $count, $offset);
// If no local results, fall back to remote API search
if (empty($localResults)) {
return $this->searchRemotely($name, $scopes, $count, $offset);
}
return $localResults;
});
}
/**
* @inheritdoc
*/
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$params = [
'company_ids' => [$account->crm_provider_id],
'status_ids' => [0], // The integer values are 0, 1, 2, 3, for "Open", "Won", "Lost", and "Abandoned".
'sort_by' => 'date_modified',
'sort_direction' => 'desc',
];
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort_by'] = 'date_modified';
$params['sort_direction'] = 'desc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort_by'] = 'date_created';
$params['sort_direction'] = 'desc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort_by'] = 'date_created';
$params['sort_direction'] = 'asc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort_by'] = 'date_modified';
$params['sort_direction'] = 'desc';
$params['status_ids'] = [0, 1, 2, 3];
}
$cpOpportunities = $this->copperClient->opportunities()->search($params);
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
foreach ($cpOpportunities as $cpOpportunity) {
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', (string) $cpOpportunity['pipeline_id'])
->first();
if ($businessProcess === null) {
// Import it.
$businessProcess = $this->importStages(
[Stage::TYPE_OPPORTUNITY],
$cpOpportunity['pipeline_stage_id']
);
}
$stage = $businessProcess
->stages()
->where('crm_provider_id', (string) $cpOpportunity['pipeline_stage_id'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $cpOpportunity['pipeline_stage_id']);
}
$recordType = $businessProcess->recordTypes()->first();
$record = [
'crmId' => $cpOpportunity['id'],
'name' => $cpOpportunity['name'],
'value' => currency_format($cpOpportunity['monetary_value'], $cpOpportunity['monetary_unit']),
'won' => $cpOpportunity['status'] === 'Won',
'stage' => [
'id' => $stage->id_string,
'name' => $stage->name,
],
'recordType' => [
'id' => $recordType->id_string,
'name' => $recordType->name,
],
];
if ($ownerId && isset($cpOpportunity['assignee_id']) && $cpOpportunity['assignee_id'] === $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
/**
* @inheritdoc
*/
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = $cpTasks = [];
switch ($objectType) {
case 'lead':
$cpTasks = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->relatedTasks($objectId)
);
break;
case 'account':
$cpTasks = $this->copperClient->accounts()->relatedTasks($objectId);
break;
case 'contact':
if ($opportunityId) {
$cpTasks = $this->copperClient->opportunities()->relatedTasks($opportunityId);
} elseif ($objectType === 'contact') {
$cpTasks = $this->copperClient->contacts()->relatedTasks($objectId);
}
break;
}
foreach ($cpTasks as $cpTask) {
// We only get the ID itself returned, so pull out the full object.
try {
$cpTask = $this->copperClient->tasks()->find($cpTask['id']);
} catch (Exception $exception) {
$this->logger->error('[Copper] Error fetching task', [
'resource_id' => $cpTask['id'],
'error' => $exception->getMessage(),
]);
continue;
}
// Only allow open tasks.
if ($cpTask['status'] === 'Open') {
$data[] = [
'crmId' => $cpTask['id'],
'subject' => $cpTask['name'],
'due' => $cpTask['due_date']
? Carbon::createFromTimestamp($cpTask['due_date'])->format('Y-m-d\TH:i:sO')
: null,
'type' => null,
];
}
}
return $data;
}
/**
* Try to find email address in CRM service
*
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchExactlyByEmail(string $email, ?int $userId = null): ?array
{
$cpObjectType = 'contact';
$cpObjects = $this->copperClient->contacts()->search([
'emails' => $email,
'sort_by' => 'date_modified',
'sort_direction' => 'desc',
]);
if (empty($cpObjects)) {
$cpObjectType = 'lead';
$cpObjects = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->search([
'emails' => ...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.6645833,"top":0.027777778,"width":0.15902779,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.82361114,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.8472222,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.87083334,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.9291667,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9527778,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9763889,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"11","depth":4,"bounds":{"left":0.7340278,"top":0.3122222,"width":0.01875,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"72","depth":4,"bounds":{"left":0.7569444,"top":0.3122222,"width":0.020833334,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.78194445,"top":0.3122222,"width":0.015277778,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"bounds":{"left":0.80138886,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.8215278,"top":0.31,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.8368056,"top":0.31,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Copper;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse GuzzleHttp\\Exception\\ClientException;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\CopperInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\FieldValue;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\PlaybookCategory;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\UserRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\Copper\\Api\\Client;\nuse Jiminny\\Services\\Crm\\Copper\\Api\\ClientFactory;\nuse Jiminny\\Services\\Crm\\Copper\\Exception\\RequestFailedException;\nuse Jiminny\\Services\\Crm\\Helpers\\FilterJoinedParticipants;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Services\\Crm\\Copper\\Traits\\SearchesCrmEntities;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\n\nclass Service extends BaseService implements\n CopperInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n use SearchesCrmEntities;\n private const int NOTE_BODY_MAX_LENGTH = 3000000;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const array STANDARD_OPPORTUNITY_FIELDS = [\n 'monetary_value' => [\n 'label' => 'Value',\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n 'type' => Field::TYPE_CURRENCY,\n ],\n 'pipeline_stage_id' => [\n 'label' => 'Stage',\n 'type' => Field::TYPE_PICKLIST,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n 'close_date' => [\n 'label' => 'Close date',\n 'type' => Field::TYPE_DATE,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n 'win_probability' => [\n 'label' => 'Win probability',\n 'type' => Field::TYPE_NUMBER,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n ];\n private const string UNSUPPORTED_OBJECT_TYPE = 'unsupported';\n private const string OPPORTUNITY_STATUS_OPEN = 'Open';\n private const string OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE = 'Opportunity import failed';\n private const string RESOURCE_UPDATE_FAILED_ERROR_MESSAGE = 'Failed to update resource';\n\n private FieldValueConverter $fieldValueConverter;\n private ClientFactory $clientFactory;\n private ?Client $copperClient = null;\n\n public function __construct(\n ClientFactory $clientFactory,\n FieldValueConverter $fieldValueConverter,\n private readonly UserRepository $userRepository,\n private readonly ProspectPhotoPathService $prospectPhotoPathService,\n private readonly CrmEntityRepository $crmEntityRepository\n ) {\n parent::__construct();\n\n $this->clientFactory = $clientFactory;\n $this->fieldValueConverter = $fieldValueConverter;\n }\n\n public function getDisplayName(): string\n {\n return 'Copper';\n }\n\n /**\n * Get the CRM entity repository (used by SearchesCrmEntities trait)\n */\n protected function getCrmEntityRepository(): CrmEntityRepository\n {\n return $this->crmEntityRepository;\n }\n\n public function getMinimumApiVersion(): string\n {\n return Client::MIN_API_VERSION;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_COPPER);\n }\n\n public function setUser(User $user): void\n {\n $this->configureSentryScope($user);\n\n $this->team = $user->getTeam();\n $this->teamService->setTeam($user->getTeam());\n $this->setConfiguration($user->getTeam()->getCrmConfiguration());\n\n // Reset state.\n $this->profile = $user->getProfile();\n\n if (! $this->profile instanceof Profile) {\n // Try to fetch their profile, maybe it was not yet imported?\n $this->profile = $this->getProfile($user);\n }\n }\n\n public function setConfiguration(Configuration $configuration): void\n {\n $this->config = $configuration;\n $this->copperClient = $this->clientFactory->create($configuration);\n\n if ($this->team === null) {\n $this->team = $configuration->getTeam();\n }\n }\n\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return $this->fieldValueConverter->convertFromCrm($fieldType, $fieldValue);\n }\n\n private function mapObjectType(string $objectType): string\n {\n $objectType = strtolower($objectType);\n\n switch ($objectType) {\n case Field::OBJECT_TASK:\n case Field::OBJECT_OPPORTUNITY:\n case Field::OBJECT_LEAD:\n $mappedType = $objectType;\n\n break;\n case Field::OBJECT_ACCOUNT:\n $mappedType = 'company';\n\n break;\n case Field::OBJECT_CONTACT:\n $mappedType = 'person';\n\n break;\n default:\n $mappedType = self::UNSUPPORTED_OBJECT_TYPE;\n\n break;\n }\n\n return $mappedType;\n }\n\n /**\n * @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact\n */\n protected function getFields(string $crmObject): array\n {\n $mappedObjectType = $this->mapObjectType($crmObject);\n\n if (! $this->isSupportedObjectType($mappedObjectType)) {\n return [];\n }\n\n $customFields = $this->copperClient->fields()->all();\n\n $filteredFields = array_filter(\n $customFields,\n static fn ($field) => in_array($mappedObjectType, $field['available_on'], true)\n );\n\n return array_map(\n fn (array $property) => [\n 'name' => $property['id'],\n 'label' => $property['name'],\n 'type' => $this->convertFieldType($property['data_type']),\n ],\n $filteredFields\n );\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {\n $defaultFields = FieldDefinitions::defaultTaskFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n $fieldFilters = FieldDefinitions::taskFollowupFieldsFilter();\n\n foreach ($fieldFilters as $data) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n public function syncFields(): void\n {\n $this->syncStandardFields();\n $this->syncCustomFields();\n }\n\n public function syncField(Field $field): void\n {\n if ($field->getCrmProviderId() === 'type') {\n /**\n * This field is a special case, it is not a custom field and is not returned by the Copper API.\n *\n * The field is created manually during layout setup.\n *\n * @see getDefaultFields()\n *\n * There is a separate endpoint to get the activity types.\n * @see importPicklistValues()\n */\n return;\n }\n\n if ($field->getCrmProviderId() === 'pipeline_stage_id') {\n // Not a custom type\n return;\n }\n\n $crmField = $this->copperClient->fields()->find($field->getCrmProviderId());\n $field->label = $crmField['name'];\n $field->type = $this->convertFieldType($crmField['data_type']);\n\n $field->save();\n }\n\n /**\n * @param string $fieldType How the data should be input\n */\n private function convertFieldType(string $fieldType): string\n {\n $fieldType = strtolower($fieldType);\n\n switch ($fieldType) {\n case 'dropdown':\n $convertedType = Field::TYPE_PICKLIST;\n\n break;\n case 'string':\n $convertedType = Field::TYPE_TEXT;\n\n break;\n case 'float':\n case 'percentage':\n $convertedType = Field::TYPE_NUMBER;\n\n break;\n case 'text':\n $convertedType = Field::TYPE_TEXTAREA;\n\n break;\n case 'checkbox':\n $convertedType = Field::TYPE_BOOLEAN;\n\n break;\n case Field::TYPE_DATE:\n case Field::TYPE_CURRENCY:\n case Field::TYPE_URL:\n $convertedType = $fieldType;\n\n break;\n default:\n $convertedType = Field::TYPE_UNSUPPORTED;\n\n break;\n }\n\n return $convertedType;\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $fieldValues = [];\n\n if ($field->object_type === 'opportunity' && $field->crm_provider_id === 'pipeline_stage_id') {\n return $this->importFieldValuesForDealInsights($field);\n }\n\n $values = [];\n\n if ($field->object_type === Field::OBJECT_TASK && $field->crm_provider_id === 'type') {\n $activityTypes = $this->copperClient->activityTypes()->all();\n\n /**\n * We ignore \"system\" activity types, disabled activity types and the \"Note\" activity type.\n */\n $activityTypes = array_filter(\n $activityTypes['user'],\n fn (array $activityType) => ! $activityType['is_disabled'] && $activityType['id'] !== 0\n );\n\n // Import all activity values.\n $i = 0;\n foreach ($activityTypes as $activityType) {\n $values[] = [\n 'value' => $activityType['id'],\n 'label' => mb_strimwidth($activityType['name'], 0, Field::LABEL_MAX_LENGTH),\n 'sequence' => $i++,\n ];\n }\n } else {\n // We just check for the field in the custom definitions.\n $crmField = $this->copperClient->fields()->find($field->crm_provider_id);\n\n // Import all values.\n foreach ($crmField['options'] as $option) {\n $values[] = [\n 'value' => $option['id'],\n 'label' => mb_strimwidth($option['name'], 0, 191),\n 'sequence' => $option['rank'],\n ];\n }\n }\n\n // Take the existing set of field values.\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n // For all current values, upsert the field.\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n $key = array_search($value['value'], $fieldsToPurge, false);\n if ($key !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n\n return $fieldValues;\n }\n\n /**\n *\n * @return FieldValue[]\n */\n private function importFieldValuesForDealInsights(Field $field): array\n {\n $fieldValues = [];\n $pipelines = $this->copperClient->pipelines()->all();\n\n foreach ($pipelines as $pipeline) {\n foreach ($pipeline['stages'] as $i => $dealStage) {\n $fieldValues[] = $field->values()->updateOrCreate(\n ['value' => $dealStage['id']],\n [\n 'label' => $dealStage['name'],\n 'sequence' => $i,\n ]\n );\n }\n }\n\n return $fieldValues;\n }\n\n /**\n * @inheritdoc\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n $missingStage = null;\n\n foreach ($types as $type) {\n if ($type === Stage::TYPE_LEAD) {\n $statuses = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leadStatuses()->all()\n );\n\n if (count($statuses) > 0) {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => BusinessProcess::TYPE_LEAD,\n ], [\n 'team_id' => $this->team->id,\n 'name' => BusinessProcess::TYPE_LEAD,\n 'type' => BusinessProcess::TYPE_LEAD,\n 'is_selectable' => true,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => BusinessProcess::TYPE_LEAD,\n ], [\n 'team_id' => $this->team->id,\n 'name' => BusinessProcess::TYPE_LEAD,\n 'is_selectable' => true,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $leadStatuses = [];\n foreach ($statuses as $status) {\n // Upsert all statuses for the team.\n $status = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $status['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($status['name'], 0, 50),\n 'label' => mb_strimwidth($status['name'], 0, 191),\n 'type' => Stage::TYPE_LEAD,\n 'sequence' => $status['order'],\n 'is_selectable' => true,\n ]);\n\n if ($missingStageName && $missingStageName === $status['id']) {\n $missingStage = $status;\n }\n\n $leadStatuses[] = $status['id'];\n }\n\n $businessProcess->stages()->sync($leadStatuses);\n }\n } else {\n // We create a business process to contain the pipeline, and later store all stages against it.\n foreach ($this->copperClient->pipelines()->all() as $pipeline) {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $pipeline['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline['name'], 0, 150),\n 'type' => BusinessProcess::TYPE_OPPORTUNITY,\n 'is_selectable' => true,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $pipeline['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline['name'], 0, 150),\n 'is_selectable' => true,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $stages = [];\n\n foreach ($pipeline['stages'] as $i => $dealStage) {\n // Upsert all stages for the team.\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $dealStage['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($dealStage['name'], 0, 50),\n 'label' => mb_strimwidth($dealStage['name'], 0, 191),\n 'type' => Stage::TYPE_OPPORTUNITY,\n 'sequence' => $i,\n 'is_selectable' => true,\n 'probability' => $dealStage['win_probability'],\n ]);\n\n if ($missingStageName && $missingStageName === $dealStage['id']) {\n $missingStage = $stage;\n }\n\n $stages[] = $stage['id'];\n }\n\n $businessProcess->stages()->sync($stages);\n }\n }\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n\n $cpLeads = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->paginate([\n 'minimum_modified_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ])\n );\n\n foreach ($cpLeads as $cpLead) {\n // Only sync if previously imported.\n if ($this->hasLead($cpLead['id']) === false) {\n $this->importLead($cpLead);\n $syncCount++;\n }\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n $cpLead = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->find($crmId)\n );\n\n if (\\count($cpLead) === 0) {\n return null;\n }\n\n return $this->importLead($cpLead);\n }\n\n /**\n * @inheritdoc\n */\n private function importLead($crmData): ?Lead\n {\n $countryCode = null;\n if (! empty($crmData['address']) && isset($crmData['address']['country'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $mobilePhone = $parsedNumber = null;\n if (! empty($crmData['phone_numbers'])) {\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n if ($phoneNumber['category'] === 'mobile') {\n $mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);\n } else {\n $parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);\n }\n }\n }\n\n $name = $crmData['name'];\n\n if (empty($crmData['company_name'])) {\n $company = 'Unknown';\n } else {\n $company = mb_strimwidth($crmData['company_name'], 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['websites']) === false) {\n $domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $email = null;\n if (empty($crmData['email']) === false) {\n $email = mb_strimwidth($crmData['email']['email'], 0, 80);\n }\n\n $stage = $this->config\n ->stages()\n ->where('crm_provider_id', (string) $crmData['status_id'])\n ->where('type', Stage::TYPE_LEAD)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status_id']);\n }\n\n if (! $stage instanceof Stage) {\n return null;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($name, 0, 191),\n 'company' => $company,\n 'domain' => $domain,\n 'title' => $crmData['title'] ? mb_strimwidth($crmData['title'], 0, 128) : null,\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'mobile_phone' => $mobilePhone,\n 'stage_id' => $stage->id,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Lead::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'country_code' => $countryCode,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $cpAccounts = $this->copperClient->accounts()->paginate([\n 'minimum_modified_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ]);\n\n foreach ($cpAccounts as $cpAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($cpAccount['id'])) {\n $this->importAccount($cpAccount);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n $cpAccount = $this->copperClient->accounts()->find($crmId);\n\n if (empty($cpAccount)) {\n return null;\n }\n\n return $this->importAccount($cpAccount);\n }\n\n /**\n * @inheritdoc\n */\n private function importAccount($crmData): Account\n {\n $countryCode = null;\n if (empty($crmData['address']) === false && $crmData['address']['country']) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $name = $crmData['name'];\n\n $parsedNumber = null;\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n $parsedNumber = parsePhoneNumber($countryCode, $phoneNumber['number']);\n }\n\n $domain = null;\n if (empty($crmData['websites']) === false) {\n $domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Account::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'country_code' => $countryCode,\n 'domain' => $domain,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->copperClient,\n ]);\n $strategies = $strategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n\n try {\n foreach ($strategies as $syncStrategy) {\n foreach ($syncStrategy->fetchOpportunities($parameters) as $opportunityData) {\n $this->importOpportunity($opportunityData);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n $this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => $exception->getMessage(),\n ]);\n }\n\n return $syncCount;\n }\n\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->copperClient,\n ]);\n $strategy = $strategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n $parameters['crm_id'] = $crmId;\n\n $cpOpportunity = $strategy->fetchOpportunities($parameters);\n\n return $this->importOpportunity($cpOpportunity);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n $companyId = (string) $crmData['company_id'];\n\n if (empty($companyId)) {\n $this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => 'No company id',\n ]);\n\n return null;\n }\n\n $account = $this->config->accounts()->where('crm_provider_id', $companyId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($companyId);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', (string) $crmData['pipeline_id'])\n ->first();\n\n if ($businessProcess === null) {\n // It is possible for some deals to not be in a pipeline.\n $this->logger->warning(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => 'Missing pipeline',\n ]);\n\n return null;\n }\n\n $stage = $businessProcess\n ->stages()\n ->where('crm_provider_id', (string) $crmData['pipeline_stage_id'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n $this->logger->info('Stage not found, importing', [\n 'pipeline_id' => $crmData['pipeline_id'],\n 'stage_id' => $crmData['pipeline_stage_id'],\n ]);\n\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['pipeline_stage_id']);\n }\n\n $recordType = $businessProcess->recordTypes()->first();\n $closeDate = null;\n $isClosed = $crmData['status'] !== self::OPPORTUNITY_STATUS_OPEN;\n\n if ($crmData['close_date']) {\n $closeDate = Carbon::parse($crmData['close_date'])->format('Y-m-d');\n }\n\n $data = [\n 'team_id' => $this->team->getId(),\n 'account_id' => $account->id,\n 'user_id' => $profile->user_id ?? null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($crmData['name'], 0, 128),\n 'value' => $crmData['monetary_value'],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['monetary_unit']),\n 'close_date' => $closeDate,\n 'is_closed' => $isClosed,\n 'is_won' => $crmData['status'] === 'Won',\n 'stage_id' => $stage->id,\n 'record_type_id' => $recordType->id ?? null,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n /** @var Opportunity $opportunity */\n $opportunity = $this->config\n ->opportunities()\n ->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data)\n ;\n\n // import external fields into crm_field_data if present\n $dealInsightsFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData($crmData, $dealInsightsFields, $opportunity->id);\n\n return $opportunity;\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n * @param string[] $dealInsightsFields\n */\n public function importOpportunityCrmFieldData(\n array $opportunityData,\n array $dealInsightsFields,\n int $opportunityId\n ): void {\n foreach ($dealInsightsFields as $fieldName) {\n $field = $this->config->fields()->with('entities')\n ->where('crm_provider_id', $fieldName)\n ->where('object_type', Field::OBJECT_OPPORTUNITY)\n ->first();\n\n if (! $field instanceof Field) {\n $this->logger->warning('Field not found', [\n 'field' => $fieldName,\n 'opportunity_id' => $opportunityId,\n ]);\n\n continue;\n }\n\n $entity = $field->getEntities()->first();\n\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $fieldValue = $this->extractFieldValue($opportunityData, $fieldName);\n $normalizedValue = $this->normalizeValue($field->getType(), (string) $fieldValue, true);\n\n $field->data()\n ->updateOrCreate([\n 'crm_layout_entity_id' => $entity->id,\n 'crm_field_id' => $field->id,\n 'object_type' => 'opportunity',\n 'object_id' => $opportunityId,\n ], ['value' => $normalizedValue])\n ;\n }\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $cpContacts = $this->copperClient->contacts()->paginate([\n 'minimum_interaction_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ]);\n\n foreach ($cpContacts as $cpContact) {\n // Only sync if previously imported.\n if ($this->hasContact($cpContact['id'])) {\n $this->importContact($cpContact);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n throw $exception;\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n $cpContact = $this->copperClient->contacts()->find($crmId);\n\n if (empty($cpContact)) {\n return null;\n }\n\n return $this->importContact($cpContact);\n }\n\n /**\n * @inheritdoc\n */\n private function importContact($crmData): Contact\n {\n $account = null;\n if ($crmData['company_id']) {\n $account = $this->team\n ->crm\n ->accounts()\n ->where('crm_provider_id', (string) $crmData['company_id'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['company_id']);\n }\n }\n\n $countryCode = null;\n if (empty($crmData['address']) === false && $crmData['address']['country']) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $mobilePhone = $parsedNumber = null;\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n if ($phoneNumber['category'] === 'mobile') {\n $mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);\n } else {\n $parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);\n }\n }\n\n $email = null;\n if (empty($crmData['emails']) === false) {\n $email = mb_strimwidth($crmData['emails'][0]['email'], 0, 80);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => $crmData['name'],\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'mobile_phone' => $mobilePhone ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'title' => $crmData['title'],\n 'country_code' => $countryCode,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Contact::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function buildContactPhone(?string $countryCode, ?string $number): ?array\n {\n if ($number) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($number, 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n return $parsedNumber;\n }\n\n private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string\n {\n return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n $organization = $this->copperClient->organisation()->all();\n\n if ($this->config->crm_provider_id !== $organization['id']) {\n $this->config->update(['crm_provider_id' => $organization['id']]);\n }\n }\n\n private function syncCustomFields(): void\n {\n foreach ($this->getFieldTypes() as $fieldType) {\n $currentFields = $this->getFields($fieldType);\n\n foreach ($currentFields as $field) {\n /** @var Field $field */\n $field = $this->config->fields()->updateOrCreate([\n 'crm_provider_id' => $field['name'],\n 'object_type' => $fieldType,\n ], [\n 'label' => mb_strimwidth($field['label'], 0, Field::LABEL_MAX_LENGTH),\n 'type' => $field['type'],\n ]);\n\n if ($field->getType() === Field::TYPE_PICKLIST) {\n $this->importPicklistValues($field);\n }\n }\n }\n\n $this->config->save();\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n parent::OBJECT_LEAD,\n parent::OBJECT_ACCOUNT,\n parent::OBJECT_CONTACT,\n parent::OBJECT_OPPORTUNITY,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $profiles = $this->copperClient->users()->all();\n\n foreach ($profiles as $profile) {\n $user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);\n\n // Only import profiles for users we have locally.\n if ($user) {\n $profile = $user->crmProfile()->updateOrCreate([\n 'crm_configuration_id' => $this->config->id,\n 'crm_provider_id' => $profile['id'],\n ]);\n\n if ($userToSearch && $userToSearch->id === $user->id) {\n return $profile;\n }\n }\n }\n\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'task',\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields(ucfirst($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))\n );\n\n if (\\count($changedFields) > 0) {\n $fields = implode(',', $newFields);\n $this->logger->debug(\n ucfirst($fieldType)\n . ' fields changed from '\n . $this->profile->{$fieldType . '_fields'}\n . ' to: '\n . $fields\n );\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (\\Exception $exception) {\n $this->logger->error('No access to ' . $fieldType . ' object, skipping...');\n\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $scopeValues = array_map(fn ($scope) => is_string($scope) ? $scope : $scope->value, $scopes);\n $cacheKey = sprintf('copper-search-%d-%s-%s-%d-%d', $this->team->id, $name, implode('-', $scopeValues), $count, $offset);\n\n return Cache::remember($cacheKey, 300, function () use ($name, $scopes, $count, $offset) {\n // Try local search first\n $localResults = $this->searchLocally($name, $scopes, $count, $offset);\n\n // If no local results, fall back to remote API search\n if (empty($localResults)) {\n return $this->searchRemotely($name, $scopes, $count, $offset);\n }\n\n return $localResults;\n });\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $params = [\n 'company_ids' => [$account->crm_provider_id],\n 'status_ids' => [0], // The integer values are 0, 1, 2, 3, for \"Open\", \"Won\", \"Lost\", and \"Abandoned\".\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ];\n\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort_by'] = 'date_modified';\n $params['sort_direction'] = 'desc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort_by'] = 'date_created';\n $params['sort_direction'] = 'desc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort_by'] = 'date_created';\n $params['sort_direction'] = 'asc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort_by'] = 'date_modified';\n $params['sort_direction'] = 'desc';\n $params['status_ids'] = [0, 1, 2, 3];\n }\n\n $cpOpportunities = $this->copperClient->opportunities()->search($params);\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n foreach ($cpOpportunities as $cpOpportunity) {\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', (string) $cpOpportunity['pipeline_id'])\n ->first();\n\n if ($businessProcess === null) {\n // Import it.\n $businessProcess = $this->importStages(\n [Stage::TYPE_OPPORTUNITY],\n $cpOpportunity['pipeline_stage_id']\n );\n }\n\n $stage = $businessProcess\n ->stages()\n ->where('crm_provider_id', (string) $cpOpportunity['pipeline_stage_id'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $cpOpportunity['pipeline_stage_id']);\n }\n\n $recordType = $businessProcess->recordTypes()->first();\n\n $record = [\n 'crmId' => $cpOpportunity['id'],\n 'name' => $cpOpportunity['name'],\n 'value' => currency_format($cpOpportunity['monetary_value'], $cpOpportunity['monetary_unit']),\n 'won' => $cpOpportunity['status'] === 'Won',\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n\n if ($ownerId && isset($cpOpportunity['assignee_id']) && $cpOpportunity['assignee_id'] === $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $cpTasks = [];\n\n switch ($objectType) {\n case 'lead':\n $cpTasks = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->relatedTasks($objectId)\n );\n\n break;\n\n case 'account':\n $cpTasks = $this->copperClient->accounts()->relatedTasks($objectId);\n\n break;\n case 'contact':\n if ($opportunityId) {\n $cpTasks = $this->copperClient->opportunities()->relatedTasks($opportunityId);\n } elseif ($objectType === 'contact') {\n $cpTasks = $this->copperClient->contacts()->relatedTasks($objectId);\n }\n\n break;\n }\n\n foreach ($cpTasks as $cpTask) {\n // We only get the ID itself returned, so pull out the full object.\n try {\n $cpTask = $this->copperClient->tasks()->find($cpTask['id']);\n } catch (Exception $exception) {\n $this->logger->error('[Copper] Error fetching task', [\n 'resource_id' => $cpTask['id'],\n 'error' => $exception->getMessage(),\n ]);\n\n continue;\n }\n\n // Only allow open tasks.\n if ($cpTask['status'] === 'Open') {\n $data[] = [\n 'crmId' => $cpTask['id'],\n 'subject' => $cpTask['name'],\n 'due' => $cpTask['due_date']\n ? Carbon::createFromTimestamp($cpTask['due_date'])->format('Y-m-d\\TH:i:sO')\n : null,\n 'type' => null,\n ];\n }\n }\n\n return $data;\n }\n\n /**\n * Try to find email address in CRM service\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $cpObjectType = 'contact';\n\n $cpObjects = $this->copperClient->contacts()->search([\n 'emails' => $email,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (empty($cpObjects)) {\n $cpObjectType = 'lead';\n $cpObjects = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'emails' => $email,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (empty($cpObjects)) {\n return null;\n }\n\n // Search returns an array of results, but we only want the first\n $cpObject = reset($cpObjects);\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember === false) {\n $cpObjectType = 'contact';\n $cpObject = $this->copperClient->contacts()->search([\n 'phone_number' => $phone,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (\\count($cpObject) === 0) {\n $cpObjectType = 'lead';\n $cpObject = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'phone_number' => $phone,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (empty($cpObject)) {\n return null;\n }\n\n $cpObject = reset($cpObject);\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n return null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n $result = \\Cache::remember($this->team->id . $name, 60, function () use ($name, $userId) {\n $cpObjectType = 'contact';\n $cpObject = $this->copperClient->contacts()->search([\n 'name' => $name,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (\\count($cpObject) === 0) {\n $cpObjectType = 'lead';\n $cpObject = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'name' => $name,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (! empty($cpObject)) {\n $cpObject = reset($cpObject);\n }\n\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n private function convertCrmData(array $object, string $objectType, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n if ($objectType === 'lead') {\n $lead = $this->importLead($object);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } else {\n $contact = $this->importContact($object);\n $account = $contact->account;\n\n if ($contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $cpOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact->crm_provider_id,\n $userId,\n );\n\n if (! empty($cpOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($cpOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n } catch (\\Exception $e) {\n // Nothing to see here.\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n public function saveActivity(Activity $activity): Activity\n {\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n $activity = $this->buildCallPayload($activity);\n\n break;\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildTextMessagePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n private function convertActivityAssociations(Activity $activity): array\n {\n if ($activity->lead) {\n $type = 'lead';\n $id = $activity->lead->crm_provider_id;\n } elseif ($activity->contact) {\n $type = 'person';\n $id = $activity->contact->crm_provider_id;\n } elseif ($activity->opportunity) {\n $type = 'opportunity';\n $id = $activity->opportunity->crm_provider_id;\n } else {\n $type = 'company';\n $id = $activity->account->crm_provider_id;\n }\n\n return [\n 'type' => $type,\n 'id' => $id,\n ];\n }\n\n private function convertActivityType(PlaybookCategory $activityType): array\n {\n return [\n 'category' => 'user',\n 'id' => $this->getCrmType($activityType)->value,\n ];\n }\n\n /**\n * @throws CrmException\n */\n private function buildCallPayload(Activity $activity): Activity\n {\n try {\n if ($activity->crm_provider_id) {\n // The activity should be logged under the existing Task (not Activity).\n $newActivityType = $this->getCrmType($activity->category);\n if ($newActivityType === null) {\n $message = sprintf('[Copper] invalid CRM Custom Activity Type: %s', $activity->category);\n\n throw new CrmException($message, 400);\n }\n $this->copperClient->tasks()->update($activity->crm_provider_id, [\n 'status' => 'Completed',\n 'custom_activity_type_id' => $newActivityType->value,\n 'details' => $this->generateActivityDescription($activity),\n ]);\n } else {\n if ($this->getCrmType($activity->category) === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n if ($this->getCrmType($activity->category)->value === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n // Just create an activity.\n $cpActivity = $this->copperClient->activities()->create([\n 'user_id' => $this->profile->crm_provider_id,\n 'activity_date' => $activity->scheduled_start_time->timestamp,\n 'parent' => $this->convertActivityAssociations($activity),\n 'type' => $this->convertActivityType($activity->category),\n 'details' => $this->generateActivityDescription($activity),\n ]);\n\n $activity->crm_provider_id = $cpActivity['id'];\n $activity->save();\n }\n } catch (ClientException $exception) {\n //Log all errors to Sentry\n \\Sentry::captureException($exception);\n\n $response = $exception->getResponse();\n\n $responseBody = $response->getBody();\n $message = $responseBody;\n $errorCode = $response->getStatusCode();\n\n $jsonResponse = json_decode($responseBody, true);\n if (isset($jsonResponse[0]['message'])) {\n $message = $jsonResponse[0]['message'];\n }\n\n throw new CrmException($message, $errorCode);\n }\n\n return $activity;\n }\n\n private function buildTextMessagePayload(Activity $activity): Activity\n {\n if ($this->getCrmType($activity->category) === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n if ($this->getCrmType($activity->category)->value === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n $cpActivity = $this->copperClient->activities()->create([\n 'user_id' => $this->profile->crm_provider_id,\n 'activity_date' => $activity->created_at->timestamp,\n 'parent' => $this->convertActivityAssociations($activity),\n 'type' => $this->convertActivityType($activity->category),\n 'details' => $this->generateActivityDescription($activity),\n ]);\n\n $activity->crm_provider_id = $cpActivity['id'];\n $activity->save();\n\n return $activity;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = '';\n\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n $description = 'Jiminny Call Summary' . PHP_EOL . PHP_EOL;\n $description .= 'Call Duration: ' . $activity->duration_for_humans . PHP_EOL . PHP_EOL;\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= 'Dialed: ' . $activity->to->phone_number . PHP_EOL . PHP_EOL;\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= 'Notetaker removed from this meeting' . PHP_EOL . PHP_EOL;\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= 'Notetaker did not join due to recording consent not being provided by attendees' . PHP_EOL . PHP_EOL;\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= 'Review Activity:' . PHP_EOL . $playbackUrl . PHP_EOL . PHP_EOL;\n }\n\n if ($activity->getCrmType() === Activity::TYPE_CONFERENCE) {\n $description .= 'Attendees:'\n . PHP_EOL\n . (new FilterJoinedParticipants())->toString($activity);\n }\n\n if (\\count($activity->notes) > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Notes: ' . PHP_EOL;\n\n foreach ($activity->notes as $note) {\n $nTime = (int) ceil($note->time);\n $time = ($nTime > 3600) ? gmdate('H:i:s', $nTime) : gmdate('i:s', $nTime);\n $description .= $time . ' ' . $note->note . PHP_EOL;\n }\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Coaching Chat: ' . PHP_EOL;\n\n foreach ($messages->get() as $message) {\n $description .= $message->participant->name . ': ' . $message->message . PHP_EOL;\n }\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Customer Chat: ' . PHP_EOL;\n\n foreach ($messages->get() as $message) {\n $description .= $message->participant->name . ': ' . $message->message . PHP_EOL;\n }\n }\n\n if ($activity->summary) {\n $description .= PHP_EOL . PHP_EOL . 'Summary: ' . PHP_EOL . $activity->summary;\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $description = $activity->description;\n\n break;\n }\n\n return $description;\n }\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // This is the user provided activity subject field.\n if (empty($fields['type'])) {\n return null;\n }\n\n $reminder = null;\n if (empty($fields['reminder_date']) === false) {\n $formatReminder = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['reminder_date']);\n $reminder = $formatReminder->getTimestamp();\n }\n\n $due = null;\n if (empty($fields['due_date']) === false) {\n $formatDue = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['due_date']);\n $due = $formatDue->getTimestamp();\n }\n\n $data = [\n 'custom_activity_type_id' => $fields['type'],\n 'status' => 'Open',\n 'assignee_id' => $this->profile->crm_provider_id,\n 'due_date' => $due,\n 'details' => $fields['details'] ?? '',\n 'reminder_date' => $reminder,\n 'name' => $fields['name'] ?? 'Follow-up',\n 'related_resource' => $this->convertActivityAssociations($activity),\n 'custom_fields' => $this->fetchCustomFieldData($activity, Field::OBJECT_TASK),\n ];\n\n // We don't actually create a corresponding activity object on our side yet.\n return $this->copperClient->tasks()->create($data)['id'];\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws \\Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // Generate activity transcription.\n $transcriptionData = $this->generateTranscription($activity);\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $transcripts = mb_strimwidth($transcriptionData, 0, static::NOTE_BODY_MAX_LENGTH);\n\n $data = [\n 'user_id' => $this->profile->crm_provider_id,\n 'type' => [\n 'category' => 'user',\n 'id' => 0, // This creates a note.\n ],\n 'activity_date' => time(),\n 'details' => $transcripts,\n 'parent' => $this->convertActivityAssociations($activity),\n ];\n\n $cpActivity = $this->copperClient->activities()->create($data);\n\n // Store CRM Activity ID in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $cpActivity['id'];\n $transcription->save();\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n if ($crmObject instanceof Lead) {\n $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->update($crmObject->crm_provider_id, [\n 'status_id' => $stage->crm_provider_id,\n ])\n );\n } else {\n $this->copperClient->opportunities()->update($crmObject->crm_provider_id, [\n 'pipeline_stage_id' => $stage->crm_provider_id,\n ]);\n }\n }\n\n public function prepareValueForUpdate(array $params): array\n {\n return [$params['fieldName'] => $params['fieldValue']];\n }\n\n /*\n * @inheritdoc\n */\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $preparedData = $data;\n\n if ($objectType === Field::OBJECT_OPPORTUNITY) {\n $preparedData = $this->prepareOpportunityFieldsForUpdate($data);\n }\n\n try {\n $this->copperClient\n ->createResourceFromObjectType($objectType)\n ->update($objectId, $preparedData)\n ;\n } catch (Exception $e) {\n $this->logger->error(self::RESOURCE_UPDATE_FAILED_ERROR_MESSAGE, [\n 'resource_id' => $objectId,\n 'data' => $preparedData,\n 'error' => $e->getMessage(),\n ]);\n\n throw new CrmException(self::RESOURCE_UPDATE_FAILED_ERROR_MESSAGE, $e->getCode(), $e);\n }\n }\n\n /**\n * @param array<string,string> $fieldData\n *\n * @throws CrmException\n *\n * @return array<string,array<int,array<string,bool|float|int|string|null>>|bool|float|int|string|null>\n */\n private function prepareOpportunityFieldsForUpdate(array $fieldData): array\n {\n $preparedData = [];\n $customFields = [];\n\n foreach ($fieldData as $fieldName => $fieldValue) {\n $field = $this->config\n ->fields()\n ->where('crm_provider_id', $fieldName)\n ->first();\n\n if (! $field instanceof Field) {\n throw new CrmException('Field not found');\n }\n\n $convertedValue = $this->fieldValueConverter->convertToCrm($field->getType(), $fieldValue);\n\n if ($this->isStandardField($fieldName)) {\n $preparedData[$fieldName] = $convertedValue;\n\n continue;\n }\n\n $customFields[] = [\n 'custom_field_definition_id' => $fieldName,\n 'value' => $convertedValue,\n ];\n }\n\n if (! empty($customFields)) {\n $preparedData['custom_fields'] = $customFields;\n }\n\n return $preparedData;\n }\n\n /*\n * @inheritdoc\n */\n public function getRecord(string $objectType, string $objectId, array $fields = []): array\n {\n return $this->copperClient->createResourceFromObjectType($objectType)->find($objectId);\n }\n\n private function fetchCustomFieldData(Activity $activity, string $objectType): array\n {\n $payload = [];\n\n $fieldData = FieldData::where([\n 'object_id' => $activity->id,\n ])->whereHas('field', function ($query) use ($objectType) {\n $query->where('object_type', $objectType);\n })->get();\n\n foreach ($fieldData as $data) {\n // Add the field and value to the payload.\n $payload += [\n 'custom_field_definition_id' => $data->field->crm_provider_id,\n 'value' => $data->value,\n ];\n }\n\n return $payload;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $baseUrl = 'https://app.prosperworks.com/companies/' . $this->config->crm_provider_id . '/app#/';\n switch ($objectType) {\n case 'lead':\n $url = $baseUrl . 'leads/' . $providerId;\n\n break;\n\n case 'account':\n $url = $baseUrl . 'organization/' . $providerId;\n\n break;\n\n case 'contact':\n $url = $baseUrl . 'contact/' . $providerId;\n\n break;\n\n case 'opportunity':\n $url = $baseUrl . 'deal/' . $providerId;\n\n break;\n\n default:\n case 'task':\n case 'activity':\n // Sadly we can't deeplink to these in Copper UI.\n $url = null;\n }\n\n return $url;\n }\n\n /**\n * Generate transcription for the activity.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! ($this->config->store_transcript)) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n return $this->transcriptionService\n ->findTranscriptionByActivity($activity)\n ->map(static function (array $transcriptionSegment): string {\n return $transcriptionSegment['formattedStartsAt'] . ' | ' . $transcriptionSegment['transcript'];\n })\n ->implode(PHP_EOL);\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n *\n * @return int|string|bool|float|null\n */\n private function extractFieldValue(array $opportunityData, string $fieldName)\n {\n $fieldValue = $this->isStandardField($fieldName)\n ? $opportunityData[$fieldName]\n : $this->resolveCustomFieldFromOpportunityData($opportunityData, $fieldName);\n\n if (is_array($fieldValue)) {\n $fieldValue = implode(', ', $fieldValue);\n }\n\n return $fieldValue;\n }\n\n private function isStandardField(string $fieldName): bool\n {\n return array_key_exists($fieldName, self::STANDARD_OPPORTUNITY_FIELDS);\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n *\n * @return string|int|float|bool|null|array<string, mixed>\n */\n private function resolveCustomFieldFromOpportunityData(array $opportunityData, string $fieldName)\n {\n $fieldData = array_filter(\n $opportunityData['custom_fields'],\n static fn ($field) => (string) $field['custom_field_definition_id'] === $fieldName\n );\n\n return array_pop($fieldData)['value'] ?? '';\n }\n\n private function isSupportedObjectType(string $objectType): bool\n {\n return $objectType !== self::UNSUPPORTED_OBJECT_TYPE;\n }\n\n private function syncStandardFields(): void\n {\n foreach (self::STANDARD_OPPORTUNITY_FIELDS as $fieldId => $fieldData) {\n $this->config->fields()->updateOrCreate([\n 'crm_provider_id' => mb_strimwidth($fieldId, 0, 128),\n 'object_type' => Field::OBJECT_OPPORTUNITY,\n ], [\n 'label' => mb_strimwidth($fieldData['label'], 0, Field::LABEL_MAX_LENGTH),\n 'type' => $fieldData['type'],\n ]);\n }\n\n $this->importStages([Stage::TYPE_OPPORTUNITY]);\n }\n\n private function requestWithExceptionHandling(\\Closure $apiRequest): iterable\n {\n try {\n return $apiRequest();\n } catch (\\Exception $exception) {\n if ($exception->getCode() === 403) {\n // Object might not be supported\n return [];\n }\n\n \\Sentry::captureException($exception);\n\n return [];\n }\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n if ($this->copperClient === null) {\n return false;\n }\n\n $task = $this->copperClient->tasks()->find($crmProviderId);\n\n return ! empty($task);\n } catch (HttpNotFoundException) {\n // Task not found in CRM - this is expected and permanent\n $this->logger->info('[Copper] Task not found during verification', [\n 'task_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n } catch (RequestFailedException $e) {\n // Handle 404 responses from Copper API\n if ($e->getCode() === 404) {\n $this->logger->info('[Copper] Task not found during verification (404)', [\n 'task_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n\n // Re-throw other Copper exceptions for retry\n throw $e;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Copper;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse GuzzleHttp\\Exception\\ClientException;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\CopperInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\FieldValue;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\PlaybookCategory;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\UserRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\Copper\\Api\\Client;\nuse Jiminny\\Services\\Crm\\Copper\\Api\\ClientFactory;\nuse Jiminny\\Services\\Crm\\Copper\\Exception\\RequestFailedException;\nuse Jiminny\\Services\\Crm\\Helpers\\FilterJoinedParticipants;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Services\\Crm\\Copper\\Traits\\SearchesCrmEntities;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\n\nclass Service extends BaseService implements\n CopperInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n use SearchesCrmEntities;\n private const int NOTE_BODY_MAX_LENGTH = 3000000;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const array STANDARD_OPPORTUNITY_FIELDS = [\n 'monetary_value' => [\n 'label' => 'Value',\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n 'type' => Field::TYPE_CURRENCY,\n ],\n 'pipeline_stage_id' => [\n 'label' => 'Stage',\n 'type' => Field::TYPE_PICKLIST,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n 'close_date' => [\n 'label' => 'Close date',\n 'type' => Field::TYPE_DATE,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n 'win_probability' => [\n 'label' => 'Win probability',\n 'type' => Field::TYPE_NUMBER,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n ];\n private const string UNSUPPORTED_OBJECT_TYPE = 'unsupported';\n private const string OPPORTUNITY_STATUS_OPEN = 'Open';\n private const string OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE = 'Opportunity import failed';\n private const string RESOURCE_UPDATE_FAILED_ERROR_MESSAGE = 'Failed to update resource';\n\n private FieldValueConverter $fieldValueConverter;\n private ClientFactory $clientFactory;\n private ?Client $copperClient = null;\n\n public function __construct(\n ClientFactory $clientFactory,\n FieldValueConverter $fieldValueConverter,\n private readonly UserRepository $userRepository,\n private readonly ProspectPhotoPathService $prospectPhotoPathService,\n private readonly CrmEntityRepository $crmEntityRepository\n ) {\n parent::__construct();\n\n $this->clientFactory = $clientFactory;\n $this->fieldValueConverter = $fieldValueConverter;\n }\n\n public function getDisplayName(): string\n {\n return 'Copper';\n }\n\n /**\n * Get the CRM entity repository (used by SearchesCrmEntities trait)\n */\n protected function getCrmEntityRepository(): CrmEntityRepository\n {\n return $this->crmEntityRepository;\n }\n\n public function getMinimumApiVersion(): string\n {\n return Client::MIN_API_VERSION;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_COPPER);\n }\n\n public function setUser(User $user): void\n {\n $this->configureSentryScope($user);\n\n $this->team = $user->getTeam();\n $this->teamService->setTeam($user->getTeam());\n $this->setConfiguration($user->getTeam()->getCrmConfiguration());\n\n // Reset state.\n $this->profile = $user->getProfile();\n\n if (! $this->profile instanceof Profile) {\n // Try to fetch their profile, maybe it was not yet imported?\n $this->profile = $this->getProfile($user);\n }\n }\n\n public function setConfiguration(Configuration $configuration): void\n {\n $this->config = $configuration;\n $this->copperClient = $this->clientFactory->create($configuration);\n\n if ($this->team === null) {\n $this->team = $configuration->getTeam();\n }\n }\n\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return $this->fieldValueConverter->convertFromCrm($fieldType, $fieldValue);\n }\n\n private function mapObjectType(string $objectType): string\n {\n $objectType = strtolower($objectType);\n\n switch ($objectType) {\n case Field::OBJECT_TASK:\n case Field::OBJECT_OPPORTUNITY:\n case Field::OBJECT_LEAD:\n $mappedType = $objectType;\n\n break;\n case Field::OBJECT_ACCOUNT:\n $mappedType = 'company';\n\n break;\n case Field::OBJECT_CONTACT:\n $mappedType = 'person';\n\n break;\n default:\n $mappedType = self::UNSUPPORTED_OBJECT_TYPE;\n\n break;\n }\n\n return $mappedType;\n }\n\n /**\n * @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact\n */\n protected function getFields(string $crmObject): array\n {\n $mappedObjectType = $this->mapObjectType($crmObject);\n\n if (! $this->isSupportedObjectType($mappedObjectType)) {\n return [];\n }\n\n $customFields = $this->copperClient->fields()->all();\n\n $filteredFields = array_filter(\n $customFields,\n static fn ($field) => in_array($mappedObjectType, $field['available_on'], true)\n );\n\n return array_map(\n fn (array $property) => [\n 'name' => $property['id'],\n 'label' => $property['name'],\n 'type' => $this->convertFieldType($property['data_type']),\n ],\n $filteredFields\n );\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {\n $defaultFields = FieldDefinitions::defaultTaskFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n $fieldFilters = FieldDefinitions::taskFollowupFieldsFilter();\n\n foreach ($fieldFilters as $data) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n public function syncFields(): void\n {\n $this->syncStandardFields();\n $this->syncCustomFields();\n }\n\n public function syncField(Field $field): void\n {\n if ($field->getCrmProviderId() === 'type') {\n /**\n * This field is a special case, it is not a custom field and is not returned by the Copper API.\n *\n * The field is created manually during layout setup.\n *\n * @see getDefaultFields()\n *\n * There is a separate endpoint to get the activity types.\n * @see importPicklistValues()\n */\n return;\n }\n\n if ($field->getCrmProviderId() === 'pipeline_stage_id') {\n // Not a custom type\n return;\n }\n\n $crmField = $this->copperClient->fields()->find($field->getCrmProviderId());\n $field->label = $crmField['name'];\n $field->type = $this->convertFieldType($crmField['data_type']);\n\n $field->save();\n }\n\n /**\n * @param string $fieldType How the data should be input\n */\n private function convertFieldType(string $fieldType): string\n {\n $fieldType = strtolower($fieldType);\n\n switch ($fieldType) {\n case 'dropdown':\n $convertedType = Field::TYPE_PICKLIST;\n\n break;\n case 'string':\n $convertedType = Field::TYPE_TEXT;\n\n break;\n case 'float':\n case 'percentage':\n $convertedType = Field::TYPE_NUMBER;\n\n break;\n case 'text':\n $convertedType = Field::TYPE_TEXTAREA;\n\n break;\n case 'checkbox':\n $convertedType = Field::TYPE_BOOLEAN;\n\n break;\n case Field::TYPE_DATE:\n case Field::TYPE_CURRENCY:\n case Field::TYPE_URL:\n $convertedType = $fieldType;\n\n break;\n default:\n $convertedType = Field::TYPE_UNSUPPORTED;\n\n break;\n }\n\n return $convertedType;\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $fieldValues = [];\n\n if ($field->object_type === 'opportunity' && $field->crm_provider_id === 'pipeline_stage_id') {\n return $this->importFieldValuesForDealInsights($field);\n }\n\n $values = [];\n\n if ($field->object_type === Field::OBJECT_TASK && $field->crm_provider_id === 'type') {\n $activityTypes = $this->copperClient->activityTypes()->all();\n\n /**\n * We ignore \"system\" activity types, disabled activity types and the \"Note\" activity type.\n */\n $activityTypes = array_filter(\n $activityTypes['user'],\n fn (array $activityType) => ! $activityType['is_disabled'] && $activityType['id'] !== 0\n );\n\n // Import all activity values.\n $i = 0;\n foreach ($activityTypes as $activityType) {\n $values[] = [\n 'value' => $activityType['id'],\n 'label' => mb_strimwidth($activityType['name'], 0, Field::LABEL_MAX_LENGTH),\n 'sequence' => $i++,\n ];\n }\n } else {\n // We just check for the field in the custom definitions.\n $crmField = $this->copperClient->fields()->find($field->crm_provider_id);\n\n // Import all values.\n foreach ($crmField['options'] as $option) {\n $values[] = [\n 'value' => $option['id'],\n 'label' => mb_strimwidth($option['name'], 0, 191),\n 'sequence' => $option['rank'],\n ];\n }\n }\n\n // Take the existing set of field values.\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n // For all current values, upsert the field.\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n $key = array_search($value['value'], $fieldsToPurge, false);\n if ($key !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n\n return $fieldValues;\n }\n\n /**\n *\n * @return FieldValue[]\n */\n private function importFieldValuesForDealInsights(Field $field): array\n {\n $fieldValues = [];\n $pipelines = $this->copperClient->pipelines()->all();\n\n foreach ($pipelines as $pipeline) {\n foreach ($pipeline['stages'] as $i => $dealStage) {\n $fieldValues[] = $field->values()->updateOrCreate(\n ['value' => $dealStage['id']],\n [\n 'label' => $dealStage['name'],\n 'sequence' => $i,\n ]\n );\n }\n }\n\n return $fieldValues;\n }\n\n /**\n * @inheritdoc\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n $missingStage = null;\n\n foreach ($types as $type) {\n if ($type === Stage::TYPE_LEAD) {\n $statuses = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leadStatuses()->all()\n );\n\n if (count($statuses) > 0) {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => BusinessProcess::TYPE_LEAD,\n ], [\n 'team_id' => $this->team->id,\n 'name' => BusinessProcess::TYPE_LEAD,\n 'type' => BusinessProcess::TYPE_LEAD,\n 'is_selectable' => true,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => BusinessProcess::TYPE_LEAD,\n ], [\n 'team_id' => $this->team->id,\n 'name' => BusinessProcess::TYPE_LEAD,\n 'is_selectable' => true,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $leadStatuses = [];\n foreach ($statuses as $status) {\n // Upsert all statuses for the team.\n $status = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $status['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($status['name'], 0, 50),\n 'label' => mb_strimwidth($status['name'], 0, 191),\n 'type' => Stage::TYPE_LEAD,\n 'sequence' => $status['order'],\n 'is_selectable' => true,\n ]);\n\n if ($missingStageName && $missingStageName === $status['id']) {\n $missingStage = $status;\n }\n\n $leadStatuses[] = $status['id'];\n }\n\n $businessProcess->stages()->sync($leadStatuses);\n }\n } else {\n // We create a business process to contain the pipeline, and later store all stages against it.\n foreach ($this->copperClient->pipelines()->all() as $pipeline) {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $pipeline['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline['name'], 0, 150),\n 'type' => BusinessProcess::TYPE_OPPORTUNITY,\n 'is_selectable' => true,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $pipeline['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline['name'], 0, 150),\n 'is_selectable' => true,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $stages = [];\n\n foreach ($pipeline['stages'] as $i => $dealStage) {\n // Upsert all stages for the team.\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $dealStage['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($dealStage['name'], 0, 50),\n 'label' => mb_strimwidth($dealStage['name'], 0, 191),\n 'type' => Stage::TYPE_OPPORTUNITY,\n 'sequence' => $i,\n 'is_selectable' => true,\n 'probability' => $dealStage['win_probability'],\n ]);\n\n if ($missingStageName && $missingStageName === $dealStage['id']) {\n $missingStage = $stage;\n }\n\n $stages[] = $stage['id'];\n }\n\n $businessProcess->stages()->sync($stages);\n }\n }\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n\n $cpLeads = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->paginate([\n 'minimum_modified_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ])\n );\n\n foreach ($cpLeads as $cpLead) {\n // Only sync if previously imported.\n if ($this->hasLead($cpLead['id']) === false) {\n $this->importLead($cpLead);\n $syncCount++;\n }\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n $cpLead = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->find($crmId)\n );\n\n if (\\count($cpLead) === 0) {\n return null;\n }\n\n return $this->importLead($cpLead);\n }\n\n /**\n * @inheritdoc\n */\n private function importLead($crmData): ?Lead\n {\n $countryCode = null;\n if (! empty($crmData['address']) && isset($crmData['address']['country'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $mobilePhone = $parsedNumber = null;\n if (! empty($crmData['phone_numbers'])) {\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n if ($phoneNumber['category'] === 'mobile') {\n $mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);\n } else {\n $parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);\n }\n }\n }\n\n $name = $crmData['name'];\n\n if (empty($crmData['company_name'])) {\n $company = 'Unknown';\n } else {\n $company = mb_strimwidth($crmData['company_name'], 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['websites']) === false) {\n $domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $email = null;\n if (empty($crmData['email']) === false) {\n $email = mb_strimwidth($crmData['email']['email'], 0, 80);\n }\n\n $stage = $this->config\n ->stages()\n ->where('crm_provider_id', (string) $crmData['status_id'])\n ->where('type', Stage::TYPE_LEAD)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status_id']);\n }\n\n if (! $stage instanceof Stage) {\n return null;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($name, 0, 191),\n 'company' => $company,\n 'domain' => $domain,\n 'title' => $crmData['title'] ? mb_strimwidth($crmData['title'], 0, 128) : null,\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'mobile_phone' => $mobilePhone,\n 'stage_id' => $stage->id,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Lead::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'country_code' => $countryCode,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $cpAccounts = $this->copperClient->accounts()->paginate([\n 'minimum_modified_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ]);\n\n foreach ($cpAccounts as $cpAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($cpAccount['id'])) {\n $this->importAccount($cpAccount);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n $cpAccount = $this->copperClient->accounts()->find($crmId);\n\n if (empty($cpAccount)) {\n return null;\n }\n\n return $this->importAccount($cpAccount);\n }\n\n /**\n * @inheritdoc\n */\n private function importAccount($crmData): Account\n {\n $countryCode = null;\n if (empty($crmData['address']) === false && $crmData['address']['country']) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $name = $crmData['name'];\n\n $parsedNumber = null;\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n $parsedNumber = parsePhoneNumber($countryCode, $phoneNumber['number']);\n }\n\n $domain = null;\n if (empty($crmData['websites']) === false) {\n $domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Account::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'country_code' => $countryCode,\n 'domain' => $domain,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->copperClient,\n ]);\n $strategies = $strategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n\n try {\n foreach ($strategies as $syncStrategy) {\n foreach ($syncStrategy->fetchOpportunities($parameters) as $opportunityData) {\n $this->importOpportunity($opportunityData);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n $this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => $exception->getMessage(),\n ]);\n }\n\n return $syncCount;\n }\n\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->copperClient,\n ]);\n $strategy = $strategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n $parameters['crm_id'] = $crmId;\n\n $cpOpportunity = $strategy->fetchOpportunities($parameters);\n\n return $this->importOpportunity($cpOpportunity);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n $companyId = (string) $crmData['company_id'];\n\n if (empty($companyId)) {\n $this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => 'No company id',\n ]);\n\n return null;\n }\n\n $account = $this->config->accounts()->where('crm_provider_id', $companyId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($companyId);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', (string) $crmData['pipeline_id'])\n ->first();\n\n if ($businessProcess === null) {\n // It is possible for some deals to not be in a pipeline.\n $this->logger->warning(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => 'Missing pipeline',\n ]);\n\n return null;\n }\n\n $stage = $businessProcess\n ->stages()\n ->where('crm_provider_id', (string) $crmData['pipeline_stage_id'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n $this->logger->info('Stage not found, importing', [\n 'pipeline_id' => $crmData['pipeline_id'],\n 'stage_id' => $crmData['pipeline_stage_id'],\n ]);\n\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['pipeline_stage_id']);\n }\n\n $recordType = $businessProcess->recordTypes()->first();\n $closeDate = null;\n $isClosed = $crmData['status'] !== self::OPPORTUNITY_STATUS_OPEN;\n\n if ($crmData['close_date']) {\n $closeDate = Carbon::parse($crmData['close_date'])->format('Y-m-d');\n }\n\n $data = [\n 'team_id' => $this->team->getId(),\n 'account_id' => $account->id,\n 'user_id' => $profile->user_id ?? null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($crmData['name'], 0, 128),\n 'value' => $crmData['monetary_value'],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['monetary_unit']),\n 'close_date' => $closeDate,\n 'is_closed' => $isClosed,\n 'is_won' => $crmData['status'] === 'Won',\n 'stage_id' => $stage->id,\n 'record_type_id' => $recordType->id ?? null,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n /** @var Opportunity $opportunity */\n $opportunity = $this->config\n ->opportunities()\n ->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data)\n ;\n\n // import external fields into crm_field_data if present\n $dealInsightsFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData($crmData, $dealInsightsFields, $opportunity->id);\n\n return $opportunity;\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n * @param string[] $dealInsightsFields\n */\n public function importOpportunityCrmFieldData(\n array $opportunityData,\n array $dealInsightsFields,\n int $opportunityId\n ): void {\n foreach ($dealInsightsFields as $fieldName) {\n $field = $this->config->fields()->with('entities')\n ->where('crm_provider_id', $fieldName)\n ->where('object_type', Field::OBJECT_OPPORTUNITY)\n ->first();\n\n if (! $field instanceof Field) {\n $this->logger->warning('Field not found', [\n 'field' => $fieldName,\n 'opportunity_id' => $opportunityId,\n ]);\n\n continue;\n }\n\n $entity = $field->getEntities()->first();\n\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $fieldValue = $this->extractFieldValue($opportunityData, $fieldName);\n $normalizedValue = $this->normalizeValue($field->getType(), (string) $fieldValue, true);\n\n $field->data()\n ->updateOrCreate([\n 'crm_layout_entity_id' => $entity->id,\n 'crm_field_id' => $field->id,\n 'object_type' => 'opportunity',\n 'object_id' => $opportunityId,\n ], ['value' => $normalizedValue])\n ;\n }\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $cpContacts = $this->copperClient->contacts()->paginate([\n 'minimum_interaction_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ]);\n\n foreach ($cpContacts as $cpContact) {\n // Only sync if previously imported.\n if ($this->hasContact($cpContact['id'])) {\n $this->importContact($cpContact);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n throw $exception;\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n $cpContact = $this->copperClient->contacts()->find($crmId);\n\n if (empty($cpContact)) {\n return null;\n }\n\n return $this->importContact($cpContact);\n }\n\n /**\n * @inheritdoc\n */\n private function importContact($crmData): Contact\n {\n $account = null;\n if ($crmData['company_id']) {\n $account = $this->team\n ->crm\n ->accounts()\n ->where('crm_provider_id', (string) $crmData['company_id'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['company_id']);\n }\n }\n\n $countryCode = null;\n if (empty($crmData['address']) === false && $crmData['address']['country']) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $mobilePhone = $parsedNumber = null;\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n if ($phoneNumber['category'] === 'mobile') {\n $mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);\n } else {\n $parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);\n }\n }\n\n $email = null;\n if (empty($crmData['emails']) === false) {\n $email = mb_strimwidth($crmData['emails'][0]['email'], 0, 80);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => $crmData['name'],\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'mobile_phone' => $mobilePhone ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'title' => $crmData['title'],\n 'country_code' => $countryCode,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Contact::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function buildContactPhone(?string $countryCode, ?string $number): ?array\n {\n if ($number) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($number, 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n return $parsedNumber;\n }\n\n private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string\n {\n return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n $organization = $this->copperClient->organisation()->all();\n\n if ($this->config->crm_provider_id !== $organization['id']) {\n $this->config->update(['crm_provider_id' => $organization['id']]);\n }\n }\n\n private function syncCustomFields(): void\n {\n foreach ($this->getFieldTypes() as $fieldType) {\n $currentFields = $this->getFields($fieldType);\n\n foreach ($currentFields as $field) {\n /** @var Field $field */\n $field = $this->config->fields()->updateOrCreate([\n 'crm_provider_id' => $field['name'],\n 'object_type' => $fieldType,\n ], [\n 'label' => mb_strimwidth($field['label'], 0, Field::LABEL_MAX_LENGTH),\n 'type' => $field['type'],\n ]);\n\n if ($field->getType() === Field::TYPE_PICKLIST) {\n $this->importPicklistValues($field);\n }\n }\n }\n\n $this->config->save();\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n parent::OBJECT_LEAD,\n parent::OBJECT_ACCOUNT,\n parent::OBJECT_CONTACT,\n parent::OBJECT_OPPORTUNITY,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $profiles = $this->copperClient->users()->all();\n\n foreach ($profiles as $profile) {\n $user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);\n\n // Only import profiles for users we have locally.\n if ($user) {\n $profile = $user->crmProfile()->updateOrCreate([\n 'crm_configuration_id' => $this->config->id,\n 'crm_provider_id' => $profile['id'],\n ]);\n\n if ($userToSearch && $userToSearch->id === $user->id) {\n return $profile;\n }\n }\n }\n\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'task',\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields(ucfirst($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))\n );\n\n if (\\count($changedFields) > 0) {\n $fields = implode(',', $newFields);\n $this->logger->debug(\n ucfirst($fieldType)\n . ' fields changed from '\n . $this->profile->{$fieldType . '_fields'}\n . ' to: '\n . $fields\n );\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (\\Exception $exception) {\n $this->logger->error('No access to ' . $fieldType . ' object, skipping...');\n\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $scopeValues = array_map(fn ($scope) => is_string($scope) ? $scope : $scope->value, $scopes);\n $cacheKey = sprintf('copper-search-%d-%s-%s-%d-%d', $this->team->id, $name, implode('-', $scopeValues), $count, $offset);\n\n return Cache::remember($cacheKey, 300, function () use ($name, $scopes, $count, $offset) {\n // Try local search first\n $localResults = $this->searchLocally($name, $scopes, $count, $offset);\n\n // If no local results, fall back to remote API search\n if (empty($localResults)) {\n return $this->searchRemotely($name, $scopes, $count, $offset);\n }\n\n return $localResults;\n });\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $params = [\n 'company_ids' => [$account->crm_provider_id],\n 'status_ids' => [0], // The integer values are 0, 1, 2, 3, for \"Open\", \"Won\", \"Lost\", and \"Abandoned\".\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ];\n\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort_by'] = 'date_modified';\n $params['sort_direction'] = 'desc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort_by'] = 'date_created';\n $params['sort_direction'] = 'desc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort_by'] = 'date_created';\n $params['sort_direction'] = 'asc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort_by'] = 'date_modified';\n $params['sort_direction'] = 'desc';\n $params['status_ids'] = [0, 1, 2, 3];\n }\n\n $cpOpportunities = $this->copperClient->opportunities()->search($params);\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n foreach ($cpOpportunities as $cpOpportunity) {\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', (string) $cpOpportunity['pipeline_id'])\n ->first();\n\n if ($businessProcess === null) {\n // Import it.\n $businessProcess = $this->importStages(\n [Stage::TYPE_OPPORTUNITY],\n $cpOpportunity['pipeline_stage_id']\n );\n }\n\n $stage = $businessProcess\n ->stages()\n ->where('crm_provider_id', (string) $cpOpportunity['pipeline_stage_id'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $cpOpportunity['pipeline_stage_id']);\n }\n\n $recordType = $businessProcess->recordTypes()->first();\n\n $record = [\n 'crmId' => $cpOpportunity['id'],\n 'name' => $cpOpportunity['name'],\n 'value' => currency_format($cpOpportunity['monetary_value'], $cpOpportunity['monetary_unit']),\n 'won' => $cpOpportunity['status'] === 'Won',\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n\n if ($ownerId && isset($cpOpportunity['assignee_id']) && $cpOpportunity['assignee_id'] === $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $cpTasks = [];\n\n switch ($objectType) {\n case 'lead':\n $cpTasks = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->relatedTasks($objectId)\n );\n\n break;\n\n case 'account':\n $cpTasks = $this->copperClient->accounts()->relatedTasks($objectId);\n\n break;\n case 'contact':\n if ($opportunityId) {\n $cpTasks = $this->copperClient->opportunities()->relatedTasks($opportunityId);\n } elseif ($objectType === 'contact') {\n $cpTasks = $this->copperClient->contacts()->relatedTasks($objectId);\n }\n\n break;\n }\n\n foreach ($cpTasks as $cpTask) {\n // We only get the ID itself returned, so pull out the full object.\n try {\n $cpTask = $this->copperClient->tasks()->find($cpTask['id']);\n } catch (Exception $exception) {\n $this->logger->error('[Copper] Error fetching task', [\n 'resource_id' => $cpTask['id'],\n 'error' => $exception->getMessage(),\n ]);\n\n continue;\n }\n\n // Only allow open tasks.\n if ($cpTask['status'] === 'Open') {\n $data[] = [\n 'crmId' => $cpTask['id'],\n 'subject' => $cpTask['name'],\n 'due' => $cpTask['due_date']\n ? Carbon::createFromTimestamp($cpTask['due_date'])->format('Y-m-d\\TH:i:sO')\n : null,\n 'type' => null,\n ];\n }\n }\n\n return $data;\n }\n\n /**\n * Try to find email address in CRM service\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $cpObjectType = 'contact';\n\n $cpObjects = $this->copperClient->contacts()->search([\n 'emails' => $email,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (empty($cpObjects)) {\n $cpObjectType = 'lead';\n $cpObjects = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'emails' => $email,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (empty($cpObjects)) {\n return null;\n }\n\n // Search returns an array of results, but we only want the first\n $cpObject = reset($cpObjects);\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember === false) {\n $cpObjectType = 'contact';\n $cpObject = $this->copperClient->contacts()->search([\n 'phone_number' => $phone,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (\\count($cpObject) === 0) {\n $cpObjectType = 'lead';\n $cpObject = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'phone_number' => $phone,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (empty($cpObject)) {\n return null;\n }\n\n $cpObject = reset($cpObject);\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n return null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n $result = \\Cache::remember($this->team->id . $name, 60, function () use ($name, $userId) {\n $cpObjectType = 'contact';\n $cpObject = $this->copperClient->contacts()->search([\n 'name' => $name,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (\\count($cpObject) === 0) {\n $cpObjectType = 'lead';\n $cpObject = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'name' => $name,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (! empty($cpObject)) {\n $cpObject = reset($cpObject);\n }\n\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n private function convertCrmData(array $object, string $objectType, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n if ($objectType === 'lead') {\n $lead = $this->importLead($object);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } else {\n $contact = $this->importContact($object);\n $account = $contact->account;\n\n if ($contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $cpOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact->crm_provider_id,\n $userId,\n );\n\n if (! empty($cpOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($cpOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n } catch (\\Exception $e) {\n // Nothing to see here.\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n public function saveActivity(Activity $activity): Activity\n {\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n $activity = $this->buildCallPayload($activity);\n\n break;\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildTextMessagePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n private function convertActivityAssociations(Activity $activity): array\n {\n if ($activity->lead) {\n $type = 'lead';\n $id = $activity->lead->crm_provider_id;\n } elseif ($activity->contact) {\n $type = 'person';\n $id = $activity->contact->crm_provider_id;\n } elseif ($activity->opportunity) {\n $type = 'opportunity';\n $id = $activity->opportunity->crm_provider_id;\n } else {\n $type = 'company';\n $id = $activity->account->crm_provider_id;\n }\n\n return [\n 'type' => $type,\n 'id' => $id,\n ];\n }\n\n private function convertActivityType(PlaybookCategory $activityType): array\n {\n return [\n 'category' => 'user',\n 'id' => $this->getCrmType($activityType)->value,\n ];\n }\n\n /**\n * @throws CrmException\n */\n private function buildCallPayload(Activity $activity): Activity\n {\n try {\n if ($activity->crm_provider_id) {\n // The activity should be logged under the existing Task (not Activity).\n $newActivityType = $this->getCrmType($activity->category);\n if ($newActivityType === null) {\n $message = sprintf('[Copper] invalid CRM Custom Activity Type: %s', $activity->category);\n\n throw new CrmException($message, 400);\n }\n $this->copperClient->tasks()->update($activity->crm_provider_id, [\n 'status' => 'Completed',\n 'custom_activity_type_id' => $newActivityType->value,\n 'details' => $this->generateActivityDescription($activity),\n ]);\n } else {\n if ($this->getCrmType($activity->category) === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n if ($this->getCrmType($activity->category)->value === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n // Just create an activity.\n $cpActivity = $this->copperClient->activities()->create([\n 'user_id' => $this->profile->crm_provider_id,\n 'activity_date' => $activity->scheduled_start_time->timestamp,\n 'parent' => $this->convertActivityAssociations($activity),\n 'type' => $this->convertActivityType($activity->category),\n 'details' => $this->generateActivityDescription($activity),\n ]);\n\n $activity->crm_provider_id = $cpActivity['id'];\n $activity->save();\n }\n } catch (ClientException $exception) {\n //Log all errors to Sentry\n \\Sentry::captureException($exception);\n\n $response = $exception->getResponse();\n\n $responseBody = $response->getBody();\n $message = $responseBody;\n $errorCode = $response->getStatusCode();\n\n $jsonResponse = json_decode($responseBody, true);\n if (isset($jsonResponse[0]['message'])) {\n $message = $jsonResponse[0]['message'];\n }\n\n throw new CrmException($message, $errorCode);\n }\n\n return $activity;\n }\n\n private function buildTextMessagePayload(Activity $activity): Activity\n {\n if ($this->getCrmType($activity->category) === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n if ($this->getCrmType($activity->category)->value === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n $cpActivity = $this->copperClient->activities()->create([\n 'user_id' => $this->profile->crm_provider_id,\n 'activity_date' => $activity->created_at->timestamp,\n 'parent' => $this->convertActivityAssociations($activity),\n 'type' => $this->convertActivityType($activity->category),\n 'details' => $this->generateActivityDescription($activity),\n ]);\n\n $activity->crm_provider_id = $cpActivity['id'];\n $activity->save();\n\n return $activity;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = '';\n\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n $description = 'Jiminny Call Summary' . PHP_EOL . PHP_EOL;\n $description .= 'Call Duration: ' . $activity->duration_for_humans . PHP_EOL . PHP_EOL;\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= 'Dialed: ' . $activity->to->phone_number . PHP_EOL . PHP_EOL;\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= 'Notetaker removed from this meeting' . PHP_EOL . PHP_EOL;\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= 'Notetaker did not join due to recording consent not being provided by attendees' . PHP_EOL . PHP_EOL;\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= 'Review Activity:' . PHP_EOL . $playbackUrl . PHP_EOL . PHP_EOL;\n }\n\n if ($activity->getCrmType() === Activity::TYPE_CONFERENCE) {\n $description .= 'Attendees:'\n . PHP_EOL\n . (new FilterJoinedParticipants())->toString($activity);\n }\n\n if (\\count($activity->notes) > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Notes: ' . PHP_EOL;\n\n foreach ($activity->notes as $note) {\n $nTime = (int) ceil($note->time);\n $time = ($nTime > 3600) ? gmdate('H:i:s', $nTime) : gmdate('i:s', $nTime);\n $description .= $time . ' ' . $note->note . PHP_EOL;\n }\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Coaching Chat: ' . PHP_EOL;\n\n foreach ($messages->get() as $message) {\n $description .= $message->participant->name . ': ' . $message->message . PHP_EOL;\n }\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Customer Chat: ' . PHP_EOL;\n\n foreach ($messages->get() as $message) {\n $description .= $message->participant->name . ': ' . $message->message . PHP_EOL;\n }\n }\n\n if ($activity->summary) {\n $description .= PHP_EOL . PHP_EOL . 'Summary: ' . PHP_EOL . $activity->summary;\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $description = $activity->description;\n\n break;\n }\n\n return $description;\n }\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // This is the user provided activity subject field.\n if (empty($fields['type'])) {\n return null;\n }\n\n $reminder = null;\n if (empty($fields['reminder_date']) === false) {\n $formatReminder = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['reminder_date']);\n $reminder = $formatReminder->getTimestamp();\n }\n\n $due = null;\n if (empty($fields['due_date']) === false) {\n $formatDue = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['due_date']);\n $due = $formatDue->getTimestamp();\n }\n\n $data = [\n 'custom_activity_type_id' => $fields['type'],\n 'status' => 'Open',\n 'assignee_id' => $this->profile->crm_provider_id,\n 'due_date' => $due,\n 'details' => $fields['details'] ?? '',\n 'reminder_date' => $reminder,\n 'name' => $fields['name'] ?? 'Follow-up',\n 'related_resource' => $this->convertActivityAssociations($activity),\n 'custom_fields' => $this->fetchCustomFieldData($activity, Field::OBJECT_TASK),\n ];\n\n // We don't actually create a corresponding activity object on our side yet.\n return $this->copperClient->tasks()->create($data)['id'];\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws \\Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // Generate activity transcription.\n $transcriptionData = $this->generateTranscription($activity);\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $transcripts = mb_strimwidth($transcriptionData, 0, static::NOTE_BODY_MAX_LENGTH);\n\n $data = [\n 'user_id' => $this->profile->crm_provider_id,\n 'type' => [\n 'category' => 'user',\n 'id' => 0, // This creates a note.\n ],\n 'activity_date' => time(),\n 'details' => $transcripts,\n 'parent' => $this->convertActivityAssociations($activity),\n ];\n\n $cpActivity = $this->copperClient->activities()->create($data);\n\n // Store CRM Activity ID in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $cpActivity['id'];\n $transcription->save();\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n if ($crmObject instanceof Lead) {\n $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->update($crmObject->crm_provider_id, [\n 'status_id' => $stage->crm_provider_id,\n ])\n );\n } else {\n $this->copperClient->opportunities()->update($crmObject->crm_provider_id, [\n 'pipeline_stage_id' => $stage->crm_provider_id,\n ]);\n }\n }\n\n public function prepareValueForUpdate(array $params): array\n {\n return [$params['fieldName'] => $params['fieldValue']];\n }\n\n /*\n * @inheritdoc\n */\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $preparedData = $data;\n\n if ($objectType === Field::OBJECT_OPPORTUNITY) {\n $preparedData = $this->prepareOpportunityFieldsForUpdate($data);\n }\n\n try {\n $this->copperClient\n ->createResourceFromObjectType($objectType)\n ->update($objectId, $preparedData)\n ;\n } catch (Exception $e) {\n $this->logger->error(self::RESOURCE_UPDATE_FAILED_ERROR_MESSAGE, [\n 'resource_id' => $objectId,\n 'data' => $preparedData,\n 'error' => $e->getMessage(),\n ]);\n\n throw new CrmException(self::RESOURCE_UPDATE_FAILED_ERROR_MESSAGE, $e->getCode(), $e);\n }\n }\n\n /**\n * @param array<string,string> $fieldData\n *\n * @throws CrmException\n *\n * @return array<string,array<int,array<string,bool|float|int|string|null>>|bool|float|int|string|null>\n */\n private function prepareOpportunityFieldsForUpdate(array $fieldData): array\n {\n $preparedData = [];\n $customFields = [];\n\n foreach ($fieldData as $fieldName => $fieldValue) {\n $field = $this->config\n ->fields()\n ->where('crm_provider_id', $fieldName)\n ->first();\n\n if (! $field instanceof Field) {\n throw new CrmException('Field not found');\n }\n\n $convertedValue = $this->fieldValueConverter->convertToCrm($field->getType(), $fieldValue);\n\n if ($this->isStandardField($fieldName)) {\n $preparedData[$fieldName] = $convertedValue;\n\n continue;\n }\n\n $customFields[] = [\n 'custom_field_definition_id' => $fieldName,\n 'value' => $convertedValue,\n ];\n }\n\n if (! empty($customFields)) {\n $preparedData['custom_fields'] = $customFields;\n }\n\n return $preparedData;\n }\n\n /*\n * @inheritdoc\n */\n public function getRecord(string $objectType, string $objectId, array $fields = []): array\n {\n return $this->copperClient->createResourceFromObjectType($objectType)->find($objectId);\n }\n\n private function fetchCustomFieldData(Activity $activity, string $objectType): array\n {\n $payload = [];\n\n $fieldData = FieldData::where([\n 'object_id' => $activity->id,\n ])->whereHas('field', function ($query) use ($objectType) {\n $query->where('object_type', $objectType);\n })->get();\n\n foreach ($fieldData as $data) {\n // Add the field and value to the payload.\n $payload += [\n 'custom_field_definition_id' => $data->field->crm_provider_id,\n 'value' => $data->value,\n ];\n }\n\n return $payload;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $baseUrl = 'https://app.prosperworks.com/companies/' . $this->config->crm_provider_id . '/app#/';\n switch ($objectType) {\n case 'lead':\n $url = $baseUrl . 'leads/' . $providerId;\n\n break;\n\n case 'account':\n $url = $baseUrl . 'organization/' . $providerId;\n\n break;\n\n case 'contact':\n $url = $baseUrl . 'contact/' . $providerId;\n\n break;\n\n case 'opportunity':\n $url = $baseUrl . 'deal/' . $providerId;\n\n break;\n\n default:\n case 'task':\n case 'activity':\n // Sadly we can't deeplink to these in Copper UI.\n $url = null;\n }\n\n return $url;\n }\n\n /**\n * Generate transcription for the activity.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! ($this->config->store_transcript)) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n return $this->transcriptionService\n ->findTranscriptionByActivity($activity)\n ->map(static function (array $transcriptionSegment): string {\n return $transcriptionSegment['formattedStartsAt'] . ' | ' . $transcriptionSegment['transcript'];\n })\n ->implode(PHP_EOL);\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n *\n * @return int|string|bool|float|null\n */\n private function extractFieldValue(array $opportunityData, string $fieldName)\n {\n $fieldValue = $this->isStandardField($fieldName)\n ? $opportunityData[$fieldName]\n : $this->resolveCustomFieldFromOpportunityData($opportunityData, $fieldName);\n\n if (is_array($fieldValue)) {\n $fieldValue = implode(', ', $fieldValue);\n }\n\n return $fieldValue;\n }\n\n private function isStandardField(string $fieldName): bool\n {\n return array_key_exists($fieldName, self::STANDARD_OPPORTUNITY_FIELDS);\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n *\n * @return string|int|float|bool|null|array<string, mixed>\n */\n private function resolveCustomFieldFromOpportunityData(array $opportunityData, string $fieldName)\n {\n $fieldData = array_filter(\n $opportunityData['custom_fields'],\n static fn ($field) => (string) $field['custom_field_definition_id'] === $fieldName\n );\n\n return array_pop($fieldData)['value'] ?? '';\n }\n\n private function isSupportedObjectType(string $objectType): bool\n {\n return $objectType !== self::UNSUPPORTED_OBJECT_TYPE;\n }\n\n private function syncStandardFields(): void\n {\n foreach (self::STANDARD_OPPORTUNITY_FIELDS as $fieldId => $fieldData) {\n $this->config->fields()->updateOrCreate([\n 'crm_provider_id' => mb_strimwidth($fieldId, 0, 128),\n 'object_type' => Field::OBJECT_OPPORTUNITY,\n ], [\n 'label' => mb_strimwidth($fieldData['label'], 0, Field::LABEL_MAX_LENGTH),\n 'type' => $fieldData['type'],\n ]);\n }\n\n $this->importStages([Stage::TYPE_OPPORTUNITY]);\n }\n\n private function requestWithExceptionHandling(\\Closure $apiRequest): iterable\n {\n try {\n return $apiRequest();\n } catch (\\Exception $exception) {\n if ($exception->getCode() === 403) {\n // Object might not be supported\n return [];\n }\n\n \\Sentry::captureException($exception);\n\n return [];\n }\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n if ($this->copperClient === null) {\n return false;\n }\n\n $task = $this->copperClient->tasks()->find($crmProviderId);\n\n return ! empty($task);\n } catch (HttpNotFoundException) {\n // Task not found in CRM - this is expected and permanent\n $this->logger->info('[Copper] Task not found during verification', [\n 'task_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n } catch (RequestFailedException $e) {\n // Handle 404 responses from Copper API\n if ($e->getCode() === 404) {\n $this->logger->info('[Copper] Task not found during verification (404)', [\n 'task_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n\n // Re-throw other Copper exceptions for retry\n throw $e;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.85486114,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"bounds":{"left":0.87291664,"top":0.31,"width":0.018055556,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.9138889,"top":0.31,"width":0.059027776,"height":0.026666667},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.8645833,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.8854167,"top":0.34444445,"width":0.015277778,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.9048611,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"bounds":{"left":0.92569447,"top":0.34444445,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.9458333,"top":0.3422222,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.9611111,"top":0.3422222,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","depth":4,"on_screen":true,"value":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.025,"top":0.06666667,"width":0.050694443,"height":0.034444444},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Expand Selected","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Collapse All","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Options","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
8957564869086018857
|
-7959665055215941403
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
11
72
1
4
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Copper;
use Carbon\Carbon;
use Exception;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Facades\Cache;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\CopperInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\FieldValue;
use Jiminny\Models\Crm\LayoutEntity;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\PlaybookCategory;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\UserRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\Copper\Api\Client;
use Jiminny\Services\Crm\Copper\Api\ClientFactory;
use Jiminny\Services\Crm\Copper\Exception\RequestFailedException;
use Jiminny\Services\Crm\Helpers\FilterJoinedParticipants;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Services\Crm\Copper\Traits\SearchesCrmEntities;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
class Service extends BaseService implements
CopperInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
use SearchesCrmEntities;
private const int NOTE_BODY_MAX_LENGTH = 3000000;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const array STANDARD_OPPORTUNITY_FIELDS = [
'monetary_value' => [
'label' => 'Value',
'available_on' => Field::OBJECT_OPPORTUNITY,
'type' => Field::TYPE_CURRENCY,
],
'pipeline_stage_id' => [
'label' => 'Stage',
'type' => Field::TYPE_PICKLIST,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
'close_date' => [
'label' => 'Close date',
'type' => Field::TYPE_DATE,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
'win_probability' => [
'label' => 'Win probability',
'type' => Field::TYPE_NUMBER,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
];
private const string UNSUPPORTED_OBJECT_TYPE = 'unsupported';
private const string OPPORTUNITY_STATUS_OPEN = 'Open';
private const string OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE = 'Opportunity import failed';
private const string RESOURCE_UPDATE_FAILED_ERROR_MESSAGE = 'Failed to update resource';
private FieldValueConverter $fieldValueConverter;
private ClientFactory $clientFactory;
private ?Client $copperClient = null;
public function __construct(
ClientFactory $clientFactory,
FieldValueConverter $fieldValueConverter,
private readonly UserRepository $userRepository,
private readonly ProspectPhotoPathService $prospectPhotoPathService,
private readonly CrmEntityRepository $crmEntityRepository
) {
parent::__construct();
$this->clientFactory = $clientFactory;
$this->fieldValueConverter = $fieldValueConverter;
}
public function getDisplayName(): string
{
return 'Copper';
}
/**
* Get the CRM entity repository (used by SearchesCrmEntities trait)
*/
protected function getCrmEntityRepository(): CrmEntityRepository
{
return $this->crmEntityRepository;
}
public function getMinimumApiVersion(): string
{
return Client::MIN_API_VERSION;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_COPPER);
}
public function setUser(User $user): void
{
$this->configureSentryScope($user);
$this->team = $user->getTeam();
$this->teamService->setTeam($user->getTeam());
$this->setConfiguration($user->getTeam()->getCrmConfiguration());
// Reset state.
$this->profile = $user->getProfile();
if (! $this->profile instanceof Profile) {
// Try to fetch their profile, maybe it was not yet imported?
$this->profile = $this->getProfile($user);
}
}
public function setConfiguration(Configuration $configuration): void
{
$this->config = $configuration;
$this->copperClient = $this->clientFactory->create($configuration);
if ($this->team === null) {
$this->team = $configuration->getTeam();
}
}
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return $this->fieldValueConverter->convertFromCrm($fieldType, $fieldValue);
}
private function mapObjectType(string $objectType): string
{
$objectType = strtolower($objectType);
switch ($objectType) {
case Field::OBJECT_TASK:
case Field::OBJECT_OPPORTUNITY:
case Field::OBJECT_LEAD:
$mappedType = $objectType;
break;
case Field::OBJECT_ACCOUNT:
$mappedType = 'company';
break;
case Field::OBJECT_CONTACT:
$mappedType = 'person';
break;
default:
$mappedType = self::UNSUPPORTED_OBJECT_TYPE;
break;
}
return $mappedType;
}
/**
* @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact
*/
protected function getFields(string $crmObject): array
{
$mappedObjectType = $this->mapObjectType($crmObject);
if (! $this->isSupportedObjectType($mappedObjectType)) {
return [];
}
$customFields = $this->copperClient->fields()->all();
$filteredFields = array_filter(
$customFields,
static fn ($field) => in_array($mappedObjectType, $field['available_on'], true)
);
return array_map(
fn (array $property) => [
'name' => $property['id'],
'label' => $property['name'],
'type' => $this->convertFieldType($property['data_type']),
],
$filteredFields
);
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {
$defaultFields = FieldDefinitions::defaultTaskFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldFilters = FieldDefinitions::taskFollowupFieldsFilter();
foreach ($fieldFilters as $data) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
public function syncFields(): void
{
$this->syncStandardFields();
$this->syncCustomFields();
}
public function syncField(Field $field): void
{
if ($field->getCrmProviderId() === 'type') {
/**
* This field is a special case, it is not a custom field and is not returned by the Copper API.
*
* The field is created manually during layout setup.
*
* @see getDefaultFields()
*
* There is a separate endpoint to get the activity types.
* @see importPicklistValues()
*/
return;
}
if ($field->getCrmProviderId() === 'pipeline_stage_id') {
// Not a custom type
return;
}
$crmField = $this->copperClient->fields()->find($field->getCrmProviderId());
$field->label = $crmField['name'];
$field->type = $this->convertFieldType($crmField['data_type']);
$field->save();
}
/**
* @param string $fieldType How the data should be input
*/
private function convertFieldType(string $fieldType): string
{
$fieldType = strtolower($fieldType);
switch ($fieldType) {
case 'dropdown':
$convertedType = Field::TYPE_PICKLIST;
break;
case 'string':
$convertedType = Field::TYPE_TEXT;
break;
case 'float':
case 'percentage':
$convertedType = Field::TYPE_NUMBER;
break;
case 'text':
$convertedType = Field::TYPE_TEXTAREA;
break;
case 'checkbox':
$convertedType = Field::TYPE_BOOLEAN;
break;
case Field::TYPE_DATE:
case Field::TYPE_CURRENCY:
case Field::TYPE_URL:
$convertedType = $fieldType;
break;
default:
$convertedType = Field::TYPE_UNSUPPORTED;
break;
}
return $convertedType;
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$fieldValues = [];
if ($field->object_type === 'opportunity' && $field->crm_provider_id === 'pipeline_stage_id') {
return $this->importFieldValuesForDealInsights($field);
}
$values = [];
if ($field->object_type === Field::OBJECT_TASK && $field->crm_provider_id === 'type') {
$activityTypes = $this->copperClient->activityTypes()->all();
/**
* We ignore "system" activity types, disabled activity types and the "Note" activity type.
*/
$activityTypes = array_filter(
$activityTypes['user'],
fn (array $activityType) => ! $activityType['is_disabled'] && $activityType['id'] !== 0
);
// Import all activity values.
$i = 0;
foreach ($activityTypes as $activityType) {
$values[] = [
'value' => $activityType['id'],
'label' => mb_strimwidth($activityType['name'], 0, Field::LABEL_MAX_LENGTH),
'sequence' => $i++,
];
}
} else {
// We just check for the field in the custom definitions.
$crmField = $this->copperClient->fields()->find($field->crm_provider_id);
// Import all values.
foreach ($crmField['options'] as $option) {
$values[] = [
'value' => $option['id'],
'label' => mb_strimwidth($option['name'], 0, 191),
'sequence' => $option['rank'],
];
}
}
// Take the existing set of field values.
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
// For all current values, upsert the field.
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
$key = array_search($value['value'], $fieldsToPurge, false);
if ($key !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
return $fieldValues;
}
/**
*
* @return FieldValue[]
*/
private function importFieldValuesForDealInsights(Field $field): array
{
$fieldValues = [];
$pipelines = $this->copperClient->pipelines()->all();
foreach ($pipelines as $pipeline) {
foreach ($pipeline['stages'] as $i => $dealStage) {
$fieldValues[] = $field->values()->updateOrCreate(
['value' => $dealStage['id']],
[
'label' => $dealStage['name'],
'sequence' => $i,
]
);
}
}
return $fieldValues;
}
/**
* @inheritdoc
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
$missingStage = null;
foreach ($types as $type) {
if ($type === Stage::TYPE_LEAD) {
$statuses = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leadStatuses()->all()
);
if (count($statuses) > 0) {
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => BusinessProcess::TYPE_LEAD,
], [
'team_id' => $this->team->id,
'name' => BusinessProcess::TYPE_LEAD,
'type' => BusinessProcess::TYPE_LEAD,
'is_selectable' => true,
]);
// A record type is really a clone of the business process, used to store which record uses which pipeline.
$this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => BusinessProcess::TYPE_LEAD,
], [
'team_id' => $this->team->id,
'name' => BusinessProcess::TYPE_LEAD,
'is_selectable' => true,
'business_process_id' => $businessProcess->id ?? null,
]);
$leadStatuses = [];
foreach ($statuses as $status) {
// Upsert all statuses for the team.
$status = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $status['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($status['name'], 0, 50),
'label' => mb_strimwidth($status['name'], 0, 191),
'type' => Stage::TYPE_LEAD,
'sequence' => $status['order'],
'is_selectable' => true,
]);
if ($missingStageName && $missingStageName === $status['id']) {
$missingStage = $status;
}
$leadStatuses[] = $status['id'];
}
$businessProcess->stages()->sync($leadStatuses);
}
} else {
// We create a business process to contain the pipeline, and later store all stages against it.
foreach ($this->copperClient->pipelines()->all() as $pipeline) {
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => $pipeline['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($pipeline['name'], 0, 150),
'type' => BusinessProcess::TYPE_OPPORTUNITY,
'is_selectable' => true,
]);
// A record type is really a clone of the business process, used to store which record uses which pipeline.
$this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => $pipeline['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($pipeline['name'], 0, 150),
'is_selectable' => true,
'business_process_id' => $businessProcess->id ?? null,
]);
$stages = [];
foreach ($pipeline['stages'] as $i => $dealStage) {
// Upsert all stages for the team.
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $dealStage['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($dealStage['name'], 0, 50),
'label' => mb_strimwidth($dealStage['name'], 0, 191),
'type' => Stage::TYPE_OPPORTUNITY,
'sequence' => $i,
'is_selectable' => true,
'probability' => $dealStage['win_probability'],
]);
if ($missingStageName && $missingStageName === $dealStage['id']) {
$missingStage = $stage;
}
$stages[] = $stage['id'];
}
$businessProcess->stages()->sync($stages);
}
}
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$cpLeads = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->paginate([
'minimum_modified_date' => $since->timestamp,
'sort_by' => 'date_modified',
])
);
foreach ($cpLeads as $cpLead) {
// Only sync if previously imported.
if ($this->hasLead($cpLead['id']) === false) {
$this->importLead($cpLead);
$syncCount++;
}
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
$cpLead = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->find($crmId)
);
if (\count($cpLead) === 0) {
return null;
}
return $this->importLead($cpLead);
}
/**
* @inheritdoc
*/
private function importLead($crmData): ?Lead
{
$countryCode = null;
if (! empty($crmData['address']) && isset($crmData['address']['country'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$mobilePhone = $parsedNumber = null;
if (! empty($crmData['phone_numbers'])) {
foreach ($crmData['phone_numbers'] as $phoneNumber) {
if ($phoneNumber['category'] === 'mobile') {
$mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);
} else {
$parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);
}
}
}
$name = $crmData['name'];
if (empty($crmData['company_name'])) {
$company = 'Unknown';
} else {
$company = mb_strimwidth($crmData['company_name'], 0, 191);
}
$domain = null;
if (empty($crmData['websites']) === false) {
$domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$email = null;
if (empty($crmData['email']) === false) {
$email = mb_strimwidth($crmData['email']['email'], 0, 80);
}
$stage = $this->config
->stages()
->where('crm_provider_id', (string) $crmData['status_id'])
->where('type', Stage::TYPE_LEAD)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status_id']);
}
if (! $stage instanceof Stage) {
return null;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($name, 0, 191),
'company' => $company,
'domain' => $domain,
'title' => $crmData['title'] ? mb_strimwidth($crmData['title'], 0, 128) : null,
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'mobile_phone' => $mobilePhone,
'stage_id' => $stage->id,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Lead::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'country_code' => $countryCode,
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$cpAccounts = $this->copperClient->accounts()->paginate([
'minimum_modified_date' => $since->timestamp,
'sort_by' => 'date_modified',
]);
foreach ($cpAccounts as $cpAccount) {
// Only sync if previously imported.
if ($this->hasAccount($cpAccount['id'])) {
$this->importAccount($cpAccount);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
$cpAccount = $this->copperClient->accounts()->find($crmId);
if (empty($cpAccount)) {
return null;
}
return $this->importAccount($cpAccount);
}
/**
* @inheritdoc
*/
private function importAccount($crmData): Account
{
$countryCode = null;
if (empty($crmData['address']) === false && $crmData['address']['country']) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$name = $crmData['name'];
$parsedNumber = null;
foreach ($crmData['phone_numbers'] as $phoneNumber) {
$parsedNumber = parsePhoneNumber($countryCode, $phoneNumber['number']);
}
$domain = null;
if (empty($crmData['websites']) === false) {
$domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Account::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'country_code' => $countryCode,
'domain' => $domain,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->copperClient,
]);
$strategies = $strategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
try {
foreach ($strategies as $syncStrategy) {
foreach ($syncStrategy->fetchOpportunities($parameters) as $opportunityData) {
$this->importOpportunity($opportunityData);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
$this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => $exception->getMessage(),
]);
}
return $syncCount;
}
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->copperClient,
]);
$strategy = $strategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
$parameters['crm_id'] = $crmId;
$cpOpportunity = $strategy->fetchOpportunities($parameters);
return $this->importOpportunity($cpOpportunity);
}
private function importOpportunity($crmData): ?Opportunity
{
$companyId = (string) $crmData['company_id'];
if (empty($companyId)) {
$this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => 'No company id',
]);
return null;
}
$account = $this->config->accounts()->where('crm_provider_id', $companyId)->first();
if ($account === null) {
$account = $this->syncAccount($companyId);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', (string) $crmData['pipeline_id'])
->first();
if ($businessProcess === null) {
// It is possible for some deals to not be in a pipeline.
$this->logger->warning(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => 'Missing pipeline',
]);
return null;
}
$stage = $businessProcess
->stages()
->where('crm_provider_id', (string) $crmData['pipeline_stage_id'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
$this->logger->info('Stage not found, importing', [
'pipeline_id' => $crmData['pipeline_id'],
'stage_id' => $crmData['pipeline_stage_id'],
]);
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['pipeline_stage_id']);
}
$recordType = $businessProcess->recordTypes()->first();
$closeDate = null;
$isClosed = $crmData['status'] !== self::OPPORTUNITY_STATUS_OPEN;
if ($crmData['close_date']) {
$closeDate = Carbon::parse($crmData['close_date'])->format('Y-m-d');
}
$data = [
'team_id' => $this->team->getId(),
'account_id' => $account->id,
'user_id' => $profile->user_id ?? null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($crmData['name'], 0, 128),
'value' => $crmData['monetary_value'],
'currency_code' => CurrencyFormatter::formatCode($crmData['monetary_unit']),
'close_date' => $closeDate,
'is_closed' => $isClosed,
'is_won' => $crmData['status'] === 'Won',
'stage_id' => $stage->id,
'record_type_id' => $recordType->id ?? null,
'remotely_created_at' => $crmData['date_created'],
];
/** @var Opportunity $opportunity */
$opportunity = $this->config
->opportunities()
->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data)
;
// import external fields into crm_field_data if present
$dealInsightsFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData($crmData, $dealInsightsFields, $opportunity->id);
return $opportunity;
}
/**
* @param array<string, mixed> $opportunityData
* @param string[] $dealInsightsFields
*/
public function importOpportunityCrmFieldData(
array $opportunityData,
array $dealInsightsFields,
int $opportunityId
): void {
foreach ($dealInsightsFields as $fieldName) {
$field = $this->config->fields()->with('entities')
->where('crm_provider_id', $fieldName)
->where('object_type', Field::OBJECT_OPPORTUNITY)
->first();
if (! $field instanceof Field) {
$this->logger->warning('Field not found', [
'field' => $fieldName,
'opportunity_id' => $opportunityId,
]);
continue;
}
$entity = $field->getEntities()->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$fieldValue = $this->extractFieldValue($opportunityData, $fieldName);
$normalizedValue = $this->normalizeValue($field->getType(), (string) $fieldValue, true);
$field->data()
->updateOrCreate([
'crm_layout_entity_id' => $entity->id,
'crm_field_id' => $field->id,
'object_type' => 'opportunity',
'object_id' => $opportunityId,
], ['value' => $normalizedValue])
;
}
}
/**
* @inheritdoc
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$cpContacts = $this->copperClient->contacts()->paginate([
'minimum_interaction_date' => $since->timestamp,
'sort_by' => 'date_modified',
]);
foreach ($cpContacts as $cpContact) {
// Only sync if previously imported.
if ($this->hasContact($cpContact['id'])) {
$this->importContact($cpContact);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
throw $exception;
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncContact(string $crmId): ?Contact
{
$cpContact = $this->copperClient->contacts()->find($crmId);
if (empty($cpContact)) {
return null;
}
return $this->importContact($cpContact);
}
/**
* @inheritdoc
*/
private function importContact($crmData): Contact
{
$account = null;
if ($crmData['company_id']) {
$account = $this->team
->crm
->accounts()
->where('crm_provider_id', (string) $crmData['company_id'])
->first();
if ($account === null) {
$account = $this->syncAccount($crmData['company_id']);
}
}
$countryCode = null;
if (empty($crmData['address']) === false && $crmData['address']['country']) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$mobilePhone = $parsedNumber = null;
foreach ($crmData['phone_numbers'] as $phoneNumber) {
if ($phoneNumber['category'] === 'mobile') {
$mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);
} else {
$parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);
}
}
$email = null;
if (empty($crmData['emails']) === false) {
$email = mb_strimwidth($crmData['emails'][0]['email'], 0, 80);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => $crmData['name'],
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'mobile_phone' => $mobilePhone ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'title' => $crmData['title'],
'country_code' => $countryCode,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Contact::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function buildContactPhone(?string $countryCode, ?string $number): ?array
{
if ($number) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($number, 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
return $parsedNumber;
}
private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string
{
return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;
}
/**
* @inheritdoc
*/
public function syncOrganization(): void
{
$organization = $this->copperClient->organisation()->all();
if ($this->config->crm_provider_id !== $organization['id']) {
$this->config->update(['crm_provider_id' => $organization['id']]);
}
}
private function syncCustomFields(): void
{
foreach ($this->getFieldTypes() as $fieldType) {
$currentFields = $this->getFields($fieldType);
foreach ($currentFields as $field) {
/** @var Field $field */
$field = $this->config->fields()->updateOrCreate([
'crm_provider_id' => $field['name'],
'object_type' => $fieldType,
], [
'label' => mb_strimwidth($field['label'], 0, Field::LABEL_MAX_LENGTH),
'type' => $field['type'],
]);
if ($field->getType() === Field::TYPE_PICKLIST) {
$this->importPicklistValues($field);
}
}
}
$this->config->save();
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
parent::OBJECT_LEAD,
parent::OBJECT_ACCOUNT,
parent::OBJECT_CONTACT,
parent::OBJECT_OPPORTUNITY,
];
}
/**
* @inheritdoc
*/
public function syncProfiles(?User $userToSearch = null): ?Profile
{
$profiles = $this->copperClient->users()->all();
foreach ($profiles as $profile) {
$user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);
// Only import profiles for users we have locally.
if ($user) {
$profile = $user->crmProfile()->updateOrCreate([
'crm_configuration_id' => $this->config->id,
'crm_provider_id' => $profile['id'],
]);
if ($userToSearch && $userToSearch->id === $user->id) {
return $profile;
}
}
}
return null;
}
/**
* @inheritdoc
*/
public function syncProfileFields(): void
{
$fieldTypes = [
'task',
'lead',
'account',
'contact',
'opportunity',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields(ucfirst($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))
);
if (\count($changedFields) > 0) {
$fields = implode(',', $newFields);
$this->logger->debug(
ucfirst($fieldType)
. ' fields changed from '
. $this->profile->{$fieldType . '_fields'}
. ' to: '
. $fields
);
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (\Exception $exception) {
$this->logger->error('No access to ' . $fieldType . ' object, skipping...');
continue;
}
}
$this->profile->save();
}
/**
* @inheritdoc
*/
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$scopeValues = array_map(fn ($scope) => is_string($scope) ? $scope : $scope->value, $scopes);
$cacheKey = sprintf('copper-search-%d-%s-%s-%d-%d', $this->team->id, $name, implode('-', $scopeValues), $count, $offset);
return Cache::remember($cacheKey, 300, function () use ($name, $scopes, $count, $offset) {
// Try local search first
$localResults = $this->searchLocally($name, $scopes, $count, $offset);
// If no local results, fall back to remote API search
if (empty($localResults)) {
return $this->searchRemotely($name, $scopes, $count, $offset);
}
return $localResults;
});
}
/**
* @inheritdoc
*/
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$params = [
'company_ids' => [$account->crm_provider_id],
'status_ids' => [0], // The integer values are 0, 1, 2, 3, for "Open", "Won", "Lost", and "Abandoned".
'sort_by' => 'date_modified',
'sort_direction' => 'desc',
];
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort_by'] = 'date_modified';
$params['sort_direction'] = 'desc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort_by'] = 'date_created';
$params['sort_direction'] = 'desc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort_by'] = 'date_created';
$params['sort_direction'] = 'asc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort_by'] = 'date_modified';
$params['sort_direction'] = 'desc';
$params['status_ids'] = [0, 1, 2, 3];
}
$cpOpportunities = $this->copperClient->opportunities()->search($params);
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
foreach ($cpOpportunities as $cpOpportunity) {
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', (string) $cpOpportunity['pipeline_id'])
->first();
if ($businessProcess === null) {
// Import it.
$businessProcess = $this->importStages(
[Stage::TYPE_OPPORTUNITY],
$cpOpportunity['pipeline_stage_id']
);
}
$stage = $businessProcess
->stages()
->where('crm_provider_id', (string) $cpOpportunity['pipeline_stage_id'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $cpOpportunity['pipeline_stage_id']);
}
$recordType = $businessProcess->recordTypes()->first();
$record = [
'crmId' => $cpOpportunity['id'],
'name' => $cpOpportunity['name'],
'value' => currency_format($cpOpportunity['monetary_value'], $cpOpportunity['monetary_unit']),
'won' => $cpOpportunity['status'] === 'Won',
'stage' => [
'id' => $stage->id_string,
'name' => $stage->name,
],
'recordType' => [
'id' => $recordType->id_string,
'name' => $recordType->name,
],
];
if ($ownerId && isset($cpOpportunity['assignee_id']) && $cpOpportunity['assignee_id'] === $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
/**
* @inheritdoc
*/
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = $cpTasks = [];
switch ($objectType) {
case 'lead':
$cpTasks = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->relatedTasks($objectId)
);
break;
case 'account':
$cpTasks = $this->copperClient->accounts()->relatedTasks($objectId);
break;
case 'contact':
if ($opportunityId) {
$cpTasks = $this->copperClient->opportunities()->relatedTasks($opportunityId);
} elseif ($objectType === 'contact') {
$cpTasks = $this->copperClient->contacts()->relatedTasks($objectId);
}
break;
}
foreach ($cpTasks as $cpTask) {
// We only get the ID itself returned, so pull out the full object.
try {
$cpTask = $this->copperClient->tasks()->find($cpTask['id']);
} catch (Exception $exception) {
$this->logger->error('[Copper] Error fetching task', [
'resource_id' => $cpTask['id'],
'error' => $exception->getMessage(),
]);
continue;
}
// Only allow open tasks.
if ($cpTask['status'] === 'Open') {
$data[] = [
'crmId' => $cpTask['id'],
'subject' => $cpTask['name'],
'due' => $cpTask['due_date']
? Carbon::createFromTimestamp($cpTask['due_date'])->format('Y-m-d\TH:i:sO')
: null,
'type' => null,
];
}
}
return $data;
}
/**
* Try to find email address in CRM service
*
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchExactlyByEmail(string $email, ?int $userId = null): ?array
{
$cpObjectType = 'contact';
$cpObjects = $this->copperClient->contacts()->search([
'emails' => $email,
'sort_by' => 'date_modified',
'sort_direction' => 'desc',
]);
if (empty($cpObjects)) {
$cpObjectType = 'lead';
$cpObjects = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->search([
'emails' => ...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45374
|
1625
|
24
|
2026-05-14T14:33:21.074066+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769201074_m1.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl100% C•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTest v8• Thu 14 May 17:33:20* :QProjectv:=custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php© FieldDefinitions.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php=laravel.log© FieldValueConverter.php• DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© Service.php© DecorateActivity.phpSF [jiminny@localhost]> D CrmObjects© Salesforce/Service.php© LogActivityTrait.phpPipedrive/Service.php© Close/Service.phpCopper/Service.php XA HS_local [jiminny@localho:W• DecorateActivity© PlainTextDecorateActivity.phpT ActivityPlaybookTrait.php© CrmHelperRepository.phpAccountController.php4 console [QAI PROD] X18© BaseDecorateActivity.php© PlainTextDecorateActivity.plT IntegrationAppTrait.php.env.stagingE.env© DetachActivityObject.phpRematchActivityOnCrmObjectDetach.php4 console [PROD]> D Dummyv Helpers52T ActivityPlaybookTrait.php1664© Arraylterator.php1678© MatchActivityCrmData.php© Client.php© HubspotPaginationService.phpclass Service extends BaseService implementsprivate function buildCallPayload(Activity $activity): Activityaetarts'= $tnis->generateActIvityuescription(sactivity),© HandleHubspotRateLimit.phpA console (EU]811 472 M1 м4 лT ConnectionStateTrait.php1679© CrmHelperRepository.php16801):• else {© FilterJoinedParticipants.php1681+ OpportunitySyncableFieldsT1682v D Hubspot1683• AccountSyncStrategy1684DGo jiminny084143 ×4 л215•m_layout_id =2162,1661, 66799,66217itn(Sthis-2getCrmType(SactivitX->categacV2mmm0ulVnt218$message = sprintf( format: '[Copper] Invalid CRM Activity Type: %s', $activity->category->getName()):_* 219=220=221.id = 33;throw new CrmException(Smessage,code: 400);> OJ Actions |1685• ContactSyncStrategy1686> ODTO1687D Fields1688› O Journal1689D Metadata1698code: 400):v C OpportunitySyncStrategy1691› D Concerns1692© HubspotLastModifiedByF 1693© HubspotLastModifiedCre 1694© HubspotLastModifiedCre 1695© HubspotLastModifiedOpe 1696© HubspotLastModifiedSyn 169711698if (Sthis->getCrmType($activity->category)->value === null) {=223$messagel = sprintf( format: '[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName224225Extract Surround //tnrow new Crmexception(smessage,=226=227228229=: 230|231232233V=234id THEN •(own© HubspotSingleSyncStrate// Just create an activity.$cpActivity = $this->copperClient-›activities()->create(['user_id' => $this->profile->crm_provider_id,'activity_date' => $activity->scheduled_start_time->timestamp,'parent' => $this->convertActivityAssociations(Sactivity),'type' => $this->convertActivityType(Sactivity->category),'details' => $this->generateActivityDescription(Sactivity),hubspot":-= 11512582;© HubspotSyncStrategyBa: 16991):© HubspotWebhookBatchS1700v [ Pagination1701• HubspotPaginationServic 1702Sactivity->crm_provider_id = $cpActivity['id'];Sactivity->save):A DaninatinnCanfin nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams1688:29 (8 chars)UTF-8Ca 4 spaces...
|
NULL
|
-1341745411075778780
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl100% C•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTest v8• Thu 14 May 17:33:20* :QProjectv:=custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php© FieldDefinitions.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php=laravel.log© FieldValueConverter.php• DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© Service.php© DecorateActivity.phpSF [jiminny@localhost]> D CrmObjects© Salesforce/Service.php© LogActivityTrait.phpPipedrive/Service.php© Close/Service.phpCopper/Service.php XA HS_local [jiminny@localho:W• DecorateActivity© PlainTextDecorateActivity.phpT ActivityPlaybookTrait.php© CrmHelperRepository.phpAccountController.php4 console [QAI PROD] X18© BaseDecorateActivity.php© PlainTextDecorateActivity.plT IntegrationAppTrait.php.env.stagingE.env© DetachActivityObject.phpRematchActivityOnCrmObjectDetach.php4 console [PROD]> D Dummyv Helpers52T ActivityPlaybookTrait.php1664© Arraylterator.php1678© MatchActivityCrmData.php© Client.php© HubspotPaginationService.phpclass Service extends BaseService implementsprivate function buildCallPayload(Activity $activity): Activityaetarts'= $tnis->generateActIvityuescription(sactivity),© HandleHubspotRateLimit.phpA console (EU]811 472 M1 м4 лT ConnectionStateTrait.php1679© CrmHelperRepository.php16801):• else {© FilterJoinedParticipants.php1681+ OpportunitySyncableFieldsT1682v D Hubspot1683• AccountSyncStrategy1684DGo jiminny084143 ×4 л215•m_layout_id =2162,1661, 66799,66217itn(Sthis-2getCrmType(SactivitX->categacV2mmm0ulVnt218$message = sprintf( format: '[Copper] Invalid CRM Activity Type: %s', $activity->category->getName()):_* 219=220=221.id = 33;throw new CrmException(Smessage,code: 400);> OJ Actions |1685• ContactSyncStrategy1686> ODTO1687D Fields1688› O Journal1689D Metadata1698code: 400):v C OpportunitySyncStrategy1691› D Concerns1692© HubspotLastModifiedByF 1693© HubspotLastModifiedCre 1694© HubspotLastModifiedCre 1695© HubspotLastModifiedOpe 1696© HubspotLastModifiedSyn 169711698if (Sthis->getCrmType($activity->category)->value === null) {=223$messagel = sprintf( format: '[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName224225Extract Surround //tnrow new Crmexception(smessage,=226=227228229=: 230|231232233V=234id THEN •(own© HubspotSingleSyncStrate// Just create an activity.$cpActivity = $this->copperClient-›activities()->create(['user_id' => $this->profile->crm_provider_id,'activity_date' => $activity->scheduled_start_time->timestamp,'parent' => $this->convertActivityAssociations(Sactivity),'type' => $this->convertActivityType(Sactivity->category),'details' => $this->generateActivityDescription(Sactivity),hubspot":-= 11512582;© HubspotSyncStrategyBa: 16991):© HubspotWebhookBatchS1700v [ Pagination1701• HubspotPaginationServic 1702Sactivity->crm_provider_id = $cpActivity['id'];Sactivity->save):A DaninatinnCanfin nhnWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams1688:29 (8 chars)UTF-8Ca 4 spaces...
|
45371
|
NULL
|
NULL
|
NULL
|
|
45373
|
1626
|
16
|
2026-05-14T14:33:18.940443+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769198940_m2.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Jiminny... ~ActivityFilesLater@ jiminny-x-integrat Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preuiew in sact[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pmv Q SearchDate ModifiedYesterday at 13.3Yesterday at 13:36Yesterday at 13:36Yesterday at 13.30Yesterdav at 13:35Yesterday at 13:34Yesterday at 13:34Yesterdav at 13:3kYesterday at 13:33Yesterday at 13.32Yesterdav at 13:31resterday at 15:30Yesterdav at 13:30Yesterday at 13:29Yesterday at 13:29Yesterday at 13:28Yecterdav at 12:28resterday at 13-21Yesterdav at 13:26Yesterday at 13:26Yesterday at 13:25Yesterday at 13:25Voctorday at 12:01Yesterday at 13.23Yesterdav at 13:22resterady al 15.clYesterday at 13:20Yesterday at 13.19Yecterdav at 12:19Yesterdav at 13:18Yesterday at 13-1/Yesterdav at 13:17Yesterday at 13:16Yesterday at 13:15Yecterdav at 12:15Yesterday at 13.14Yecterdav at 13:10Yesterday at 13:13Yesterday at 13:12Yoctorday at 12:11Yesterday at 13.10Yecterdav at 12:10Yesterdav at 13:09Yesterdav at 13:08v Size23 KB9 KB13 Kb16 KE17 KB29 KB16 K:12 KB9 KEIKBn8 KBI37 KB10 KB7 KE8 KB9 KB8 KB172 KR14 KB13 KB9 KE18 KB12 KB10 KBI16 KB6 KB6KB12 KE23 KB8 KB16 K:11 KB20 KP34 KB10 KB7 K:5 KB11 KB26 KBMPEG-4 movieMPEG-4 movieMPEG-4 movieMPEG-4 movieMPE0"4 movieMDSG-A movieMP2G-4 movieMPEG-4 movieMPEG"4 movieMPEG-4 movieMoEeh movioMPEG-4 movieMPEG-1 movieMPEG-4 movieMPEG-4 movieMPEG-4 movieMPEG-4 movieMDEG.A movicMPEG-4 movieMPEG-4 movieMPEG-4 movieMPEG-4 movieMDEC A movidMPEG-4 movieMDEG-A movieMPEG-4 movieMPEG-4 movieMDEC.A moviaMPEG-4 movie111 KC102 KB88 KBMDEG-A moviaMPEG-4 movie59 KB1MPEG-A movie98 KB MPEG-4 movie97 KB66 K3MPEG-4 movieMDEG.A movioAAKP93 KB/8 KBMPEG-4 movie50 KгMDEG-A movid58 KBMPEG-4 movie27 KB7KBMPEG-4 movieAl Notes: OffLeave• • CFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc tolde0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esv1 config.vmlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•AlfredwPmazanoko.imnaoc.YWIfана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentK:PDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.49 GB availabld• Inu 14 May 1/.33.10Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 г+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
-2134816872056375722
|
NULL
|
visual_change
|
ocr
|
NULL
|
Jiminny... ~ActivityFilesLater@ jiminny-x-integrat Jiminny... ~ActivityFilesLater@ jiminny-x-integrati• plattorm-inner-teamE Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity lab# engineering# general#jiminny-bgac nlattorm-nckets# product launches# random# releases# sofia-officed sunport# thank-yous# the people of iimi... Direct messages• 8la 62% Galya Dimitrovavasil VasilevM Stefka StovanovaSg: Todor StamatovMario GeorgievNiudlay lanay. James Graham "* Stoyan Tanevo Stelivan Georgiev( Petko Kashinski*. Lukas Kovali...::: AnnsToastS lira Gloud6d Huddle with Aneliva Angelova* Aneliya Angelova &• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някъде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preuiew in sact[HubSpotl Optimise CRM rematct(7 OpenRosdy for OA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira* SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle (LIVE 4:06 PMAneliva Angelova is here toolAneliva Angelova 4:44 PN11512582Lukas Kovalik M 5.16 PNcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-vne' annlication/ison'--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIr7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pmv Q SearchDate ModifiedYesterday at 13.3Yesterday at 13:36Yesterday at 13:36Yesterday at 13.30Yesterdav at 13:35Yesterday at 13:34Yesterday at 13:34Yesterdav at 13:3kYesterday at 13:33Yesterday at 13.32Yesterdav at 13:31resterday at 15:30Yesterdav at 13:30Yesterday at 13:29Yesterday at 13:29Yesterday at 13:28Yecterdav at 12:28resterday at 13-21Yesterdav at 13:26Yesterday at 13:26Yesterday at 13:25Yesterday at 13:25Voctorday at 12:01Yesterday at 13.23Yesterdav at 13:22resterady al 15.clYesterday at 13:20Yesterday at 13.19Yecterdav at 12:19Yesterdav at 13:18Yesterday at 13-1/Yesterdav at 13:17Yesterday at 13:16Yesterday at 13:15Yecterdav at 12:15Yesterday at 13.14Yecterdav at 13:10Yesterday at 13:13Yesterday at 13:12Yoctorday at 12:11Yesterday at 13.10Yecterdav at 12:10Yesterdav at 13:09Yesterdav at 13:08v Size23 KB9 KB13 Kb16 KE17 KB29 KB16 K:12 KB9 KEIKBn8 KBI37 KB10 KB7 KE8 KB9 KB8 KB172 KR14 KB13 KB9 KE18 KB12 KB10 KBI16 KB6 KB6KB12 KE23 KB8 KB16 K:11 KB20 KP34 KB10 KB7 K:5 KB11 KB26 KBMPEG-4 movieMPEG-4 movieMPEG-4 movieMPEG-4 movieMPE0"4 movieMDSG-A movieMP2G-4 movieMPEG-4 movieMPEG"4 movieMPEG-4 movieMoEeh movioMPEG-4 movieMPEG-1 movieMPEG-4 movieMPEG-4 movieMPEG-4 movieMPEG-4 movieMDEG.A movicMPEG-4 movieMPEG-4 movieMPEG-4 movieMPEG-4 movieMDEC A movidMPEG-4 movieMDEG-A movieMPEG-4 movieMPEG-4 movieMDEC.A moviaMPEG-4 movie111 KC102 KB88 KBMDEG-A moviaMPEG-4 movie59 KB1MPEG-A movie98 KB MPEG-4 movie97 KB66 K3MPEG-4 movieMDEG.A movioAAKP93 KB/8 KBMPEG-4 movie50 KгMDEG-A movid58 KBMPEG-4 movie27 KB7KBMPEG-4 movieAl Notes: OffLeave• • CFavourites• jiminny• Recents* ApplicationsiCloud• iCloud Drive992 Svnc tolde0 DXP4800PLUS-B5F49 Networl• CRMI• Orange• Red|• Yellow• Green• Purple•) All lags..IhlDownloadsNameLoom.pkgAlfred copv.alfredoreterences=KeychronAssist-1.0.2 (1).dmeKeychronAssist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip• Transcript.pd→mage U.loge1 Orioninstaller.dma_image.jpg- image (2).1pc• ПO-22221726037035-004-001_ORGES.pdf%D0%9F%D0%9E-22221726037035-004-001 archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterencesСE 060209С О000000026571172 CWICT 0Р70501260015900 ndt= 27022026_0000000026574472_ SWIFT_ [IBAN].pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001reportxmmi=pdt.odiB pdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonlKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst aid_notes_complete.docxrenortl2).esv1 config.vmlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.isonnokc.901a6502.6667.A62h-062 ccu•AlfredwPmazanoko.imnaoc.YWIfана Ковалик.jpg•искане даниел Ковалик..pg• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик iро• Dhotac 2.001Q SearchKind00,4 MD55.9 MBinstdlle..dckageAlfred...ferences10,1 MB10,1 MBIL MBDisk ImageDisk ImageLiP archive6.6 MBZIp archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDE Document140 KbZIP archive148 KВ148 KB122 KBZIP archivelZIP archiveXML document111 KBAlfred...ferences94 KBDDE Documont92 KBPDr DocumentK:PDF Document91 KB91 KBXML document30 KBn0kpDDE Nocumont28 KBPDF Document28 KRPDE Document28 KB27 KBDocument14 KB11 KB6 KB6KBJSONINCV NacumontZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBVAMI dosumon1 KB029 buteccSV Documenthttlicence183 bytesZero butesJSONAlfrod foronso!Zero bytesFolde1.9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.49 GB availabld• Inu 14 May 1/.33.10Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 ,Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3712 Goh 2006 9t 11:5 A1Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nau 2025 г+ 17:506 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0419 Mar 2026 at 11:55|10 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:362616 Oct 2025 aт 16:0122 Aar 2026 at 12:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
45372
|
NULL
|
NULL
|
NULL
|
|
45372
|
1626
|
15
|
2026-05-14T14:33:15.868866+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769195868_m2.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeave~ (Q SearchDate ModifiedYesterday at 13:37Yesterday at 13.30Yesterday at 13:35resterady al 15.54Yesterdav at 13:34Yesterday at 13:33Yesterday at 13:33Yesterday at 13:32Yesterday at 13:32resterday at 15.3Yesterdav at 13:30Yesterday at 13:30Yesterday at 13:29Yesterday at 13:29Yesterday at 13:28Yesterday at 13.21Yesterday at 13:27Yesterday at 13:26Yesterday at 13:26Yesterday at 13:25Yesterday at 13.24Yecterdav at 12:22Yesterday at 13:22resterday at 13.2lYesterday at 13:20Yesterday at 13.19Yecterdav at 12:10Yesterday at 13:18resterday at 13.10Yesterday at 13:16Yesterday at 13:15Yesterday at 13.14Yesterday at 13:13Yesterday at 13:13Yesterdav at 13:12Yesterday at 13:12Yesterday at 13.11Yecterdav at 12:10Yesterday at 13:10Yesterdav at 13:09Yesterday at 13:0871 KBMPEG-4 movie23 KBMPEG-4 movieMPEG-4 movie13 KE16 KB17 KBMPEO"4 movie29 KBMPEG-4 movie6 KBMPEG-4 movie12 KB9KBMPEG-4 movie7 KBMPEG-4 movie8 KB37 KBMPEO-4 moVie10 K:MPEG-4 movie7 KBMPEG-4 movie8 KB9K:MPEG-4 movie8 KBMPEG-4 movie72 KB14 KbMPEG-4 movie13 KEMPEG-4 movie9 KBMPEG-4 movie18 KBMPEG-4 movie12 K:MPEG-4 movie10 KBMPEG-4 movie16 KB6 KBMPEG-4 movieMPEG-4 movie12 KBMPEG-4 movie23 KBMPEG-4 movie8 K:MPEG-4 movie6 KBMPEG-4 movie6 KB11 KBMPEG-4 movie11 KPMDEG-A movid20 KBMPEG-4 movie34 KBMPEG-4 movie10 KI.MPEG-4 movie7KBMPEG-4 movie5 KB11 KBMPEG-4 movie26 KBMPEG-4 movie111 KB102 KBMPEG-4 movie88 KEMPEG-A movid59 KBMPEG-4 movie98 KB97 K866 KBMPEG-4 movie.MPEG-4 movie44 KB93 KBMPEG-4 movie78 KPMPEG-A movie50 KBMPEG-4 movie58 KB27 KEMPEG-4 movie7KBMPEG-4 movie• 0FavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderLocationsQ DXP4800PLUS-B5FA@ Network|• CRM• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip→mage U.loge1 Orioninstaller.dma- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zipD report(2) xmlAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfB Rovaix Famly Treo gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxconfig.ymlIteration run Search HS.postman_collection.json--report(1).csvm licence hettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 Kb148 KВ148 KB122 KB111 KB94 KBZIP archiveZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentPDF Document91 KB91 KB30 KB29 KBXML documentPDF Document28 KB28 KR28 KB27 KB14 KB11 KB6 KB6KB5KR4 KB3 KBPDF DocumentPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..umentWindo...n imageword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytes1,9 MB1,8 MB17 MB1,7 MBFoldeColdorJPEG imageJPEG ImageJPEG imageJPEG imageColdo1 of 58 selected, 8.5 GB availab!i• Inu 14 May 1/.33.10Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
-6205760700402177095
|
NULL
|
visual_change
|
ocr
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeave~ (Q SearchDate ModifiedYesterday at 13:37Yesterday at 13.30Yesterday at 13:35resterady al 15.54Yesterdav at 13:34Yesterday at 13:33Yesterday at 13:33Yesterday at 13:32Yesterday at 13:32resterday at 15.3Yesterdav at 13:30Yesterday at 13:30Yesterday at 13:29Yesterday at 13:29Yesterday at 13:28Yesterday at 13.21Yesterday at 13:27Yesterday at 13:26Yesterday at 13:26Yesterday at 13:25Yesterday at 13.24Yecterdav at 12:22Yesterday at 13:22resterday at 13.2lYesterday at 13:20Yesterday at 13.19Yecterdav at 12:10Yesterday at 13:18resterday at 13.10Yesterday at 13:16Yesterday at 13:15Yesterday at 13.14Yesterday at 13:13Yesterday at 13:13Yesterdav at 13:12Yesterday at 13:12Yesterday at 13.11Yecterdav at 12:10Yesterday at 13:10Yesterdav at 13:09Yesterday at 13:0871 KBMPEG-4 movie23 KBMPEG-4 movieMPEG-4 movie13 KE16 KB17 KBMPEO"4 movie29 KBMPEG-4 movie6 KBMPEG-4 movie12 KB9KBMPEG-4 movie7 KBMPEG-4 movie8 KB37 KBMPEO-4 moVie10 K:MPEG-4 movie7 KBMPEG-4 movie8 KB9K:MPEG-4 movie8 KBMPEG-4 movie72 KB14 KbMPEG-4 movie13 KEMPEG-4 movie9 KBMPEG-4 movie18 KBMPEG-4 movie12 K:MPEG-4 movie10 KBMPEG-4 movie16 KB6 KBMPEG-4 movieMPEG-4 movie12 KBMPEG-4 movie23 KBMPEG-4 movie8 K:MPEG-4 movie6 KBMPEG-4 movie6 KB11 KBMPEG-4 movie11 KPMDEG-A movid20 KBMPEG-4 movie34 KBMPEG-4 movie10 KI.MPEG-4 movie7KBMPEG-4 movie5 KB11 KBMPEG-4 movie26 KBMPEG-4 movie111 KB102 KBMPEG-4 movie88 KEMPEG-A movid59 KBMPEG-4 movie98 KB97 K866 KBMPEG-4 movie.MPEG-4 movie44 KB93 KBMPEG-4 movie78 KPMPEG-A movie50 KBMPEG-4 movie58 KB27 KEMPEG-4 movie7KBMPEG-4 movie• 0FavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderLocationsQ DXP4800PLUS-B5FA@ Network|• CRM• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip→mage U.loge1 Orioninstaller.dma- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zipD report(2) xmlAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfB Rovaix Famly Treo gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxconfig.ymlIteration run Search HS.postman_collection.json--report(1).csvm licence hettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 Kb148 KВ148 KB122 KB111 KB94 KBZIP archiveZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentPDF Document91 KB91 KB30 KB29 KBXML documentPDF Document28 KB28 KR28 KB27 KB14 KB11 KB6 KB6KB5KR4 KB3 KBPDF DocumentPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..umentWindo...n imageword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytes1,9 MB1,8 MB17 MB1,7 MBFoldeColdorJPEG imageJPEG ImageJPEG imageJPEG imageColdo1 of 58 selected, 8.5 GB availab!i• Inu 14 May 1/.33.10Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45371
|
1625
|
23
|
2026-05-14T14:33:10.101263+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769190101_m1.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelplhl•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTestv100% <8• Thu 14 May 17:33:09QProjectv= custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php© FieldDefinitions.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php=laravel.log© FieldValueConverter.php• DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© Service.php© DecorateActivity.phpSF [jiminny@localhost]> D CrmObjects© Salesforce/Service.php© LogActivityTrait.phpPipedrive/Service.phpClose/Service.phpCopper/Service.php XA HS_local [jiminny@localho:W• DecorateActivity© PlainTextDecorateActivity.phpT ActivityPlaybookTrait.phpCrmHelperRepository.phpAccountController.php4 console [QAI PROD] X18© BaseDecorateActivity.php© PlainTextDecorateActivity.plT IntegrationAppTrait.php.env.stagingE.env© DetachActivityObject.phpRematchActivityOnCrmObjectDetach.php4 console [PROD]> D Dummy© HandleHubspotRateLimit.phpv Helpers52811 472 M1 ×4T ActivityPlaybookTrait.php1664© Arraylterator.php1681T ConnectionStateTrait.php1682© MatchActivityCrmData.php© Client.php© HubspotPaginationService.phpclass Service extends BaseService implementsprivate function buildCallPayload(Activity $activity): Activityif(Sthis->getCrmType(Sactivitx->category2mmnull2ntSmessage = sprintf( format:'[Copper] Invalid CRM Activity Type: %s', Sactivity->category->getNameO);A console (EU]© CrmHelperRepository.php1683© FilterJoinedParticipants.php1684+ OpportunitySyncableFieldsTthrow new CrmException(Smessage,code:400);1685v D Hubspot1686• AccountSyncStrategy1687> OJ Actions |1688if (Sthis->getCrmType($activity->category)->value === null) {$message = sprintf( format: '[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName 222• ContactSyncStrategy1689> ODTO1690throw new CrmException(Smessage,code: 400):D Fields1691› O Journal1692D Metadata1693v C OpportunitySyncStrategy1694> D Concerns1695© HubspotLastModifiedByF1696© HubspotLastModifiedCre1697© HubspotLastModifiedCre1698// Just create an activity.$cpActivity = $this->copperClient->activities()->create(['user_id' = $this->profile->crm_provider_id,'activity_date' => $activity->scheduled_start_time->timestamp,'parent' => $this->convertActivityAssociations($activity),'type' => Sthis->convertActivityType($activity->category),'details' => $this->generateActivityDescription(Sactivity),© HubspotLastModifiedOpe16991):© HubspotLastModifiedSyn1700DGojiminny v084143 ×4 л215•m_layout_id =2162,1661,66799,66217218219id = 33;=220221=223= 224id THEN '(own225=226= 227228229= 230hubspot';2312322:233V= 11512582;234© HubspotSingleSyncStrate1701© HubspotSyncStrategyBa:1702Sactivity->crm_provider_id = $cpActivity['id']:Sactivity->saveO:© HubspotWebhookBatchS1703v [ Pagination1704ch (ClientException $exception) {© HubspotPaginationServic1705A DaninatinnCanfin nhn/Log all ercons to SentryWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams1688:29 (8 chars)UTF-8Co 4 spaces...
|
NULL
|
-7097145309050108631
|
NULL
|
visual_change
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelplhl•FV faVsco.jsv#12066 on JY-20725-handle-HS-search-rate-limit k vHandleHubspotRateLimitTestv100% <8• Thu 14 May 17:33:09QProjectv= custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php© FieldDefinitions.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php=laravel.log© FieldValueConverter.php• DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© Service.php© DecorateActivity.phpSF [jiminny@localhost]> D CrmObjects© Salesforce/Service.php© LogActivityTrait.phpPipedrive/Service.phpClose/Service.phpCopper/Service.php XA HS_local [jiminny@localho:W• DecorateActivity© PlainTextDecorateActivity.phpT ActivityPlaybookTrait.phpCrmHelperRepository.phpAccountController.php4 console [QAI PROD] X18© BaseDecorateActivity.php© PlainTextDecorateActivity.plT IntegrationAppTrait.php.env.stagingE.env© DetachActivityObject.phpRematchActivityOnCrmObjectDetach.php4 console [PROD]> D Dummy© HandleHubspotRateLimit.phpv Helpers52811 472 M1 ×4T ActivityPlaybookTrait.php1664© Arraylterator.php1681T ConnectionStateTrait.php1682© MatchActivityCrmData.php© Client.php© HubspotPaginationService.phpclass Service extends BaseService implementsprivate function buildCallPayload(Activity $activity): Activityif(Sthis->getCrmType(Sactivitx->category2mmnull2ntSmessage = sprintf( format:'[Copper] Invalid CRM Activity Type: %s', Sactivity->category->getNameO);A console (EU]© CrmHelperRepository.php1683© FilterJoinedParticipants.php1684+ OpportunitySyncableFieldsTthrow new CrmException(Smessage,code:400);1685v D Hubspot1686• AccountSyncStrategy1687> OJ Actions |1688if (Sthis->getCrmType($activity->category)->value === null) {$message = sprintf( format: '[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName 222• ContactSyncStrategy1689> ODTO1690throw new CrmException(Smessage,code: 400):D Fields1691› O Journal1692D Metadata1693v C OpportunitySyncStrategy1694> D Concerns1695© HubspotLastModifiedByF1696© HubspotLastModifiedCre1697© HubspotLastModifiedCre1698// Just create an activity.$cpActivity = $this->copperClient->activities()->create(['user_id' = $this->profile->crm_provider_id,'activity_date' => $activity->scheduled_start_time->timestamp,'parent' => $this->convertActivityAssociations($activity),'type' => Sthis->convertActivityType($activity->category),'details' => $this->generateActivityDescription(Sactivity),© HubspotLastModifiedOpe16991):© HubspotLastModifiedSyn1700DGojiminny v084143 ×4 л215•m_layout_id =2162,1661,66799,66217218219id = 33;=220221=223= 224id THEN '(own225=226= 227228229= 230hubspot';2312322:233V= 11512582;234© HubspotSingleSyncStrate1701© HubspotSyncStrategyBa:1702Sactivity->crm_provider_id = $cpActivity['id']:Sactivity->saveO:© HubspotWebhookBatchS1703v [ Pagination1704ch (ClientException $exception) {© HubspotPaginationServic1705A DaninatinnCanfin nhn/Log all ercons to SentryWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams1688:29 (8 chars)UTF-8Co 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45370
|
1626
|
14
|
2026-05-14T14:33:08.442631+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769188442_m2.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
7058342144550237105
|
-7195274138713862717
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctOpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeave~ (Q SearchDate ModifiedYesterdav at 13.36Yesterday at 13:36Yesterday at 13.30Yesterday at 13:34Yesterday at 13:34resterday at 15.5sYesterdav at 13:3kYesterday at 13:32Yesterday at 13.31Yesterday at 13:31Yesterday at 13:30resterday at 15.30Yesterdav at 13:29Yesterday at 13:29Yesterday at 13:28Yesterday at 13:28Yesterday at 13:27resterday at 13-40Yesterdav at 13:26Yesterday at 13:25Yesterday at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13.22Yesterdav at 13:21Yesterday at 13:20Yesterday at 13:19Yesterday at 13.18Yecterdav at 12:19Yesterday at 13-1/Yesterdav at 13:16Yesterday at 13:16Yesterday at 13:15Yecterdav at 12:1/Yesterday at 13:14Yesterday at 13.13Yecterdav at 13:10Yesterday at 13:12Yesterday at 13:11Yesterday at 13:11Yesterday at 13:10Yesterday at 13.10Yecterdav at 12:091Yesterday at 13:09Yesterdav at 13:0823K:MPEG-4 movie9KBMPEG-4 movie13 KB16 Kb17 KEMPEG-4 movieMPEG-4 movie29 KB6 KBMPE0"4 movie12 K:9 KBMPEG-4 movie7 KBMP2G-4 movie37 KBMPEG-4 movie10 KBI KDMPEG"4 movie8 KE9KBMPEG-4 movie8 KB72 KBMPEG-4 movie14 KBMPEG-4 movie13 KB9KBMPEG-4 movie18 KEMPEG-4 movie12 KBMPEG-4 movie10 KB16 K:MPEG-4 movie6 KBMPEG-4 movie12 KBMPEG-4 movie23 KBMPEG-4 movie8 KBMPEG-4 movie6 KBMPEG-4 movie16 K:11 KBMPEG-4 movie20 KBMPEG-4 movie21 KPMPEG-4 movie10 KB MPEG-4 movie7 KBMPEG-4 movie5 KB1MPEG-4 movie11 KBMPEG-4 movie26 KB111 KB102 KRMPEG-4 movieMDEG-A movie88 KB59 KBMPEG-4 movie08 KBIMPEG-A movie97 KB MPEG-4 movie66 KB44 KB02 KpMPEG-4 movieMPEG-4 movie78 KB50 KBMPEG-4 movie58 KГMPEG-A movid27 KBMPEG-4 movie7 KB12K8MPEG-4 movieFavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zipD report(2) xmlAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence hettertouchtoolMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•AlfredwPmazanoko.imnaoc.YWIfана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jpс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 Kb148 KВ148 KB122 KB111 KB94 KBZIP archiveZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentPDF Document91 KB91 KB30 KB29 KBXML documentPDF Document28 KB28 KR28 KB27 KB14 KB11 KB6 KB6KB5KR4 KB3 KBPDF DocumentPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..umentWindo...n imageword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytes1,9 MB1,8 MB17 MB1,7 MBFoldeColdorJPEG imageJPEG ImageJPEG imageJPEG imageColdo1 of 58 selected, 8.5 GB availab!i• Inu 14 Mаy 1/.33.01Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
45367
|
NULL
|
NULL
|
NULL
|
|
45369
|
1625
|
22
|
2026-05-14T14:33:08.460007+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769188460_m1.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.6645833,"top":0.027777778,"width":0.15902779,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
7058342144550237105
|
-7195274138713862717
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit k vabl100% CHandleHubspotRateLimitTest8• Thu 14 May 17:33:08* :QProjectv:=custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php© FieldDefinitions.php© UserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php=laravel.log© FieldValueConverter.php• DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© Service.php© DecorateActivity.phpSF [jiminny@localhost]> D CrmObjects© Salesforce/Service.php© LogActivityTrait.php© Pipedrive/Service.php© Close/Service.phpCopper/Service.php XA HS_local [jiminny@localho:W• DecorateActivity© PlainTextDecorateActivity.phpT ActivityPlaybookTrait.php© CrmHelperRepository.php© AccountController.php4 console [QAI PROD] X18© BaseDecorateActivity.php© PlainTextDecorateActivity.plT IntegrationAppTrait.php=.env.stagingE.env© DetachActivityObject.phpRematchActivityOnCrmObjectDetach.php4 console [PROD]> D Dummyv HelpersT ActivityPlaybookTrait.php521664© MatchActivityCrmData.php© Client.php© HubspotPaginationService.phpclass Service extends BaseService implementsprivatefunction buildCallPayload(Activity $activity): Activity© HandleHubspotRateLimit.phpA console (EU]811 472 M1 ×4© Arraylterator.phpT ConnectionStateTrait.php1674© CrmHelperRepository.php1675© FilterJoinedParticipants.php1676© OpportunitySyncableFieldsT 1677v D Hubspot1678• AccountSyncStrategy1679> OJ Actions |1680Sthis->copperClient->tasks()->update($activity->crm_provider_id, ['status' =>'Completed','custom_activity_type_id' => $newActivityType->value,'details' => $this-›generateActivityDescription(Sactivity),1):else{id = 33;• ContactSyncStrategy1681> ODTO1682if(Sthis->getCrmType(Sactivitx-2categacx2null2ntSmessage = sprintf( format: '[Copper] Invalid CRM Activity Type: %s', Sactivity->category->getName()) ; E223D Fields1683› Journal1684• Metadata1685v C OpportunitySyncStrategy1686> D Concerns1687© HubspotLastModifiedByf 1688© HubspotLastModifiedCre1689© HubspotLastModifiedCre1690HubspotLastModifiedOpe1691|© HubspotLastModifiedSyn16921693DGo jiminny084143 ×4 л215•m_layout_id =2162,1661,66799,66217218219=220221: 222= 224— 225=226Extract Surround / E :=2271t (scnis->getcrmiype(>activity->category)->value === nul) {228Smessage = sprintf( format: '[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName 229= 230231t232233 V234id THEN(ownthrow new CrmException(Smessage,code: 400);HIhubspat":throw new CrmException(Smessage,code: 400);// Just createan activity.= 11512582;© HubspotSingleSyncStrate$cpActivity = $this->copperClient-›activities()->create([© HubspotSyncStrategyBa:1694'user_id' => $this->profile->crm_provider_id,© HubspotWebhookBatchS1695'activity_date' => $activity->scheduled_start_time->timestamp,v [ Pagination1696'parent' => $this->convertActivityAssociations(Sactivity),© HubspotPaginationServic 1697'type' => $this->convertActivityType($activity->category),A DaninationCanfin nhn1698'details= $this->qenerateActivityDescription(Sactivity)Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams1685:18 (246 chars, 4 line breaks)UTF-8Ca 4 spaces...
|
45368
|
NULL
|
NULL
|
NULL
|
|
45367
|
1626
|
13
|
2026-05-14T14:32:59.007462+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769179007_m2.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctOpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeave~ (Q SearchDate ModifiedYesterdav at 13.36Yesterday at 13:36Yesterday at 13.30Yesterday at 13:34Yesterday at 13:34resterday at 15.5sYesterdav at 13:3kYesterday at 13:32Yesterday at 13.31Yesterday at 13:31Yesterday at 13:30resterday at 15.30Yesterdav at 13:29Yesterday at 13:29Yesterday at 13:28Yesterday at 13:28Yesterday at 13:27resterday at 13-40Yesterdav at 13:26Yesterday at 13:25Yesterday at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13.22Yesterdav at 13:21Yesterday at 13:20Yesterday at 13:19Yesterday at 13.18Yecterdav at 12:19Yesterday at 13-1/Yesterdav at 13:16Yesterday at 13:16Yesterday at 13:15Yecterdav at 12:1/Yesterday at 13:14Yesterday at 13.13Yecterdav at 13:10Yesterday at 13:12Yesterday at 13:11Yesterday at 13:11Yesterday at 13:10Yesterday at 13.10Yecterdav at 12:091Yesterday at 13:09Yesterdav at 13:0823K:MPEG-4 movie9KBMPEG-4 movie13 KB16 Kb17 KEMPEG-4 movieMPEG-4 movie29 KB6 KBMPE0"4 movie12 K:9 KBMPEG-4 movie7 KBMP2G-4 movie37 KBMPEG-4 movie10 KBI KDMPEG"4 movie8 KE9KBMPEG-4 movie8 KB72 KBMPEG-4 movie14 KBMPEG-4 movie13 KB9KBMPEG-4 movie18 KEMPEG-4 movie12 KBMPEG-4 movie10 KB16 K:MPEG-4 movie6 KBMPEG-4 movie12 KBMPEG-4 movie23 KBMPEG-4 movie8 KBMPEG-4 movie6 KBMPEG-4 movie16 K:11 KBMPEG-4 movie20 KBMPEG-4 movie21 KPMPEG-4 movie10 KB MPEG-4 movie7 KBMPEG-4 movie5 KB1MPEG-4 movie11 KBMPEG-4 movie26 KB111 KB102 KRMPEG-4 movieMDEG-A movie88 KB59 KBMPEG-4 movie08 KBIMPEG-A movie97 KB MPEG-4 movie66 KB44 KB02 KpMPEG-4 movieMPEG-4 movie78 KB50 KBMPEG-4 movie58 KГMPEG-A movid27 KBMPEG-4 movie7 KB12K8MPEG-4 movieFavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zipD report(2) xmlAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence hettertouchtoolMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•AlfredwPmazanoko.imnaoc.YWIfана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jpс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 Kb148 KВ148 KB122 KB111 KB94 KBZIP archiveZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentPDF Document91 KB91 KB30 KB29 KBXML documentPDF Document28 KB28 KR28 KB27 KB14 KB11 KB6 KB6KB5KR4 KB3 KBPDF DocumentPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..umentWindo...n imageword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytes1,9 MB1,8 MB17 MB1,7 MBFoldeColdorJPEG imageJPEG ImageJPEG imageJPEG imageColdo1 of 58 selected, 8.5 GB availab!i• Inu 14 May 1/.32:00Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
2977166443459692715
|
NULL
|
click
|
ocr
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctOpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeave~ (Q SearchDate ModifiedYesterdav at 13.36Yesterday at 13:36Yesterday at 13.30Yesterday at 13:34Yesterday at 13:34resterday at 15.5sYesterdav at 13:3kYesterday at 13:32Yesterday at 13.31Yesterday at 13:31Yesterday at 13:30resterday at 15.30Yesterdav at 13:29Yesterday at 13:29Yesterday at 13:28Yesterday at 13:28Yesterday at 13:27resterday at 13-40Yesterdav at 13:26Yesterday at 13:25Yesterday at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13.22Yesterdav at 13:21Yesterday at 13:20Yesterday at 13:19Yesterday at 13.18Yecterdav at 12:19Yesterday at 13-1/Yesterdav at 13:16Yesterday at 13:16Yesterday at 13:15Yecterdav at 12:1/Yesterday at 13:14Yesterday at 13.13Yecterdav at 13:10Yesterday at 13:12Yesterday at 13:11Yesterday at 13:11Yesterday at 13:10Yesterday at 13.10Yecterdav at 12:091Yesterday at 13:09Yesterdav at 13:0823K:MPEG-4 movie9KBMPEG-4 movie13 KB16 Kb17 KEMPEG-4 movieMPEG-4 movie29 KB6 KBMPE0"4 movie12 K:9 KBMPEG-4 movie7 KBMP2G-4 movie37 KBMPEG-4 movie10 KBI KDMPEG"4 movie8 KE9KBMPEG-4 movie8 KB72 KBMPEG-4 movie14 KBMPEG-4 movie13 KB9KBMPEG-4 movie18 KEMPEG-4 movie12 KBMPEG-4 movie10 KB16 K:MPEG-4 movie6 KBMPEG-4 movie12 KBMPEG-4 movie23 KBMPEG-4 movie8 KBMPEG-4 movie6 KBMPEG-4 movie16 K:11 KBMPEG-4 movie20 KBMPEG-4 movie21 KPMPEG-4 movie10 KB MPEG-4 movie7 KBMPEG-4 movie5 KB1MPEG-4 movie11 KBMPEG-4 movie26 KB111 KB102 KRMPEG-4 movieMDEG-A movie88 KB59 KBMPEG-4 movie08 KBIMPEG-A movie97 KB MPEG-4 movie66 KB44 KB02 KpMPEG-4 movieMPEG-4 movie78 KB50 KBMPEG-4 movie58 KГMPEG-A movid27 KBMPEG-4 movie7 KB12K8MPEG-4 movieFavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zipD report(2) xmlAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence hettertouchtoolMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•AlfredwPmazanoko.imnaoc.YWIfана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jpс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 Kb148 KВ148 KB122 KB111 KB94 KBZIP archiveZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentPDF Document91 KB91 KB30 KB29 KBXML documentPDF Document28 KB28 KR28 KB27 KB14 KB11 KB6 KB6KB5KR4 KB3 KBPDF DocumentPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..umentWindo...n imageword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytes1,9 MB1,8 MB17 MB1,7 MBFoldeColdorJPEG imageJPEG ImageJPEG imageJPEG imageColdo1 of 58 selected, 8.5 GB availab!i• Inu 14 May 1/.32:00Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45365
|
1626
|
12
|
2026-05-14T14:32:55.476143+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769175476_m2.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
11
72
1
4
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Copper;
use Carbon\Carbon;
use Exception;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Facades\Cache;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\CopperInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\FieldValue;
use Jiminny\Models\Crm\LayoutEntity;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\PlaybookCategory;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\UserRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\Copper\Api\Client;
use Jiminny\Services\Crm\Copper\Api\ClientFactory;
use Jiminny\Services\Crm\Copper\Exception\RequestFailedException;
use Jiminny\Services\Crm\Helpers\FilterJoinedParticipants;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Services\Crm\Copper\Traits\SearchesCrmEntities;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
class Service extends BaseService implements
CopperInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
use SearchesCrmEntities;
private const int NOTE_BODY_MAX_LENGTH = 3000000;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const array STANDARD_OPPORTUNITY_FIELDS = [
'monetary_value' => [
'label' => 'Value',
'available_on' => Field::OBJECT_OPPORTUNITY,
'type' => Field::TYPE_CURRENCY,
],
'pipeline_stage_id' => [
'label' => 'Stage',
'type' => Field::TYPE_PICKLIST,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
'close_date' => [
'label' => 'Close date',
'type' => Field::TYPE_DATE,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
'win_probability' => [
'label' => 'Win probability',
'type' => Field::TYPE_NUMBER,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
];
private const string UNSUPPORTED_OBJECT_TYPE = 'unsupported';
private const string OPPORTUNITY_STATUS_OPEN = 'Open';
private const string OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE = 'Opportunity import failed';
private const string RESOURCE_UPDATE_FAILED_ERROR_MESSAGE = 'Failed to update resource';
private FieldValueConverter $fieldValueConverter;
private ClientFactory $clientFactory;
private ?Client $copperClient = null;
public function __construct(
ClientFactory $clientFactory,
FieldValueConverter $fieldValueConverter,
private readonly UserRepository $userRepository,
private readonly ProspectPhotoPathService $prospectPhotoPathService,
private readonly CrmEntityRepository $crmEntityRepository
) {
parent::__construct();
$this->clientFactory = $clientFactory;
$this->fieldValueConverter = $fieldValueConverter;
}
public function getDisplayName(): string
{
return 'Copper';
}
/**
* Get the CRM entity repository (used by SearchesCrmEntities trait)
*/
protected function getCrmEntityRepository(): CrmEntityRepository
{
return $this->crmEntityRepository;
}
public function getMinimumApiVersion(): string
{
return Client::MIN_API_VERSION;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_COPPER);
}
public function setUser(User $user): void
{
$this->configureSentryScope($user);
$this->team = $user->getTeam();
$this->teamService->setTeam($user->getTeam());
$this->setConfiguration($user->getTeam()->getCrmConfiguration());
// Reset state.
$this->profile = $user->getProfile();
if (! $this->profile instanceof Profile) {
// Try to fetch their profile, maybe it was not yet imported?
$this->profile = $this->getProfile($user);
}
}
public function setConfiguration(Configuration $configuration): void
{
$this->config = $configuration;
$this->copperClient = $this->clientFactory->create($configuration);
if ($this->team === null) {
$this->team = $configuration->getTeam();
}
}
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return $this->fieldValueConverter->convertFromCrm($fieldType, $fieldValue);
}
private function mapObjectType(string $objectType): string
{
$objectType = strtolower($objectType);
switch ($objectType) {
case Field::OBJECT_TASK:
case Field::OBJECT_OPPORTUNITY:
case Field::OBJECT_LEAD:
$mappedType = $objectType;
break;
case Field::OBJECT_ACCOUNT:
$mappedType = 'company';
break;
case Field::OBJECT_CONTACT:
$mappedType = 'person';
break;
default:
$mappedType = self::UNSUPPORTED_OBJECT_TYPE;
break;
}
return $mappedType;
}
/**
* @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact
*/
protected function getFields(string $crmObject): array
{
$mappedObjectType = $this->mapObjectType($crmObject);
if (! $this->isSupportedObjectType($mappedObjectType)) {
return [];
}
$customFields = $this->copperClient->fields()->all();
$filteredFields = array_filter(
$customFields,
static fn ($field) => in_array($mappedObjectType, $field['available_on'], true)
);
return array_map(
fn (array $property) => [
'name' => $property['id'],
'label' => $property['name'],
'type' => $this->convertFieldType($property['data_type']),
],
$filteredFields
);
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {
$defaultFields = FieldDefinitions::defaultTaskFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldFilters = FieldDefinitions::taskFollowupFieldsFilter();
foreach ($fieldFilters as $data) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
public function syncFields(): void
{
$this->syncStandardFields();
$this->syncCustomFields();
}
public function syncField(Field $field): void
{
if ($field->getCrmProviderId() === 'type') {
/**
* This field is a special case, it is not a custom field and is not returned by the Copper API.
*
* The field is created manually during layout setup.
*
* @see getDefaultFields()
*
* There is a separate endpoint to get the activity types.
* @see importPicklistValues()
*/
return;
}
if ($field->getCrmProviderId() === 'pipeline_stage_id') {
// Not a custom type
return;
}
$crmField = $this->copperClient->fields()->find($field->getCrmProviderId());
$field->label = $crmField['name'];
$field->type = $this->convertFieldType($crmField['data_type']);
$field->save();
}
/**
* @param string $fieldType How the data should be input
*/
private function convertFieldType(string $fieldType): string
{
$fieldType = strtolower($fieldType);
switch ($fieldType) {
case 'dropdown':
$convertedType = Field::TYPE_PICKLIST;
break;
case 'string':
$convertedType = Field::TYPE_TEXT;
break;
case 'float':
case 'percentage':
$convertedType = Field::TYPE_NUMBER;
break;
case 'text':
$convertedType = Field::TYPE_TEXTAREA;
break;
case 'checkbox':
$convertedType = Field::TYPE_BOOLEAN;
break;
case Field::TYPE_DATE:
case Field::TYPE_CURRENCY:
case Field::TYPE_URL:
$convertedType = $fieldType;
break;
default:
$convertedType = Field::TYPE_UNSUPPORTED;
break;
}
return $convertedType;
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$fieldValues = [];
if ($field->object_type === 'opportunity' && $field->crm_provider_id === 'pipeline_stage_id') {
return $this->importFieldValuesForDealInsights($field);
}
$values = [];
if ($field->object_type === Field::OBJECT_TASK && $field->crm_provider_id === 'type') {
$activityTypes = $this->copperClient->activityTypes()->all();
/**
* We ignore "system" activity types, disabled activity types and the "Note" activity type.
*/
$activityTypes = array_filter(
$activityTypes['user'],
fn (array $activityType) => ! $activityType['is_disabled'] && $activityType['id'] !== 0
);
// Import all activity values.
$i = 0;
foreach ($activityTypes as $activityType) {
$values[] = [
'value' => $activityType['id'],
'label' => mb_strimwidth($activityType['name'], 0, Field::LABEL_MAX_LENGTH),
'sequence' => $i++,
];
}
} else {
// We just check for the field in the custom definitions.
$crmField = $this->copperClient->fields()->find($field->crm_provider_id);
// Import all values.
foreach ($crmField['options'] as $option) {
$values[] = [
'value' => $option['id'],
'label' => mb_strimwidth($option['name'], 0, 191),
'sequence' => $option['rank'],
];
}
}
// Take the existing set of field values.
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
// For all current values, upsert the field.
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
$key = array_search($value['value'], $fieldsToPurge, false);
if ($key !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
return $fieldValues;
}
/**
*
* @return FieldValue[]
*/
private function importFieldValuesForDealInsights(Field $field): array
{
$fieldValues = [];
$pipelines = $this->copperClient->pipelines()->all();
foreach ($pipelines as $pipeline) {
foreach ($pipeline['stages'] as $i => $dealStage) {
$fieldValues[] = $field->values()->updateOrCreate(
['value' => $dealStage['id']],
[
'label' => $dealStage['name'],
'sequence' => $i,
]
);
}
}
return $fieldValues;
}
/**
* @inheritdoc
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
$missingStage = null;
foreach ($types as $type) {
if ($type === Stage::TYPE_LEAD) {
$statuses = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leadStatuses()->all()
);
if (count($statuses) > 0) {
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => BusinessProcess::TYPE_LEAD,
], [
'team_id' => $this->team->id,
'name' => BusinessProcess::TYPE_LEAD,
'type' => BusinessProcess::TYPE_LEAD,
'is_selectable' => true,
]);
// A record type is really a clone of the business process, used to store which record uses which pipeline.
$this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => BusinessProcess::TYPE_LEAD,
], [
'team_id' => $this->team->id,
'name' => BusinessProcess::TYPE_LEAD,
'is_selectable' => true,
'business_process_id' => $businessProcess->id ?? null,
]);
$leadStatuses = [];
foreach ($statuses as $status) {
// Upsert all statuses for the team.
$status = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $status['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($status['name'], 0, 50),
'label' => mb_strimwidth($status['name'], 0, 191),
'type' => Stage::TYPE_LEAD,
'sequence' => $status['order'],
'is_selectable' => true,
]);
if ($missingStageName && $missingStageName === $status['id']) {
$missingStage = $status;
}
$leadStatuses[] = $status['id'];
}
$businessProcess->stages()->sync($leadStatuses);
}
} else {
// We create a business process to contain the pipeline, and later store all stages against it.
foreach ($this->copperClient->pipelines()->all() as $pipeline) {
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => $pipeline['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($pipeline['name'], 0, 150),
'type' => BusinessProcess::TYPE_OPPORTUNITY,
'is_selectable' => true,
]);
// A record type is really a clone of the business process, used to store which record uses which pipeline.
$this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => $pipeline['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($pipeline['name'], 0, 150),
'is_selectable' => true,
'business_process_id' => $businessProcess->id ?? null,
]);
$stages = [];
foreach ($pipeline['stages'] as $i => $dealStage) {
// Upsert all stages for the team.
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $dealStage['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($dealStage['name'], 0, 50),
'label' => mb_strimwidth($dealStage['name'], 0, 191),
'type' => Stage::TYPE_OPPORTUNITY,
'sequence' => $i,
'is_selectable' => true,
'probability' => $dealStage['win_probability'],
]);
if ($missingStageName && $missingStageName === $dealStage['id']) {
$missingStage = $stage;
}
$stages[] = $stage['id'];
}
$businessProcess->stages()->sync($stages);
}
}
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$cpLeads = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->paginate([
'minimum_modified_date' => $since->timestamp,
'sort_by' => 'date_modified',
])
);
foreach ($cpLeads as $cpLead) {
// Only sync if previously imported.
if ($this->hasLead($cpLead['id']) === false) {
$this->importLead($cpLead);
$syncCount++;
}
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
$cpLead = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->find($crmId)
);
if (\count($cpLead) === 0) {
return null;
}
return $this->importLead($cpLead);
}
/**
* @inheritdoc
*/
private function importLead($crmData): ?Lead
{
$countryCode = null;
if (! empty($crmData['address']) && isset($crmData['address']['country'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$mobilePhone = $parsedNumber = null;
if (! empty($crmData['phone_numbers'])) {
foreach ($crmData['phone_numbers'] as $phoneNumber) {
if ($phoneNumber['category'] === 'mobile') {
$mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);
} else {
$parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);
}
}
}
$name = $crmData['name'];
if (empty($crmData['company_name'])) {
$company = 'Unknown';
} else {
$company = mb_strimwidth($crmData['company_name'], 0, 191);
}
$domain = null;
if (empty($crmData['websites']) === false) {
$domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$email = null;
if (empty($crmData['email']) === false) {
$email = mb_strimwidth($crmData['email']['email'], 0, 80);
}
$stage = $this->config
->stages()
->where('crm_provider_id', (string) $crmData['status_id'])
->where('type', Stage::TYPE_LEAD)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status_id']);
}
if (! $stage instanceof Stage) {
return null;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($name, 0, 191),
'company' => $company,
'domain' => $domain,
'title' => $crmData['title'] ? mb_strimwidth($crmData['title'], 0, 128) : null,
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'mobile_phone' => $mobilePhone,
'stage_id' => $stage->id,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Lead::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'country_code' => $countryCode,
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$cpAccounts = $this->copperClient->accounts()->paginate([
'minimum_modified_date' => $since->timestamp,
'sort_by' => 'date_modified',
]);
foreach ($cpAccounts as $cpAccount) {
// Only sync if previously imported.
if ($this->hasAccount($cpAccount['id'])) {
$this->importAccount($cpAccount);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
$cpAccount = $this->copperClient->accounts()->find($crmId);
if (empty($cpAccount)) {
return null;
}
return $this->importAccount($cpAccount);
}
/**
* @inheritdoc
*/
private function importAccount($crmData): Account
{
$countryCode = null;
if (empty($crmData['address']) === false && $crmData['address']['country']) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$name = $crmData['name'];
$parsedNumber = null;
foreach ($crmData['phone_numbers'] as $phoneNumber) {
$parsedNumber = parsePhoneNumber($countryCode, $phoneNumber['number']);
}
$domain = null;
if (empty($crmData['websites']) === false) {
$domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Account::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'country_code' => $countryCode,
'domain' => $domain,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->copperClient,
]);
$strategies = $strategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
try {
foreach ($strategies as $syncStrategy) {
foreach ($syncStrategy->fetchOpportunities($parameters) as $opportunityData) {
$this->importOpportunity($opportunityData);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
$this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => $exception->getMessage(),
]);
}
return $syncCount;
}
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->copperClient,
]);
$strategy = $strategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
$parameters['crm_id'] = $crmId;
$cpOpportunity = $strategy->fetchOpportunities($parameters);
return $this->importOpportunity($cpOpportunity);
}
private function importOpportunity($crmData): ?Opportunity
{
$companyId = (string) $crmData['company_id'];
if (empty($companyId)) {
$this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => 'No company id',
]);
return null;
}
$account = $this->config->accounts()->where('crm_provider_id', $companyId)->first();
if ($account === null) {
$account = $this->syncAccount($companyId);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', (string) $crmData['pipeline_id'])
->first();
if ($businessProcess === null) {
// It is possible for some deals to not be in a pipeline.
$this->logger->warning(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => 'Missing pipeline',
]);
return null;
}
$stage = $businessProcess
->stages()
->where('crm_provider_id', (string) $crmData['pipeline_stage_id'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
$this->logger->info('Stage not found, importing', [
'pipeline_id' => $crmData['pipeline_id'],
'stage_id' => $crmData['pipeline_stage_id'],
]);
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['pipeline_stage_id']);
}
$recordType = $businessProcess->recordTypes()->first();
$closeDate = null;
$isClosed = $crmData['status'] !== self::OPPORTUNITY_STATUS_OPEN;
if ($crmData['close_date']) {
$closeDate = Carbon::parse($crmData['close_date'])->format('Y-m-d');
}
$data = [
'team_id' => $this->team->getId(),
'account_id' => $account->id,
'user_id' => $profile->user_id ?? null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($crmData['name'], 0, 128),
'value' => $crmData['monetary_value'],
'currency_code' => CurrencyFormatter::formatCode($crmData['monetary_unit']),
'close_date' => $closeDate,
'is_closed' => $isClosed,
'is_won' => $crmData['status'] === 'Won',
'stage_id' => $stage->id,
'record_type_id' => $recordType->id ?? null,
'remotely_created_at' => $crmData['date_created'],
];
/** @var Opportunity $opportunity */
$opportunity = $this->config
->opportunities()
->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data)
;
// import external fields into crm_field_data if present
$dealInsightsFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData($crmData, $dealInsightsFields, $opportunity->id);
return $opportunity;
}
/**
* @param array<string, mixed> $opportunityData
* @param string[] $dealInsightsFields
*/
public function importOpportunityCrmFieldData(
array $opportunityData,
array $dealInsightsFields,
int $opportunityId
): void {
foreach ($dealInsightsFields as $fieldName) {
$field = $this->config->fields()->with('entities')
->where('crm_provider_id', $fieldName)
->where('object_type', Field::OBJECT_OPPORTUNITY)
->first();
if (! $field instanceof Field) {
$this->logger->warning('Field not found', [
'field' => $fieldName,
'opportunity_id' => $opportunityId,
]);
continue;
}
$entity = $field->getEntities()->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$fieldValue = $this->extractFieldValue($opportunityData, $fieldName);
$normalizedValue = $this->normalizeValue($field->getType(), (string) $fieldValue, true);
$field->data()
->updateOrCreate([
'crm_layout_entity_id' => $entity->id,
'crm_field_id' => $field->id,
'object_type' => 'opportunity',
'object_id' => $opportunityId,
], ['value' => $normalizedValue])
;
}
}
/**
* @inheritdoc
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$cpContacts = $this->copperClient->contacts()->paginate([
'minimum_interaction_date' => $since->timestamp,
'sort_by' => 'date_modified',
]);
foreach ($cpContacts as $cpContact) {
// Only sync if previously imported.
if ($this->hasContact($cpContact['id'])) {
$this->importContact($cpContact);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
throw $exception;
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncContact(string $crmId): ?Contact
{
$cpContact = $this->copperClient->contacts()->find($crmId);
if (empty($cpContact)) {
return null;
}
return $this->importContact($cpContact);
}
/**
* @inheritdoc
*/
private function importContact($crmData): Contact
{
$account = null;
if ($crmData['company_id']) {
$account = $this->team
->crm
->accounts()
->where('crm_provider_id', (string) $crmData['company_id'])
->first();
if ($account === null) {
$account = $this->syncAccount($crmData['company_id']);
}
}
$countryCode = null;
if (empty($crmData['address']) === false && $crmData['address']['country']) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$mobilePhone = $parsedNumber = null;
foreach ($crmData['phone_numbers'] as $phoneNumber) {
if ($phoneNumber['category'] === 'mobile') {
$mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);
} else {
$parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);
}
}
$email = null;
if (empty($crmData['emails']) === false) {
$email = mb_strimwidth($crmData['emails'][0]['email'], 0, 80);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => $crmData['name'],
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'mobile_phone' => $mobilePhone ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'title' => $crmData['title'],
'country_code' => $countryCode,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Contact::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function buildContactPhone(?string $countryCode, ?string $number): ?array
{
if ($number) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($number, 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
return $parsedNumber;
}
private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string
{
return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;
}
/**
* @inheritdoc
*/
public function syncOrganization(): void
{
$organization = $this->copperClient->organisation()->all();
if ($this->config->crm_provider_id !== $organization['id']) {
$this->config->update(['crm_provider_id' => $organization['id']]);
}
}
private function syncCustomFields(): void
{
foreach ($this->getFieldTypes() as $fieldType) {
$currentFields = $this->getFields($fieldType);
foreach ($currentFields as $field) {
/** @var Field $field */
$field = $this->config->fields()->updateOrCreate([
'crm_provider_id' => $field['name'],
'object_type' => $fieldType,
], [
'label' => mb_strimwidth($field['label'], 0, Field::LABEL_MAX_LENGTH),
'type' => $field['type'],
]);
if ($field->getType() === Field::TYPE_PICKLIST) {
$this->importPicklistValues($field);
}
}
}
$this->config->save();
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
parent::OBJECT_LEAD,
parent::OBJECT_ACCOUNT,
parent::OBJECT_CONTACT,
parent::OBJECT_OPPORTUNITY,
];
}
/**
* @inheritdoc
*/
public function syncProfiles(?User $userToSearch = null): ?Profile
{
$profiles = $this->copperClient->users()->all();
foreach ($profiles as $profile) {
$user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);
// Only import profiles for users we have locally.
if ($user) {
$profile = $user->crmProfile()->updateOrCreate([
'crm_configuration_id' => $this->config->id,
'crm_provider_id' => $profile['id'],
]);
if ($userToSearch && $userToSearch->id === $user->id) {
return $profile;
}
}
}
return null;
}
/**
* @inheritdoc
*/
public function syncProfileFields(): void
{
$fieldTypes = [
'task',
'lead',
'account',
'contact',
'opportunity',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields(ucfirst($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))
);
if (\count($changedFields) > 0) {
$fields = implode(',', $newFields);
$this->logger->debug(
ucfirst($fieldType)
. ' fields changed from '
. $this->profile->{$fieldType . '_fields'}
. ' to: '
. $fields
);
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (\Exception $exception) {
$this->logger->error('No access to ' . $fieldType . ' object, skipping...');
continue;
}
}
$this->profile->save();
}
/**
* @inheritdoc
*/
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$scopeValues = array_map(fn ($scope) => is_string($scope) ? $scope : $scope->value, $scopes);
$cacheKey = sprintf('copper-search-%d-%s-%s-%d-%d', $this->team->id, $name, implode('-', $scopeValues), $count, $offset);
return Cache::remember($cacheKey, 300, function () use ($name, $scopes, $count, $offset) {
// Try local search first
$localResults = $this->searchLocally($name, $scopes, $count, $offset);
// If no local results, fall back to remote API search
if (empty($localResults)) {
return $this->searchRemotely($name, $scopes, $count, $offset);
}
return $localResults;
});
}
/**
* @inheritdoc
*/
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$params = [
'company_ids' => [$account->crm_provider_id],
'status_ids' => [0], // The integer values are 0, 1, 2, 3, for "Open", "Won", "Lost", and "Abandoned".
'sort_by' => 'date_modified',
'sort_direction' => 'desc',
];
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort_by'] = 'date_modified';
$params['sort_direction'] = 'desc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort_by'] = 'date_created';
$params['sort_direction'] = 'desc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort_by'] = 'date_created';
$params['sort_direction'] = 'asc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort_by'] = 'date_modified';
$params['sort_direction'] = 'desc';
$params['status_ids'] = [0, 1, 2, 3];
}
$cpOpportunities = $this->copperClient->opportunities()->search($params);
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
foreach ($cpOpportunities as $cpOpportunity) {
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', (string) $cpOpportunity['pipeline_id'])
->first();
if ($businessProcess === null) {
// Import it.
$businessProcess = $this->importStages(
[Stage::TYPE_OPPORTUNITY],
$cpOpportunity['pipeline_stage_id']
);
}
$stage = $businessProcess
->stages()
->where('crm_provider_id', (string) $cpOpportunity['pipeline_stage_id'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $cpOpportunity['pipeline_stage_id']);
}
$recordType = $businessProcess->recordTypes()->first();
$record = [
'crmId' => $cpOpportunity['id'],
'name' => $cpOpportunity['name'],
'value' => currency_format($cpOpportunity['monetary_value'], $cpOpportunity['monetary_unit']),
'won' => $cpOpportunity['status'] === 'Won',
'stage' => [
'id' => $stage->id_string,
'name' => $stage->name,
],
'recordType' => [
'id' => $recordType->id_string,
'name' => $recordType->name,
],
];
if ($ownerId && isset($cpOpportunity['assignee_id']) && $cpOpportunity['assignee_id'] === $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
/**
* @inheritdoc
*/
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = $cpTasks = [];
switch ($objectType) {
case 'lead':
$cpTasks = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->relatedTasks($objectId)
);
break;
case 'account':
$cpTasks = $this->copperClient->accounts()->relatedTasks($objectId);
break;
case 'contact':
if ($opportunityId) {
$cpTasks = $this->copperClient->opportunities()->relatedTasks($opportunityId);
} elseif ($objectType === 'contact') {
$cpTasks = $this->copperClient->contacts()->relatedTasks($objectId);
}
break;
}
foreach ($cpTasks as $cpTask) {
// We only get the ID itself returned, so pull out the full object.
try {
$cpTask = $this->copperClient->tasks()->find($cpTask['id']);
} catch (Exception $exception) {
$this->logger->error('[Copper] Error fetching task', [
'resource_id' => $cpTask['id'],
'error' => $exception->getMessage(),
]);
continue;
}
// Only allow open tasks.
if ($cpTask['status'] === 'Open') {
$data[] = [
'crmId' => $cpTask['id'],
'subject' => $cpTask['name'],
'due' => $cpTask['due_date']
? Carbon::createFromTimestamp($cpTask['due_date'])->format('Y-m-d\TH:i:sO')
: null,
'type' => null,
];
}
}
return $data;
}
/**
* Try to find email address in CRM service
*
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchExactlyByEmail(string $email, ?int $userId = null): ?array
{
$cpObjectType = 'contact';
$cpObjects = $this->copperClient->contacts()->search([
'emails' => $email,
'sort_by' => 'date_modified',
'sort_direction' => 'desc',
]);
if (empty($cpObjects)) {
$cpObjectType = 'lead';
$cpObjects = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->search([
'emails' => ...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.66456115,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.67586434,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.6871675,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.7150931,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.72639626,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.73769945,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"11","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"72","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Copper;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse GuzzleHttp\\Exception\\ClientException;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\CopperInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\FieldValue;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\PlaybookCategory;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\UserRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\Copper\\Api\\Client;\nuse Jiminny\\Services\\Crm\\Copper\\Api\\ClientFactory;\nuse Jiminny\\Services\\Crm\\Copper\\Exception\\RequestFailedException;\nuse Jiminny\\Services\\Crm\\Helpers\\FilterJoinedParticipants;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Services\\Crm\\Copper\\Traits\\SearchesCrmEntities;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\n\nclass Service extends BaseService implements\n CopperInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n use SearchesCrmEntities;\n private const int NOTE_BODY_MAX_LENGTH = 3000000;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const array STANDARD_OPPORTUNITY_FIELDS = [\n 'monetary_value' => [\n 'label' => 'Value',\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n 'type' => Field::TYPE_CURRENCY,\n ],\n 'pipeline_stage_id' => [\n 'label' => 'Stage',\n 'type' => Field::TYPE_PICKLIST,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n 'close_date' => [\n 'label' => 'Close date',\n 'type' => Field::TYPE_DATE,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n 'win_probability' => [\n 'label' => 'Win probability',\n 'type' => Field::TYPE_NUMBER,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n ];\n private const string UNSUPPORTED_OBJECT_TYPE = 'unsupported';\n private const string OPPORTUNITY_STATUS_OPEN = 'Open';\n private const string OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE = 'Opportunity import failed';\n private const string RESOURCE_UPDATE_FAILED_ERROR_MESSAGE = 'Failed to update resource';\n\n private FieldValueConverter $fieldValueConverter;\n private ClientFactory $clientFactory;\n private ?Client $copperClient = null;\n\n public function __construct(\n ClientFactory $clientFactory,\n FieldValueConverter $fieldValueConverter,\n private readonly UserRepository $userRepository,\n private readonly ProspectPhotoPathService $prospectPhotoPathService,\n private readonly CrmEntityRepository $crmEntityRepository\n ) {\n parent::__construct();\n\n $this->clientFactory = $clientFactory;\n $this->fieldValueConverter = $fieldValueConverter;\n }\n\n public function getDisplayName(): string\n {\n return 'Copper';\n }\n\n /**\n * Get the CRM entity repository (used by SearchesCrmEntities trait)\n */\n protected function getCrmEntityRepository(): CrmEntityRepository\n {\n return $this->crmEntityRepository;\n }\n\n public function getMinimumApiVersion(): string\n {\n return Client::MIN_API_VERSION;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_COPPER);\n }\n\n public function setUser(User $user): void\n {\n $this->configureSentryScope($user);\n\n $this->team = $user->getTeam();\n $this->teamService->setTeam($user->getTeam());\n $this->setConfiguration($user->getTeam()->getCrmConfiguration());\n\n // Reset state.\n $this->profile = $user->getProfile();\n\n if (! $this->profile instanceof Profile) {\n // Try to fetch their profile, maybe it was not yet imported?\n $this->profile = $this->getProfile($user);\n }\n }\n\n public function setConfiguration(Configuration $configuration): void\n {\n $this->config = $configuration;\n $this->copperClient = $this->clientFactory->create($configuration);\n\n if ($this->team === null) {\n $this->team = $configuration->getTeam();\n }\n }\n\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return $this->fieldValueConverter->convertFromCrm($fieldType, $fieldValue);\n }\n\n private function mapObjectType(string $objectType): string\n {\n $objectType = strtolower($objectType);\n\n switch ($objectType) {\n case Field::OBJECT_TASK:\n case Field::OBJECT_OPPORTUNITY:\n case Field::OBJECT_LEAD:\n $mappedType = $objectType;\n\n break;\n case Field::OBJECT_ACCOUNT:\n $mappedType = 'company';\n\n break;\n case Field::OBJECT_CONTACT:\n $mappedType = 'person';\n\n break;\n default:\n $mappedType = self::UNSUPPORTED_OBJECT_TYPE;\n\n break;\n }\n\n return $mappedType;\n }\n\n /**\n * @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact\n */\n protected function getFields(string $crmObject): array\n {\n $mappedObjectType = $this->mapObjectType($crmObject);\n\n if (! $this->isSupportedObjectType($mappedObjectType)) {\n return [];\n }\n\n $customFields = $this->copperClient->fields()->all();\n\n $filteredFields = array_filter(\n $customFields,\n static fn ($field) => in_array($mappedObjectType, $field['available_on'], true)\n );\n\n return array_map(\n fn (array $property) => [\n 'name' => $property['id'],\n 'label' => $property['name'],\n 'type' => $this->convertFieldType($property['data_type']),\n ],\n $filteredFields\n );\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {\n $defaultFields = FieldDefinitions::defaultTaskFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n $fieldFilters = FieldDefinitions::taskFollowupFieldsFilter();\n\n foreach ($fieldFilters as $data) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n public function syncFields(): void\n {\n $this->syncStandardFields();\n $this->syncCustomFields();\n }\n\n public function syncField(Field $field): void\n {\n if ($field->getCrmProviderId() === 'type') {\n /**\n * This field is a special case, it is not a custom field and is not returned by the Copper API.\n *\n * The field is created manually during layout setup.\n *\n * @see getDefaultFields()\n *\n * There is a separate endpoint to get the activity types.\n * @see importPicklistValues()\n */\n return;\n }\n\n if ($field->getCrmProviderId() === 'pipeline_stage_id') {\n // Not a custom type\n return;\n }\n\n $crmField = $this->copperClient->fields()->find($field->getCrmProviderId());\n $field->label = $crmField['name'];\n $field->type = $this->convertFieldType($crmField['data_type']);\n\n $field->save();\n }\n\n /**\n * @param string $fieldType How the data should be input\n */\n private function convertFieldType(string $fieldType): string\n {\n $fieldType = strtolower($fieldType);\n\n switch ($fieldType) {\n case 'dropdown':\n $convertedType = Field::TYPE_PICKLIST;\n\n break;\n case 'string':\n $convertedType = Field::TYPE_TEXT;\n\n break;\n case 'float':\n case 'percentage':\n $convertedType = Field::TYPE_NUMBER;\n\n break;\n case 'text':\n $convertedType = Field::TYPE_TEXTAREA;\n\n break;\n case 'checkbox':\n $convertedType = Field::TYPE_BOOLEAN;\n\n break;\n case Field::TYPE_DATE:\n case Field::TYPE_CURRENCY:\n case Field::TYPE_URL:\n $convertedType = $fieldType;\n\n break;\n default:\n $convertedType = Field::TYPE_UNSUPPORTED;\n\n break;\n }\n\n return $convertedType;\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $fieldValues = [];\n\n if ($field->object_type === 'opportunity' && $field->crm_provider_id === 'pipeline_stage_id') {\n return $this->importFieldValuesForDealInsights($field);\n }\n\n $values = [];\n\n if ($field->object_type === Field::OBJECT_TASK && $field->crm_provider_id === 'type') {\n $activityTypes = $this->copperClient->activityTypes()->all();\n\n /**\n * We ignore \"system\" activity types, disabled activity types and the \"Note\" activity type.\n */\n $activityTypes = array_filter(\n $activityTypes['user'],\n fn (array $activityType) => ! $activityType['is_disabled'] && $activityType['id'] !== 0\n );\n\n // Import all activity values.\n $i = 0;\n foreach ($activityTypes as $activityType) {\n $values[] = [\n 'value' => $activityType['id'],\n 'label' => mb_strimwidth($activityType['name'], 0, Field::LABEL_MAX_LENGTH),\n 'sequence' => $i++,\n ];\n }\n } else {\n // We just check for the field in the custom definitions.\n $crmField = $this->copperClient->fields()->find($field->crm_provider_id);\n\n // Import all values.\n foreach ($crmField['options'] as $option) {\n $values[] = [\n 'value' => $option['id'],\n 'label' => mb_strimwidth($option['name'], 0, 191),\n 'sequence' => $option['rank'],\n ];\n }\n }\n\n // Take the existing set of field values.\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n // For all current values, upsert the field.\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n $key = array_search($value['value'], $fieldsToPurge, false);\n if ($key !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n\n return $fieldValues;\n }\n\n /**\n *\n * @return FieldValue[]\n */\n private function importFieldValuesForDealInsights(Field $field): array\n {\n $fieldValues = [];\n $pipelines = $this->copperClient->pipelines()->all();\n\n foreach ($pipelines as $pipeline) {\n foreach ($pipeline['stages'] as $i => $dealStage) {\n $fieldValues[] = $field->values()->updateOrCreate(\n ['value' => $dealStage['id']],\n [\n 'label' => $dealStage['name'],\n 'sequence' => $i,\n ]\n );\n }\n }\n\n return $fieldValues;\n }\n\n /**\n * @inheritdoc\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n $missingStage = null;\n\n foreach ($types as $type) {\n if ($type === Stage::TYPE_LEAD) {\n $statuses = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leadStatuses()->all()\n );\n\n if (count($statuses) > 0) {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => BusinessProcess::TYPE_LEAD,\n ], [\n 'team_id' => $this->team->id,\n 'name' => BusinessProcess::TYPE_LEAD,\n 'type' => BusinessProcess::TYPE_LEAD,\n 'is_selectable' => true,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => BusinessProcess::TYPE_LEAD,\n ], [\n 'team_id' => $this->team->id,\n 'name' => BusinessProcess::TYPE_LEAD,\n 'is_selectable' => true,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $leadStatuses = [];\n foreach ($statuses as $status) {\n // Upsert all statuses for the team.\n $status = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $status['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($status['name'], 0, 50),\n 'label' => mb_strimwidth($status['name'], 0, 191),\n 'type' => Stage::TYPE_LEAD,\n 'sequence' => $status['order'],\n 'is_selectable' => true,\n ]);\n\n if ($missingStageName && $missingStageName === $status['id']) {\n $missingStage = $status;\n }\n\n $leadStatuses[] = $status['id'];\n }\n\n $businessProcess->stages()->sync($leadStatuses);\n }\n } else {\n // We create a business process to contain the pipeline, and later store all stages against it.\n foreach ($this->copperClient->pipelines()->all() as $pipeline) {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $pipeline['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline['name'], 0, 150),\n 'type' => BusinessProcess::TYPE_OPPORTUNITY,\n 'is_selectable' => true,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $pipeline['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline['name'], 0, 150),\n 'is_selectable' => true,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $stages = [];\n\n foreach ($pipeline['stages'] as $i => $dealStage) {\n // Upsert all stages for the team.\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $dealStage['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($dealStage['name'], 0, 50),\n 'label' => mb_strimwidth($dealStage['name'], 0, 191),\n 'type' => Stage::TYPE_OPPORTUNITY,\n 'sequence' => $i,\n 'is_selectable' => true,\n 'probability' => $dealStage['win_probability'],\n ]);\n\n if ($missingStageName && $missingStageName === $dealStage['id']) {\n $missingStage = $stage;\n }\n\n $stages[] = $stage['id'];\n }\n\n $businessProcess->stages()->sync($stages);\n }\n }\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n\n $cpLeads = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->paginate([\n 'minimum_modified_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ])\n );\n\n foreach ($cpLeads as $cpLead) {\n // Only sync if previously imported.\n if ($this->hasLead($cpLead['id']) === false) {\n $this->importLead($cpLead);\n $syncCount++;\n }\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n $cpLead = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->find($crmId)\n );\n\n if (\\count($cpLead) === 0) {\n return null;\n }\n\n return $this->importLead($cpLead);\n }\n\n /**\n * @inheritdoc\n */\n private function importLead($crmData): ?Lead\n {\n $countryCode = null;\n if (! empty($crmData['address']) && isset($crmData['address']['country'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $mobilePhone = $parsedNumber = null;\n if (! empty($crmData['phone_numbers'])) {\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n if ($phoneNumber['category'] === 'mobile') {\n $mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);\n } else {\n $parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);\n }\n }\n }\n\n $name = $crmData['name'];\n\n if (empty($crmData['company_name'])) {\n $company = 'Unknown';\n } else {\n $company = mb_strimwidth($crmData['company_name'], 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['websites']) === false) {\n $domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $email = null;\n if (empty($crmData['email']) === false) {\n $email = mb_strimwidth($crmData['email']['email'], 0, 80);\n }\n\n $stage = $this->config\n ->stages()\n ->where('crm_provider_id', (string) $crmData['status_id'])\n ->where('type', Stage::TYPE_LEAD)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status_id']);\n }\n\n if (! $stage instanceof Stage) {\n return null;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($name, 0, 191),\n 'company' => $company,\n 'domain' => $domain,\n 'title' => $crmData['title'] ? mb_strimwidth($crmData['title'], 0, 128) : null,\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'mobile_phone' => $mobilePhone,\n 'stage_id' => $stage->id,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Lead::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'country_code' => $countryCode,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $cpAccounts = $this->copperClient->accounts()->paginate([\n 'minimum_modified_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ]);\n\n foreach ($cpAccounts as $cpAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($cpAccount['id'])) {\n $this->importAccount($cpAccount);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n $cpAccount = $this->copperClient->accounts()->find($crmId);\n\n if (empty($cpAccount)) {\n return null;\n }\n\n return $this->importAccount($cpAccount);\n }\n\n /**\n * @inheritdoc\n */\n private function importAccount($crmData): Account\n {\n $countryCode = null;\n if (empty($crmData['address']) === false && $crmData['address']['country']) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $name = $crmData['name'];\n\n $parsedNumber = null;\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n $parsedNumber = parsePhoneNumber($countryCode, $phoneNumber['number']);\n }\n\n $domain = null;\n if (empty($crmData['websites']) === false) {\n $domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Account::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'country_code' => $countryCode,\n 'domain' => $domain,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->copperClient,\n ]);\n $strategies = $strategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n\n try {\n foreach ($strategies as $syncStrategy) {\n foreach ($syncStrategy->fetchOpportunities($parameters) as $opportunityData) {\n $this->importOpportunity($opportunityData);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n $this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => $exception->getMessage(),\n ]);\n }\n\n return $syncCount;\n }\n\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->copperClient,\n ]);\n $strategy = $strategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n $parameters['crm_id'] = $crmId;\n\n $cpOpportunity = $strategy->fetchOpportunities($parameters);\n\n return $this->importOpportunity($cpOpportunity);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n $companyId = (string) $crmData['company_id'];\n\n if (empty($companyId)) {\n $this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => 'No company id',\n ]);\n\n return null;\n }\n\n $account = $this->config->accounts()->where('crm_provider_id', $companyId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($companyId);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', (string) $crmData['pipeline_id'])\n ->first();\n\n if ($businessProcess === null) {\n // It is possible for some deals to not be in a pipeline.\n $this->logger->warning(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => 'Missing pipeline',\n ]);\n\n return null;\n }\n\n $stage = $businessProcess\n ->stages()\n ->where('crm_provider_id', (string) $crmData['pipeline_stage_id'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n $this->logger->info('Stage not found, importing', [\n 'pipeline_id' => $crmData['pipeline_id'],\n 'stage_id' => $crmData['pipeline_stage_id'],\n ]);\n\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['pipeline_stage_id']);\n }\n\n $recordType = $businessProcess->recordTypes()->first();\n $closeDate = null;\n $isClosed = $crmData['status'] !== self::OPPORTUNITY_STATUS_OPEN;\n\n if ($crmData['close_date']) {\n $closeDate = Carbon::parse($crmData['close_date'])->format('Y-m-d');\n }\n\n $data = [\n 'team_id' => $this->team->getId(),\n 'account_id' => $account->id,\n 'user_id' => $profile->user_id ?? null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($crmData['name'], 0, 128),\n 'value' => $crmData['monetary_value'],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['monetary_unit']),\n 'close_date' => $closeDate,\n 'is_closed' => $isClosed,\n 'is_won' => $crmData['status'] === 'Won',\n 'stage_id' => $stage->id,\n 'record_type_id' => $recordType->id ?? null,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n /** @var Opportunity $opportunity */\n $opportunity = $this->config\n ->opportunities()\n ->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data)\n ;\n\n // import external fields into crm_field_data if present\n $dealInsightsFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData($crmData, $dealInsightsFields, $opportunity->id);\n\n return $opportunity;\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n * @param string[] $dealInsightsFields\n */\n public function importOpportunityCrmFieldData(\n array $opportunityData,\n array $dealInsightsFields,\n int $opportunityId\n ): void {\n foreach ($dealInsightsFields as $fieldName) {\n $field = $this->config->fields()->with('entities')\n ->where('crm_provider_id', $fieldName)\n ->where('object_type', Field::OBJECT_OPPORTUNITY)\n ->first();\n\n if (! $field instanceof Field) {\n $this->logger->warning('Field not found', [\n 'field' => $fieldName,\n 'opportunity_id' => $opportunityId,\n ]);\n\n continue;\n }\n\n $entity = $field->getEntities()->first();\n\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $fieldValue = $this->extractFieldValue($opportunityData, $fieldName);\n $normalizedValue = $this->normalizeValue($field->getType(), (string) $fieldValue, true);\n\n $field->data()\n ->updateOrCreate([\n 'crm_layout_entity_id' => $entity->id,\n 'crm_field_id' => $field->id,\n 'object_type' => 'opportunity',\n 'object_id' => $opportunityId,\n ], ['value' => $normalizedValue])\n ;\n }\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $cpContacts = $this->copperClient->contacts()->paginate([\n 'minimum_interaction_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ]);\n\n foreach ($cpContacts as $cpContact) {\n // Only sync if previously imported.\n if ($this->hasContact($cpContact['id'])) {\n $this->importContact($cpContact);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n throw $exception;\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n $cpContact = $this->copperClient->contacts()->find($crmId);\n\n if (empty($cpContact)) {\n return null;\n }\n\n return $this->importContact($cpContact);\n }\n\n /**\n * @inheritdoc\n */\n private function importContact($crmData): Contact\n {\n $account = null;\n if ($crmData['company_id']) {\n $account = $this->team\n ->crm\n ->accounts()\n ->where('crm_provider_id', (string) $crmData['company_id'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['company_id']);\n }\n }\n\n $countryCode = null;\n if (empty($crmData['address']) === false && $crmData['address']['country']) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $mobilePhone = $parsedNumber = null;\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n if ($phoneNumber['category'] === 'mobile') {\n $mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);\n } else {\n $parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);\n }\n }\n\n $email = null;\n if (empty($crmData['emails']) === false) {\n $email = mb_strimwidth($crmData['emails'][0]['email'], 0, 80);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => $crmData['name'],\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'mobile_phone' => $mobilePhone ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'title' => $crmData['title'],\n 'country_code' => $countryCode,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Contact::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function buildContactPhone(?string $countryCode, ?string $number): ?array\n {\n if ($number) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($number, 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n return $parsedNumber;\n }\n\n private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string\n {\n return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n $organization = $this->copperClient->organisation()->all();\n\n if ($this->config->crm_provider_id !== $organization['id']) {\n $this->config->update(['crm_provider_id' => $organization['id']]);\n }\n }\n\n private function syncCustomFields(): void\n {\n foreach ($this->getFieldTypes() as $fieldType) {\n $currentFields = $this->getFields($fieldType);\n\n foreach ($currentFields as $field) {\n /** @var Field $field */\n $field = $this->config->fields()->updateOrCreate([\n 'crm_provider_id' => $field['name'],\n 'object_type' => $fieldType,\n ], [\n 'label' => mb_strimwidth($field['label'], 0, Field::LABEL_MAX_LENGTH),\n 'type' => $field['type'],\n ]);\n\n if ($field->getType() === Field::TYPE_PICKLIST) {\n $this->importPicklistValues($field);\n }\n }\n }\n\n $this->config->save();\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n parent::OBJECT_LEAD,\n parent::OBJECT_ACCOUNT,\n parent::OBJECT_CONTACT,\n parent::OBJECT_OPPORTUNITY,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $profiles = $this->copperClient->users()->all();\n\n foreach ($profiles as $profile) {\n $user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);\n\n // Only import profiles for users we have locally.\n if ($user) {\n $profile = $user->crmProfile()->updateOrCreate([\n 'crm_configuration_id' => $this->config->id,\n 'crm_provider_id' => $profile['id'],\n ]);\n\n if ($userToSearch && $userToSearch->id === $user->id) {\n return $profile;\n }\n }\n }\n\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'task',\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields(ucfirst($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))\n );\n\n if (\\count($changedFields) > 0) {\n $fields = implode(',', $newFields);\n $this->logger->debug(\n ucfirst($fieldType)\n . ' fields changed from '\n . $this->profile->{$fieldType . '_fields'}\n . ' to: '\n . $fields\n );\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (\\Exception $exception) {\n $this->logger->error('No access to ' . $fieldType . ' object, skipping...');\n\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $scopeValues = array_map(fn ($scope) => is_string($scope) ? $scope : $scope->value, $scopes);\n $cacheKey = sprintf('copper-search-%d-%s-%s-%d-%d', $this->team->id, $name, implode('-', $scopeValues), $count, $offset);\n\n return Cache::remember($cacheKey, 300, function () use ($name, $scopes, $count, $offset) {\n // Try local search first\n $localResults = $this->searchLocally($name, $scopes, $count, $offset);\n\n // If no local results, fall back to remote API search\n if (empty($localResults)) {\n return $this->searchRemotely($name, $scopes, $count, $offset);\n }\n\n return $localResults;\n });\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $params = [\n 'company_ids' => [$account->crm_provider_id],\n 'status_ids' => [0], // The integer values are 0, 1, 2, 3, for \"Open\", \"Won\", \"Lost\", and \"Abandoned\".\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ];\n\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort_by'] = 'date_modified';\n $params['sort_direction'] = 'desc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort_by'] = 'date_created';\n $params['sort_direction'] = 'desc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort_by'] = 'date_created';\n $params['sort_direction'] = 'asc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort_by'] = 'date_modified';\n $params['sort_direction'] = 'desc';\n $params['status_ids'] = [0, 1, 2, 3];\n }\n\n $cpOpportunities = $this->copperClient->opportunities()->search($params);\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n foreach ($cpOpportunities as $cpOpportunity) {\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', (string) $cpOpportunity['pipeline_id'])\n ->first();\n\n if ($businessProcess === null) {\n // Import it.\n $businessProcess = $this->importStages(\n [Stage::TYPE_OPPORTUNITY],\n $cpOpportunity['pipeline_stage_id']\n );\n }\n\n $stage = $businessProcess\n ->stages()\n ->where('crm_provider_id', (string) $cpOpportunity['pipeline_stage_id'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $cpOpportunity['pipeline_stage_id']);\n }\n\n $recordType = $businessProcess->recordTypes()->first();\n\n $record = [\n 'crmId' => $cpOpportunity['id'],\n 'name' => $cpOpportunity['name'],\n 'value' => currency_format($cpOpportunity['monetary_value'], $cpOpportunity['monetary_unit']),\n 'won' => $cpOpportunity['status'] === 'Won',\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n\n if ($ownerId && isset($cpOpportunity['assignee_id']) && $cpOpportunity['assignee_id'] === $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $cpTasks = [];\n\n switch ($objectType) {\n case 'lead':\n $cpTasks = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->relatedTasks($objectId)\n );\n\n break;\n\n case 'account':\n $cpTasks = $this->copperClient->accounts()->relatedTasks($objectId);\n\n break;\n case 'contact':\n if ($opportunityId) {\n $cpTasks = $this->copperClient->opportunities()->relatedTasks($opportunityId);\n } elseif ($objectType === 'contact') {\n $cpTasks = $this->copperClient->contacts()->relatedTasks($objectId);\n }\n\n break;\n }\n\n foreach ($cpTasks as $cpTask) {\n // We only get the ID itself returned, so pull out the full object.\n try {\n $cpTask = $this->copperClient->tasks()->find($cpTask['id']);\n } catch (Exception $exception) {\n $this->logger->error('[Copper] Error fetching task', [\n 'resource_id' => $cpTask['id'],\n 'error' => $exception->getMessage(),\n ]);\n\n continue;\n }\n\n // Only allow open tasks.\n if ($cpTask['status'] === 'Open') {\n $data[] = [\n 'crmId' => $cpTask['id'],\n 'subject' => $cpTask['name'],\n 'due' => $cpTask['due_date']\n ? Carbon::createFromTimestamp($cpTask['due_date'])->format('Y-m-d\\TH:i:sO')\n : null,\n 'type' => null,\n ];\n }\n }\n\n return $data;\n }\n\n /**\n * Try to find email address in CRM service\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $cpObjectType = 'contact';\n\n $cpObjects = $this->copperClient->contacts()->search([\n 'emails' => $email,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (empty($cpObjects)) {\n $cpObjectType = 'lead';\n $cpObjects = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'emails' => $email,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (empty($cpObjects)) {\n return null;\n }\n\n // Search returns an array of results, but we only want the first\n $cpObject = reset($cpObjects);\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember === false) {\n $cpObjectType = 'contact';\n $cpObject = $this->copperClient->contacts()->search([\n 'phone_number' => $phone,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (\\count($cpObject) === 0) {\n $cpObjectType = 'lead';\n $cpObject = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'phone_number' => $phone,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (empty($cpObject)) {\n return null;\n }\n\n $cpObject = reset($cpObject);\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n return null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n $result = \\Cache::remember($this->team->id . $name, 60, function () use ($name, $userId) {\n $cpObjectType = 'contact';\n $cpObject = $this->copperClient->contacts()->search([\n 'name' => $name,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (\\count($cpObject) === 0) {\n $cpObjectType = 'lead';\n $cpObject = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'name' => $name,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (! empty($cpObject)) {\n $cpObject = reset($cpObject);\n }\n\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n private function convertCrmData(array $object, string $objectType, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n if ($objectType === 'lead') {\n $lead = $this->importLead($object);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } else {\n $contact = $this->importContact($object);\n $account = $contact->account;\n\n if ($contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $cpOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact->crm_provider_id,\n $userId,\n );\n\n if (! empty($cpOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($cpOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n } catch (\\Exception $e) {\n // Nothing to see here.\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n public function saveActivity(Activity $activity): Activity\n {\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n $activity = $this->buildCallPayload($activity);\n\n break;\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildTextMessagePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n private function convertActivityAssociations(Activity $activity): array\n {\n if ($activity->lead) {\n $type = 'lead';\n $id = $activity->lead->crm_provider_id;\n } elseif ($activity->contact) {\n $type = 'person';\n $id = $activity->contact->crm_provider_id;\n } elseif ($activity->opportunity) {\n $type = 'opportunity';\n $id = $activity->opportunity->crm_provider_id;\n } else {\n $type = 'company';\n $id = $activity->account->crm_provider_id;\n }\n\n return [\n 'type' => $type,\n 'id' => $id,\n ];\n }\n\n private function convertActivityType(PlaybookCategory $activityType): array\n {\n return [\n 'category' => 'user',\n 'id' => $this->getCrmType($activityType)->value,\n ];\n }\n\n /**\n * @throws CrmException\n */\n private function buildCallPayload(Activity $activity): Activity\n {\n try {\n if ($activity->crm_provider_id) {\n // The activity should be logged under the existing Task (not Activity).\n $newActivityType = $this->getCrmType($activity->category);\n if ($newActivityType === null) {\n $message = sprintf('[Copper] invalid CRM Custom Activity Type: %s', $activity->category);\n\n throw new CrmException($message, 400);\n }\n $this->copperClient->tasks()->update($activity->crm_provider_id, [\n 'status' => 'Completed',\n 'custom_activity_type_id' => $newActivityType->value,\n 'details' => $this->generateActivityDescription($activity),\n ]);\n } else {\n if ($this->getCrmType($activity->category) === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n if ($this->getCrmType($activity->category)->value === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n // Just create an activity.\n $cpActivity = $this->copperClient->activities()->create([\n 'user_id' => $this->profile->crm_provider_id,\n 'activity_date' => $activity->scheduled_start_time->timestamp,\n 'parent' => $this->convertActivityAssociations($activity),\n 'type' => $this->convertActivityType($activity->category),\n 'details' => $this->generateActivityDescription($activity),\n ]);\n\n $activity->crm_provider_id = $cpActivity['id'];\n $activity->save();\n }\n } catch (ClientException $exception) {\n //Log all errors to Sentry\n \\Sentry::captureException($exception);\n\n $response = $exception->getResponse();\n\n $responseBody = $response->getBody();\n $message = $responseBody;\n $errorCode = $response->getStatusCode();\n\n $jsonResponse = json_decode($responseBody, true);\n if (isset($jsonResponse[0]['message'])) {\n $message = $jsonResponse[0]['message'];\n }\n\n throw new CrmException($message, $errorCode);\n }\n\n return $activity;\n }\n\n private function buildTextMessagePayload(Activity $activity): Activity\n {\n if ($this->getCrmType($activity->category) === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n if ($this->getCrmType($activity->category)->value === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n $cpActivity = $this->copperClient->activities()->create([\n 'user_id' => $this->profile->crm_provider_id,\n 'activity_date' => $activity->created_at->timestamp,\n 'parent' => $this->convertActivityAssociations($activity),\n 'type' => $this->convertActivityType($activity->category),\n 'details' => $this->generateActivityDescription($activity),\n ]);\n\n $activity->crm_provider_id = $cpActivity['id'];\n $activity->save();\n\n return $activity;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = '';\n\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n $description = 'Jiminny Call Summary' . PHP_EOL . PHP_EOL;\n $description .= 'Call Duration: ' . $activity->duration_for_humans . PHP_EOL . PHP_EOL;\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= 'Dialed: ' . $activity->to->phone_number . PHP_EOL . PHP_EOL;\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= 'Notetaker removed from this meeting' . PHP_EOL . PHP_EOL;\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= 'Notetaker did not join due to recording consent not being provided by attendees' . PHP_EOL . PHP_EOL;\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= 'Review Activity:' . PHP_EOL . $playbackUrl . PHP_EOL . PHP_EOL;\n }\n\n if ($activity->getCrmType() === Activity::TYPE_CONFERENCE) {\n $description .= 'Attendees:'\n . PHP_EOL\n . (new FilterJoinedParticipants())->toString($activity);\n }\n\n if (\\count($activity->notes) > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Notes: ' . PHP_EOL;\n\n foreach ($activity->notes as $note) {\n $nTime = (int) ceil($note->time);\n $time = ($nTime > 3600) ? gmdate('H:i:s', $nTime) : gmdate('i:s', $nTime);\n $description .= $time . ' ' . $note->note . PHP_EOL;\n }\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Coaching Chat: ' . PHP_EOL;\n\n foreach ($messages->get() as $message) {\n $description .= $message->participant->name . ': ' . $message->message . PHP_EOL;\n }\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Customer Chat: ' . PHP_EOL;\n\n foreach ($messages->get() as $message) {\n $description .= $message->participant->name . ': ' . $message->message . PHP_EOL;\n }\n }\n\n if ($activity->summary) {\n $description .= PHP_EOL . PHP_EOL . 'Summary: ' . PHP_EOL . $activity->summary;\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $description = $activity->description;\n\n break;\n }\n\n return $description;\n }\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // This is the user provided activity subject field.\n if (empty($fields['type'])) {\n return null;\n }\n\n $reminder = null;\n if (empty($fields['reminder_date']) === false) {\n $formatReminder = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['reminder_date']);\n $reminder = $formatReminder->getTimestamp();\n }\n\n $due = null;\n if (empty($fields['due_date']) === false) {\n $formatDue = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['due_date']);\n $due = $formatDue->getTimestamp();\n }\n\n $data = [\n 'custom_activity_type_id' => $fields['type'],\n 'status' => 'Open',\n 'assignee_id' => $this->profile->crm_provider_id,\n 'due_date' => $due,\n 'details' => $fields['details'] ?? '',\n 'reminder_date' => $reminder,\n 'name' => $fields['name'] ?? 'Follow-up',\n 'related_resource' => $this->convertActivityAssociations($activity),\n 'custom_fields' => $this->fetchCustomFieldData($activity, Field::OBJECT_TASK),\n ];\n\n // We don't actually create a corresponding activity object on our side yet.\n return $this->copperClient->tasks()->create($data)['id'];\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws \\Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // Generate activity transcription.\n $transcriptionData = $this->generateTranscription($activity);\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $transcripts = mb_strimwidth($transcriptionData, 0, static::NOTE_BODY_MAX_LENGTH);\n\n $data = [\n 'user_id' => $this->profile->crm_provider_id,\n 'type' => [\n 'category' => 'user',\n 'id' => 0, // This creates a note.\n ],\n 'activity_date' => time(),\n 'details' => $transcripts,\n 'parent' => $this->convertActivityAssociations($activity),\n ];\n\n $cpActivity = $this->copperClient->activities()->create($data);\n\n // Store CRM Activity ID in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $cpActivity['id'];\n $transcription->save();\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n if ($crmObject instanceof Lead) {\n $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->update($crmObject->crm_provider_id, [\n 'status_id' => $stage->crm_provider_id,\n ])\n );\n } else {\n $this->copperClient->opportunities()->update($crmObject->crm_provider_id, [\n 'pipeline_stage_id' => $stage->crm_provider_id,\n ]);\n }\n }\n\n public function prepareValueForUpdate(array $params): array\n {\n return [$params['fieldName'] => $params['fieldValue']];\n }\n\n /*\n * @inheritdoc\n */\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $preparedData = $data;\n\n if ($objectType === Field::OBJECT_OPPORTUNITY) {\n $preparedData = $this->prepareOpportunityFieldsForUpdate($data);\n }\n\n try {\n $this->copperClient\n ->createResourceFromObjectType($objectType)\n ->update($objectId, $preparedData)\n ;\n } catch (Exception $e) {\n $this->logger->error(self::RESOURCE_UPDATE_FAILED_ERROR_MESSAGE, [\n 'resource_id' => $objectId,\n 'data' => $preparedData,\n 'error' => $e->getMessage(),\n ]);\n\n throw new CrmException(self::RESOURCE_UPDATE_FAILED_ERROR_MESSAGE, $e->getCode(), $e);\n }\n }\n\n /**\n * @param array<string,string> $fieldData\n *\n * @throws CrmException\n *\n * @return array<string,array<int,array<string,bool|float|int|string|null>>|bool|float|int|string|null>\n */\n private function prepareOpportunityFieldsForUpdate(array $fieldData): array\n {\n $preparedData = [];\n $customFields = [];\n\n foreach ($fieldData as $fieldName => $fieldValue) {\n $field = $this->config\n ->fields()\n ->where('crm_provider_id', $fieldName)\n ->first();\n\n if (! $field instanceof Field) {\n throw new CrmException('Field not found');\n }\n\n $convertedValue = $this->fieldValueConverter->convertToCrm($field->getType(), $fieldValue);\n\n if ($this->isStandardField($fieldName)) {\n $preparedData[$fieldName] = $convertedValue;\n\n continue;\n }\n\n $customFields[] = [\n 'custom_field_definition_id' => $fieldName,\n 'value' => $convertedValue,\n ];\n }\n\n if (! empty($customFields)) {\n $preparedData['custom_fields'] = $customFields;\n }\n\n return $preparedData;\n }\n\n /*\n * @inheritdoc\n */\n public function getRecord(string $objectType, string $objectId, array $fields = []): array\n {\n return $this->copperClient->createResourceFromObjectType($objectType)->find($objectId);\n }\n\n private function fetchCustomFieldData(Activity $activity, string $objectType): array\n {\n $payload = [];\n\n $fieldData = FieldData::where([\n 'object_id' => $activity->id,\n ])->whereHas('field', function ($query) use ($objectType) {\n $query->where('object_type', $objectType);\n })->get();\n\n foreach ($fieldData as $data) {\n // Add the field and value to the payload.\n $payload += [\n 'custom_field_definition_id' => $data->field->crm_provider_id,\n 'value' => $data->value,\n ];\n }\n\n return $payload;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $baseUrl = 'https://app.prosperworks.com/companies/' . $this->config->crm_provider_id . '/app#/';\n switch ($objectType) {\n case 'lead':\n $url = $baseUrl . 'leads/' . $providerId;\n\n break;\n\n case 'account':\n $url = $baseUrl . 'organization/' . $providerId;\n\n break;\n\n case 'contact':\n $url = $baseUrl . 'contact/' . $providerId;\n\n break;\n\n case 'opportunity':\n $url = $baseUrl . 'deal/' . $providerId;\n\n break;\n\n default:\n case 'task':\n case 'activity':\n // Sadly we can't deeplink to these in Copper UI.\n $url = null;\n }\n\n return $url;\n }\n\n /**\n * Generate transcription for the activity.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! ($this->config->store_transcript)) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n return $this->transcriptionService\n ->findTranscriptionByActivity($activity)\n ->map(static function (array $transcriptionSegment): string {\n return $transcriptionSegment['formattedStartsAt'] . ' | ' . $transcriptionSegment['transcript'];\n })\n ->implode(PHP_EOL);\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n *\n * @return int|string|bool|float|null\n */\n private function extractFieldValue(array $opportunityData, string $fieldName)\n {\n $fieldValue = $this->isStandardField($fieldName)\n ? $opportunityData[$fieldName]\n : $this->resolveCustomFieldFromOpportunityData($opportunityData, $fieldName);\n\n if (is_array($fieldValue)) {\n $fieldValue = implode(', ', $fieldValue);\n }\n\n return $fieldValue;\n }\n\n private function isStandardField(string $fieldName): bool\n {\n return array_key_exists($fieldName, self::STANDARD_OPPORTUNITY_FIELDS);\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n *\n * @return string|int|float|bool|null|array<string, mixed>\n */\n private function resolveCustomFieldFromOpportunityData(array $opportunityData, string $fieldName)\n {\n $fieldData = array_filter(\n $opportunityData['custom_fields'],\n static fn ($field) => (string) $field['custom_field_definition_id'] === $fieldName\n );\n\n return array_pop($fieldData)['value'] ?? '';\n }\n\n private function isSupportedObjectType(string $objectType): bool\n {\n return $objectType !== self::UNSUPPORTED_OBJECT_TYPE;\n }\n\n private function syncStandardFields(): void\n {\n foreach (self::STANDARD_OPPORTUNITY_FIELDS as $fieldId => $fieldData) {\n $this->config->fields()->updateOrCreate([\n 'crm_provider_id' => mb_strimwidth($fieldId, 0, 128),\n 'object_type' => Field::OBJECT_OPPORTUNITY,\n ], [\n 'label' => mb_strimwidth($fieldData['label'], 0, Field::LABEL_MAX_LENGTH),\n 'type' => $fieldData['type'],\n ]);\n }\n\n $this->importStages([Stage::TYPE_OPPORTUNITY]);\n }\n\n private function requestWithExceptionHandling(\\Closure $apiRequest): iterable\n {\n try {\n return $apiRequest();\n } catch (\\Exception $exception) {\n if ($exception->getCode() === 403) {\n // Object might not be supported\n return [];\n }\n\n \\Sentry::captureException($exception);\n\n return [];\n }\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n if ($this->copperClient === null) {\n return false;\n }\n\n $task = $this->copperClient->tasks()->find($crmProviderId);\n\n return ! empty($task);\n } catch (HttpNotFoundException) {\n // Task not found in CRM - this is expected and permanent\n $this->logger->info('[Copper] Task not found during verification', [\n 'task_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n } catch (RequestFailedException $e) {\n // Handle 404 responses from Copper API\n if ($e->getCode() === 404) {\n $this->logger->info('[Copper] Task not found during verification (404)', [\n 'task_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n\n // Re-throw other Copper exceptions for retry\n throw $e;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Copper;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse GuzzleHttp\\Exception\\ClientException;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\CopperInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\FieldValue;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\PlaybookCategory;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\UserRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\Copper\\Api\\Client;\nuse Jiminny\\Services\\Crm\\Copper\\Api\\ClientFactory;\nuse Jiminny\\Services\\Crm\\Copper\\Exception\\RequestFailedException;\nuse Jiminny\\Services\\Crm\\Helpers\\FilterJoinedParticipants;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Services\\Crm\\Copper\\Traits\\SearchesCrmEntities;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\n\nclass Service extends BaseService implements\n CopperInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n use SearchesCrmEntities;\n private const int NOTE_BODY_MAX_LENGTH = 3000000;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const array STANDARD_OPPORTUNITY_FIELDS = [\n 'monetary_value' => [\n 'label' => 'Value',\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n 'type' => Field::TYPE_CURRENCY,\n ],\n 'pipeline_stage_id' => [\n 'label' => 'Stage',\n 'type' => Field::TYPE_PICKLIST,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n 'close_date' => [\n 'label' => 'Close date',\n 'type' => Field::TYPE_DATE,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n 'win_probability' => [\n 'label' => 'Win probability',\n 'type' => Field::TYPE_NUMBER,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n ];\n private const string UNSUPPORTED_OBJECT_TYPE = 'unsupported';\n private const string OPPORTUNITY_STATUS_OPEN = 'Open';\n private const string OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE = 'Opportunity import failed';\n private const string RESOURCE_UPDATE_FAILED_ERROR_MESSAGE = 'Failed to update resource';\n\n private FieldValueConverter $fieldValueConverter;\n private ClientFactory $clientFactory;\n private ?Client $copperClient = null;\n\n public function __construct(\n ClientFactory $clientFactory,\n FieldValueConverter $fieldValueConverter,\n private readonly UserRepository $userRepository,\n private readonly ProspectPhotoPathService $prospectPhotoPathService,\n private readonly CrmEntityRepository $crmEntityRepository\n ) {\n parent::__construct();\n\n $this->clientFactory = $clientFactory;\n $this->fieldValueConverter = $fieldValueConverter;\n }\n\n public function getDisplayName(): string\n {\n return 'Copper';\n }\n\n /**\n * Get the CRM entity repository (used by SearchesCrmEntities trait)\n */\n protected function getCrmEntityRepository(): CrmEntityRepository\n {\n return $this->crmEntityRepository;\n }\n\n public function getMinimumApiVersion(): string\n {\n return Client::MIN_API_VERSION;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_COPPER);\n }\n\n public function setUser(User $user): void\n {\n $this->configureSentryScope($user);\n\n $this->team = $user->getTeam();\n $this->teamService->setTeam($user->getTeam());\n $this->setConfiguration($user->getTeam()->getCrmConfiguration());\n\n // Reset state.\n $this->profile = $user->getProfile();\n\n if (! $this->profile instanceof Profile) {\n // Try to fetch their profile, maybe it was not yet imported?\n $this->profile = $this->getProfile($user);\n }\n }\n\n public function setConfiguration(Configuration $configuration): void\n {\n $this->config = $configuration;\n $this->copperClient = $this->clientFactory->create($configuration);\n\n if ($this->team === null) {\n $this->team = $configuration->getTeam();\n }\n }\n\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return $this->fieldValueConverter->convertFromCrm($fieldType, $fieldValue);\n }\n\n private function mapObjectType(string $objectType): string\n {\n $objectType = strtolower($objectType);\n\n switch ($objectType) {\n case Field::OBJECT_TASK:\n case Field::OBJECT_OPPORTUNITY:\n case Field::OBJECT_LEAD:\n $mappedType = $objectType;\n\n break;\n case Field::OBJECT_ACCOUNT:\n $mappedType = 'company';\n\n break;\n case Field::OBJECT_CONTACT:\n $mappedType = 'person';\n\n break;\n default:\n $mappedType = self::UNSUPPORTED_OBJECT_TYPE;\n\n break;\n }\n\n return $mappedType;\n }\n\n /**\n * @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact\n */\n protected function getFields(string $crmObject): array\n {\n $mappedObjectType = $this->mapObjectType($crmObject);\n\n if (! $this->isSupportedObjectType($mappedObjectType)) {\n return [];\n }\n\n $customFields = $this->copperClient->fields()->all();\n\n $filteredFields = array_filter(\n $customFields,\n static fn ($field) => in_array($mappedObjectType, $field['available_on'], true)\n );\n\n return array_map(\n fn (array $property) => [\n 'name' => $property['id'],\n 'label' => $property['name'],\n 'type' => $this->convertFieldType($property['data_type']),\n ],\n $filteredFields\n );\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {\n $defaultFields = FieldDefinitions::defaultTaskFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n $fieldFilters = FieldDefinitions::taskFollowupFieldsFilter();\n\n foreach ($fieldFilters as $data) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n public function syncFields(): void\n {\n $this->syncStandardFields();\n $this->syncCustomFields();\n }\n\n public function syncField(Field $field): void\n {\n if ($field->getCrmProviderId() === 'type') {\n /**\n * This field is a special case, it is not a custom field and is not returned by the Copper API.\n *\n * The field is created manually during layout setup.\n *\n * @see getDefaultFields()\n *\n * There is a separate endpoint to get the activity types.\n * @see importPicklistValues()\n */\n return;\n }\n\n if ($field->getCrmProviderId() === 'pipeline_stage_id') {\n // Not a custom type\n return;\n }\n\n $crmField = $this->copperClient->fields()->find($field->getCrmProviderId());\n $field->label = $crmField['name'];\n $field->type = $this->convertFieldType($crmField['data_type']);\n\n $field->save();\n }\n\n /**\n * @param string $fieldType How the data should be input\n */\n private function convertFieldType(string $fieldType): string\n {\n $fieldType = strtolower($fieldType);\n\n switch ($fieldType) {\n case 'dropdown':\n $convertedType = Field::TYPE_PICKLIST;\n\n break;\n case 'string':\n $convertedType = Field::TYPE_TEXT;\n\n break;\n case 'float':\n case 'percentage':\n $convertedType = Field::TYPE_NUMBER;\n\n break;\n case 'text':\n $convertedType = Field::TYPE_TEXTAREA;\n\n break;\n case 'checkbox':\n $convertedType = Field::TYPE_BOOLEAN;\n\n break;\n case Field::TYPE_DATE:\n case Field::TYPE_CURRENCY:\n case Field::TYPE_URL:\n $convertedType = $fieldType;\n\n break;\n default:\n $convertedType = Field::TYPE_UNSUPPORTED;\n\n break;\n }\n\n return $convertedType;\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $fieldValues = [];\n\n if ($field->object_type === 'opportunity' && $field->crm_provider_id === 'pipeline_stage_id') {\n return $this->importFieldValuesForDealInsights($field);\n }\n\n $values = [];\n\n if ($field->object_type === Field::OBJECT_TASK && $field->crm_provider_id === 'type') {\n $activityTypes = $this->copperClient->activityTypes()->all();\n\n /**\n * We ignore \"system\" activity types, disabled activity types and the \"Note\" activity type.\n */\n $activityTypes = array_filter(\n $activityTypes['user'],\n fn (array $activityType) => ! $activityType['is_disabled'] && $activityType['id'] !== 0\n );\n\n // Import all activity values.\n $i = 0;\n foreach ($activityTypes as $activityType) {\n $values[] = [\n 'value' => $activityType['id'],\n 'label' => mb_strimwidth($activityType['name'], 0, Field::LABEL_MAX_LENGTH),\n 'sequence' => $i++,\n ];\n }\n } else {\n // We just check for the field in the custom definitions.\n $crmField = $this->copperClient->fields()->find($field->crm_provider_id);\n\n // Import all values.\n foreach ($crmField['options'] as $option) {\n $values[] = [\n 'value' => $option['id'],\n 'label' => mb_strimwidth($option['name'], 0, 191),\n 'sequence' => $option['rank'],\n ];\n }\n }\n\n // Take the existing set of field values.\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n // For all current values, upsert the field.\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n $key = array_search($value['value'], $fieldsToPurge, false);\n if ($key !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n\n return $fieldValues;\n }\n\n /**\n *\n * @return FieldValue[]\n */\n private function importFieldValuesForDealInsights(Field $field): array\n {\n $fieldValues = [];\n $pipelines = $this->copperClient->pipelines()->all();\n\n foreach ($pipelines as $pipeline) {\n foreach ($pipeline['stages'] as $i => $dealStage) {\n $fieldValues[] = $field->values()->updateOrCreate(\n ['value' => $dealStage['id']],\n [\n 'label' => $dealStage['name'],\n 'sequence' => $i,\n ]\n );\n }\n }\n\n return $fieldValues;\n }\n\n /**\n * @inheritdoc\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n $missingStage = null;\n\n foreach ($types as $type) {\n if ($type === Stage::TYPE_LEAD) {\n $statuses = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leadStatuses()->all()\n );\n\n if (count($statuses) > 0) {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => BusinessProcess::TYPE_LEAD,\n ], [\n 'team_id' => $this->team->id,\n 'name' => BusinessProcess::TYPE_LEAD,\n 'type' => BusinessProcess::TYPE_LEAD,\n 'is_selectable' => true,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => BusinessProcess::TYPE_LEAD,\n ], [\n 'team_id' => $this->team->id,\n 'name' => BusinessProcess::TYPE_LEAD,\n 'is_selectable' => true,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $leadStatuses = [];\n foreach ($statuses as $status) {\n // Upsert all statuses for the team.\n $status = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $status['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($status['name'], 0, 50),\n 'label' => mb_strimwidth($status['name'], 0, 191),\n 'type' => Stage::TYPE_LEAD,\n 'sequence' => $status['order'],\n 'is_selectable' => true,\n ]);\n\n if ($missingStageName && $missingStageName === $status['id']) {\n $missingStage = $status;\n }\n\n $leadStatuses[] = $status['id'];\n }\n\n $businessProcess->stages()->sync($leadStatuses);\n }\n } else {\n // We create a business process to contain the pipeline, and later store all stages against it.\n foreach ($this->copperClient->pipelines()->all() as $pipeline) {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $pipeline['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline['name'], 0, 150),\n 'type' => BusinessProcess::TYPE_OPPORTUNITY,\n 'is_selectable' => true,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $pipeline['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline['name'], 0, 150),\n 'is_selectable' => true,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $stages = [];\n\n foreach ($pipeline['stages'] as $i => $dealStage) {\n // Upsert all stages for the team.\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $dealStage['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($dealStage['name'], 0, 50),\n 'label' => mb_strimwidth($dealStage['name'], 0, 191),\n 'type' => Stage::TYPE_OPPORTUNITY,\n 'sequence' => $i,\n 'is_selectable' => true,\n 'probability' => $dealStage['win_probability'],\n ]);\n\n if ($missingStageName && $missingStageName === $dealStage['id']) {\n $missingStage = $stage;\n }\n\n $stages[] = $stage['id'];\n }\n\n $businessProcess->stages()->sync($stages);\n }\n }\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n\n $cpLeads = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->paginate([\n 'minimum_modified_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ])\n );\n\n foreach ($cpLeads as $cpLead) {\n // Only sync if previously imported.\n if ($this->hasLead($cpLead['id']) === false) {\n $this->importLead($cpLead);\n $syncCount++;\n }\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n $cpLead = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->find($crmId)\n );\n\n if (\\count($cpLead) === 0) {\n return null;\n }\n\n return $this->importLead($cpLead);\n }\n\n /**\n * @inheritdoc\n */\n private function importLead($crmData): ?Lead\n {\n $countryCode = null;\n if (! empty($crmData['address']) && isset($crmData['address']['country'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $mobilePhone = $parsedNumber = null;\n if (! empty($crmData['phone_numbers'])) {\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n if ($phoneNumber['category'] === 'mobile') {\n $mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);\n } else {\n $parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);\n }\n }\n }\n\n $name = $crmData['name'];\n\n if (empty($crmData['company_name'])) {\n $company = 'Unknown';\n } else {\n $company = mb_strimwidth($crmData['company_name'], 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['websites']) === false) {\n $domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $email = null;\n if (empty($crmData['email']) === false) {\n $email = mb_strimwidth($crmData['email']['email'], 0, 80);\n }\n\n $stage = $this->config\n ->stages()\n ->where('crm_provider_id', (string) $crmData['status_id'])\n ->where('type', Stage::TYPE_LEAD)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status_id']);\n }\n\n if (! $stage instanceof Stage) {\n return null;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($name, 0, 191),\n 'company' => $company,\n 'domain' => $domain,\n 'title' => $crmData['title'] ? mb_strimwidth($crmData['title'], 0, 128) : null,\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'mobile_phone' => $mobilePhone,\n 'stage_id' => $stage->id,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Lead::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'country_code' => $countryCode,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $cpAccounts = $this->copperClient->accounts()->paginate([\n 'minimum_modified_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ]);\n\n foreach ($cpAccounts as $cpAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($cpAccount['id'])) {\n $this->importAccount($cpAccount);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n $cpAccount = $this->copperClient->accounts()->find($crmId);\n\n if (empty($cpAccount)) {\n return null;\n }\n\n return $this->importAccount($cpAccount);\n }\n\n /**\n * @inheritdoc\n */\n private function importAccount($crmData): Account\n {\n $countryCode = null;\n if (empty($crmData['address']) === false && $crmData['address']['country']) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $name = $crmData['name'];\n\n $parsedNumber = null;\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n $parsedNumber = parsePhoneNumber($countryCode, $phoneNumber['number']);\n }\n\n $domain = null;\n if (empty($crmData['websites']) === false) {\n $domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Account::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'country_code' => $countryCode,\n 'domain' => $domain,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->copperClient,\n ]);\n $strategies = $strategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n\n try {\n foreach ($strategies as $syncStrategy) {\n foreach ($syncStrategy->fetchOpportunities($parameters) as $opportunityData) {\n $this->importOpportunity($opportunityData);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n $this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => $exception->getMessage(),\n ]);\n }\n\n return $syncCount;\n }\n\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->copperClient,\n ]);\n $strategy = $strategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n $parameters['crm_id'] = $crmId;\n\n $cpOpportunity = $strategy->fetchOpportunities($parameters);\n\n return $this->importOpportunity($cpOpportunity);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n $companyId = (string) $crmData['company_id'];\n\n if (empty($companyId)) {\n $this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => 'No company id',\n ]);\n\n return null;\n }\n\n $account = $this->config->accounts()->where('crm_provider_id', $companyId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($companyId);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', (string) $crmData['pipeline_id'])\n ->first();\n\n if ($businessProcess === null) {\n // It is possible for some deals to not be in a pipeline.\n $this->logger->warning(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => 'Missing pipeline',\n ]);\n\n return null;\n }\n\n $stage = $businessProcess\n ->stages()\n ->where('crm_provider_id', (string) $crmData['pipeline_stage_id'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n $this->logger->info('Stage not found, importing', [\n 'pipeline_id' => $crmData['pipeline_id'],\n 'stage_id' => $crmData['pipeline_stage_id'],\n ]);\n\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['pipeline_stage_id']);\n }\n\n $recordType = $businessProcess->recordTypes()->first();\n $closeDate = null;\n $isClosed = $crmData['status'] !== self::OPPORTUNITY_STATUS_OPEN;\n\n if ($crmData['close_date']) {\n $closeDate = Carbon::parse($crmData['close_date'])->format('Y-m-d');\n }\n\n $data = [\n 'team_id' => $this->team->getId(),\n 'account_id' => $account->id,\n 'user_id' => $profile->user_id ?? null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($crmData['name'], 0, 128),\n 'value' => $crmData['monetary_value'],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['monetary_unit']),\n 'close_date' => $closeDate,\n 'is_closed' => $isClosed,\n 'is_won' => $crmData['status'] === 'Won',\n 'stage_id' => $stage->id,\n 'record_type_id' => $recordType->id ?? null,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n /** @var Opportunity $opportunity */\n $opportunity = $this->config\n ->opportunities()\n ->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data)\n ;\n\n // import external fields into crm_field_data if present\n $dealInsightsFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData($crmData, $dealInsightsFields, $opportunity->id);\n\n return $opportunity;\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n * @param string[] $dealInsightsFields\n */\n public function importOpportunityCrmFieldData(\n array $opportunityData,\n array $dealInsightsFields,\n int $opportunityId\n ): void {\n foreach ($dealInsightsFields as $fieldName) {\n $field = $this->config->fields()->with('entities')\n ->where('crm_provider_id', $fieldName)\n ->where('object_type', Field::OBJECT_OPPORTUNITY)\n ->first();\n\n if (! $field instanceof Field) {\n $this->logger->warning('Field not found', [\n 'field' => $fieldName,\n 'opportunity_id' => $opportunityId,\n ]);\n\n continue;\n }\n\n $entity = $field->getEntities()->first();\n\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $fieldValue = $this->extractFieldValue($opportunityData, $fieldName);\n $normalizedValue = $this->normalizeValue($field->getType(), (string) $fieldValue, true);\n\n $field->data()\n ->updateOrCreate([\n 'crm_layout_entity_id' => $entity->id,\n 'crm_field_id' => $field->id,\n 'object_type' => 'opportunity',\n 'object_id' => $opportunityId,\n ], ['value' => $normalizedValue])\n ;\n }\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $cpContacts = $this->copperClient->contacts()->paginate([\n 'minimum_interaction_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ]);\n\n foreach ($cpContacts as $cpContact) {\n // Only sync if previously imported.\n if ($this->hasContact($cpContact['id'])) {\n $this->importContact($cpContact);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n throw $exception;\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n $cpContact = $this->copperClient->contacts()->find($crmId);\n\n if (empty($cpContact)) {\n return null;\n }\n\n return $this->importContact($cpContact);\n }\n\n /**\n * @inheritdoc\n */\n private function importContact($crmData): Contact\n {\n $account = null;\n if ($crmData['company_id']) {\n $account = $this->team\n ->crm\n ->accounts()\n ->where('crm_provider_id', (string) $crmData['company_id'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['company_id']);\n }\n }\n\n $countryCode = null;\n if (empty($crmData['address']) === false && $crmData['address']['country']) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $mobilePhone = $parsedNumber = null;\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n if ($phoneNumber['category'] === 'mobile') {\n $mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);\n } else {\n $parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);\n }\n }\n\n $email = null;\n if (empty($crmData['emails']) === false) {\n $email = mb_strimwidth($crmData['emails'][0]['email'], 0, 80);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => $crmData['name'],\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'mobile_phone' => $mobilePhone ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'title' => $crmData['title'],\n 'country_code' => $countryCode,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Contact::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function buildContactPhone(?string $countryCode, ?string $number): ?array\n {\n if ($number) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($number, 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n return $parsedNumber;\n }\n\n private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string\n {\n return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n $organization = $this->copperClient->organisation()->all();\n\n if ($this->config->crm_provider_id !== $organization['id']) {\n $this->config->update(['crm_provider_id' => $organization['id']]);\n }\n }\n\n private function syncCustomFields(): void\n {\n foreach ($this->getFieldTypes() as $fieldType) {\n $currentFields = $this->getFields($fieldType);\n\n foreach ($currentFields as $field) {\n /** @var Field $field */\n $field = $this->config->fields()->updateOrCreate([\n 'crm_provider_id' => $field['name'],\n 'object_type' => $fieldType,\n ], [\n 'label' => mb_strimwidth($field['label'], 0, Field::LABEL_MAX_LENGTH),\n 'type' => $field['type'],\n ]);\n\n if ($field->getType() === Field::TYPE_PICKLIST) {\n $this->importPicklistValues($field);\n }\n }\n }\n\n $this->config->save();\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n parent::OBJECT_LEAD,\n parent::OBJECT_ACCOUNT,\n parent::OBJECT_CONTACT,\n parent::OBJECT_OPPORTUNITY,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $profiles = $this->copperClient->users()->all();\n\n foreach ($profiles as $profile) {\n $user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);\n\n // Only import profiles for users we have locally.\n if ($user) {\n $profile = $user->crmProfile()->updateOrCreate([\n 'crm_configuration_id' => $this->config->id,\n 'crm_provider_id' => $profile['id'],\n ]);\n\n if ($userToSearch && $userToSearch->id === $user->id) {\n return $profile;\n }\n }\n }\n\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'task',\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields(ucfirst($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))\n );\n\n if (\\count($changedFields) > 0) {\n $fields = implode(',', $newFields);\n $this->logger->debug(\n ucfirst($fieldType)\n . ' fields changed from '\n . $this->profile->{$fieldType . '_fields'}\n . ' to: '\n . $fields\n );\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (\\Exception $exception) {\n $this->logger->error('No access to ' . $fieldType . ' object, skipping...');\n\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $scopeValues = array_map(fn ($scope) => is_string($scope) ? $scope : $scope->value, $scopes);\n $cacheKey = sprintf('copper-search-%d-%s-%s-%d-%d', $this->team->id, $name, implode('-', $scopeValues), $count, $offset);\n\n return Cache::remember($cacheKey, 300, function () use ($name, $scopes, $count, $offset) {\n // Try local search first\n $localResults = $this->searchLocally($name, $scopes, $count, $offset);\n\n // If no local results, fall back to remote API search\n if (empty($localResults)) {\n return $this->searchRemotely($name, $scopes, $count, $offset);\n }\n\n return $localResults;\n });\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $params = [\n 'company_ids' => [$account->crm_provider_id],\n 'status_ids' => [0], // The integer values are 0, 1, 2, 3, for \"Open\", \"Won\", \"Lost\", and \"Abandoned\".\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ];\n\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort_by'] = 'date_modified';\n $params['sort_direction'] = 'desc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort_by'] = 'date_created';\n $params['sort_direction'] = 'desc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort_by'] = 'date_created';\n $params['sort_direction'] = 'asc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort_by'] = 'date_modified';\n $params['sort_direction'] = 'desc';\n $params['status_ids'] = [0, 1, 2, 3];\n }\n\n $cpOpportunities = $this->copperClient->opportunities()->search($params);\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n foreach ($cpOpportunities as $cpOpportunity) {\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', (string) $cpOpportunity['pipeline_id'])\n ->first();\n\n if ($businessProcess === null) {\n // Import it.\n $businessProcess = $this->importStages(\n [Stage::TYPE_OPPORTUNITY],\n $cpOpportunity['pipeline_stage_id']\n );\n }\n\n $stage = $businessProcess\n ->stages()\n ->where('crm_provider_id', (string) $cpOpportunity['pipeline_stage_id'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $cpOpportunity['pipeline_stage_id']);\n }\n\n $recordType = $businessProcess->recordTypes()->first();\n\n $record = [\n 'crmId' => $cpOpportunity['id'],\n 'name' => $cpOpportunity['name'],\n 'value' => currency_format($cpOpportunity['monetary_value'], $cpOpportunity['monetary_unit']),\n 'won' => $cpOpportunity['status'] === 'Won',\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n\n if ($ownerId && isset($cpOpportunity['assignee_id']) && $cpOpportunity['assignee_id'] === $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $cpTasks = [];\n\n switch ($objectType) {\n case 'lead':\n $cpTasks = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->relatedTasks($objectId)\n );\n\n break;\n\n case 'account':\n $cpTasks = $this->copperClient->accounts()->relatedTasks($objectId);\n\n break;\n case 'contact':\n if ($opportunityId) {\n $cpTasks = $this->copperClient->opportunities()->relatedTasks($opportunityId);\n } elseif ($objectType === 'contact') {\n $cpTasks = $this->copperClient->contacts()->relatedTasks($objectId);\n }\n\n break;\n }\n\n foreach ($cpTasks as $cpTask) {\n // We only get the ID itself returned, so pull out the full object.\n try {\n $cpTask = $this->copperClient->tasks()->find($cpTask['id']);\n } catch (Exception $exception) {\n $this->logger->error('[Copper] Error fetching task', [\n 'resource_id' => $cpTask['id'],\n 'error' => $exception->getMessage(),\n ]);\n\n continue;\n }\n\n // Only allow open tasks.\n if ($cpTask['status'] === 'Open') {\n $data[] = [\n 'crmId' => $cpTask['id'],\n 'subject' => $cpTask['name'],\n 'due' => $cpTask['due_date']\n ? Carbon::createFromTimestamp($cpTask['due_date'])->format('Y-m-d\\TH:i:sO')\n : null,\n 'type' => null,\n ];\n }\n }\n\n return $data;\n }\n\n /**\n * Try to find email address in CRM service\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $cpObjectType = 'contact';\n\n $cpObjects = $this->copperClient->contacts()->search([\n 'emails' => $email,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (empty($cpObjects)) {\n $cpObjectType = 'lead';\n $cpObjects = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'emails' => $email,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (empty($cpObjects)) {\n return null;\n }\n\n // Search returns an array of results, but we only want the first\n $cpObject = reset($cpObjects);\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember === false) {\n $cpObjectType = 'contact';\n $cpObject = $this->copperClient->contacts()->search([\n 'phone_number' => $phone,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (\\count($cpObject) === 0) {\n $cpObjectType = 'lead';\n $cpObject = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'phone_number' => $phone,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (empty($cpObject)) {\n return null;\n }\n\n $cpObject = reset($cpObject);\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n return null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n $result = \\Cache::remember($this->team->id . $name, 60, function () use ($name, $userId) {\n $cpObjectType = 'contact';\n $cpObject = $this->copperClient->contacts()->search([\n 'name' => $name,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (\\count($cpObject) === 0) {\n $cpObjectType = 'lead';\n $cpObject = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'name' => $name,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (! empty($cpObject)) {\n $cpObject = reset($cpObject);\n }\n\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n private function convertCrmData(array $object, string $objectType, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n if ($objectType === 'lead') {\n $lead = $this->importLead($object);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } else {\n $contact = $this->importContact($object);\n $account = $contact->account;\n\n if ($contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $cpOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact->crm_provider_id,\n $userId,\n );\n\n if (! empty($cpOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($cpOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n } catch (\\Exception $e) {\n // Nothing to see here.\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n public function saveActivity(Activity $activity): Activity\n {\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n $activity = $this->buildCallPayload($activity);\n\n break;\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildTextMessagePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n private function convertActivityAssociations(Activity $activity): array\n {\n if ($activity->lead) {\n $type = 'lead';\n $id = $activity->lead->crm_provider_id;\n } elseif ($activity->contact) {\n $type = 'person';\n $id = $activity->contact->crm_provider_id;\n } elseif ($activity->opportunity) {\n $type = 'opportunity';\n $id = $activity->opportunity->crm_provider_id;\n } else {\n $type = 'company';\n $id = $activity->account->crm_provider_id;\n }\n\n return [\n 'type' => $type,\n 'id' => $id,\n ];\n }\n\n private function convertActivityType(PlaybookCategory $activityType): array\n {\n return [\n 'category' => 'user',\n 'id' => $this->getCrmType($activityType)->value,\n ];\n }\n\n /**\n * @throws CrmException\n */\n private function buildCallPayload(Activity $activity): Activity\n {\n try {\n if ($activity->crm_provider_id) {\n // The activity should be logged under the existing Task (not Activity).\n $newActivityType = $this->getCrmType($activity->category);\n if ($newActivityType === null) {\n $message = sprintf('[Copper] invalid CRM Custom Activity Type: %s', $activity->category);\n\n throw new CrmException($message, 400);\n }\n $this->copperClient->tasks()->update($activity->crm_provider_id, [\n 'status' => 'Completed',\n 'custom_activity_type_id' => $newActivityType->value,\n 'details' => $this->generateActivityDescription($activity),\n ]);\n } else {\n if ($this->getCrmType($activity->category) === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n if ($this->getCrmType($activity->category)->value === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n // Just create an activity.\n $cpActivity = $this->copperClient->activities()->create([\n 'user_id' => $this->profile->crm_provider_id,\n 'activity_date' => $activity->scheduled_start_time->timestamp,\n 'parent' => $this->convertActivityAssociations($activity),\n 'type' => $this->convertActivityType($activity->category),\n 'details' => $this->generateActivityDescription($activity),\n ]);\n\n $activity->crm_provider_id = $cpActivity['id'];\n $activity->save();\n }\n } catch (ClientException $exception) {\n //Log all errors to Sentry\n \\Sentry::captureException($exception);\n\n $response = $exception->getResponse();\n\n $responseBody = $response->getBody();\n $message = $responseBody;\n $errorCode = $response->getStatusCode();\n\n $jsonResponse = json_decode($responseBody, true);\n if (isset($jsonResponse[0]['message'])) {\n $message = $jsonResponse[0]['message'];\n }\n\n throw new CrmException($message, $errorCode);\n }\n\n return $activity;\n }\n\n private function buildTextMessagePayload(Activity $activity): Activity\n {\n if ($this->getCrmType($activity->category) === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n if ($this->getCrmType($activity->category)->value === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n $cpActivity = $this->copperClient->activities()->create([\n 'user_id' => $this->profile->crm_provider_id,\n 'activity_date' => $activity->created_at->timestamp,\n 'parent' => $this->convertActivityAssociations($activity),\n 'type' => $this->convertActivityType($activity->category),\n 'details' => $this->generateActivityDescription($activity),\n ]);\n\n $activity->crm_provider_id = $cpActivity['id'];\n $activity->save();\n\n return $activity;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = '';\n\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n $description = 'Jiminny Call Summary' . PHP_EOL . PHP_EOL;\n $description .= 'Call Duration: ' . $activity->duration_for_humans . PHP_EOL . PHP_EOL;\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= 'Dialed: ' . $activity->to->phone_number . PHP_EOL . PHP_EOL;\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= 'Notetaker removed from this meeting' . PHP_EOL . PHP_EOL;\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= 'Notetaker did not join due to recording consent not being provided by attendees' . PHP_EOL . PHP_EOL;\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= 'Review Activity:' . PHP_EOL . $playbackUrl . PHP_EOL . PHP_EOL;\n }\n\n if ($activity->getCrmType() === Activity::TYPE_CONFERENCE) {\n $description .= 'Attendees:'\n . PHP_EOL\n . (new FilterJoinedParticipants())->toString($activity);\n }\n\n if (\\count($activity->notes) > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Notes: ' . PHP_EOL;\n\n foreach ($activity->notes as $note) {\n $nTime = (int) ceil($note->time);\n $time = ($nTime > 3600) ? gmdate('H:i:s', $nTime) : gmdate('i:s', $nTime);\n $description .= $time . ' ' . $note->note . PHP_EOL;\n }\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Coaching Chat: ' . PHP_EOL;\n\n foreach ($messages->get() as $message) {\n $description .= $message->participant->name . ': ' . $message->message . PHP_EOL;\n }\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Customer Chat: ' . PHP_EOL;\n\n foreach ($messages->get() as $message) {\n $description .= $message->participant->name . ': ' . $message->message . PHP_EOL;\n }\n }\n\n if ($activity->summary) {\n $description .= PHP_EOL . PHP_EOL . 'Summary: ' . PHP_EOL . $activity->summary;\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $description = $activity->description;\n\n break;\n }\n\n return $description;\n }\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // This is the user provided activity subject field.\n if (empty($fields['type'])) {\n return null;\n }\n\n $reminder = null;\n if (empty($fields['reminder_date']) === false) {\n $formatReminder = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['reminder_date']);\n $reminder = $formatReminder->getTimestamp();\n }\n\n $due = null;\n if (empty($fields['due_date']) === false) {\n $formatDue = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['due_date']);\n $due = $formatDue->getTimestamp();\n }\n\n $data = [\n 'custom_activity_type_id' => $fields['type'],\n 'status' => 'Open',\n 'assignee_id' => $this->profile->crm_provider_id,\n 'due_date' => $due,\n 'details' => $fields['details'] ?? '',\n 'reminder_date' => $reminder,\n 'name' => $fields['name'] ?? 'Follow-up',\n 'related_resource' => $this->convertActivityAssociations($activity),\n 'custom_fields' => $this->fetchCustomFieldData($activity, Field::OBJECT_TASK),\n ];\n\n // We don't actually create a corresponding activity object on our side yet.\n return $this->copperClient->tasks()->create($data)['id'];\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws \\Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // Generate activity transcription.\n $transcriptionData = $this->generateTranscription($activity);\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $transcripts = mb_strimwidth($transcriptionData, 0, static::NOTE_BODY_MAX_LENGTH);\n\n $data = [\n 'user_id' => $this->profile->crm_provider_id,\n 'type' => [\n 'category' => 'user',\n 'id' => 0, // This creates a note.\n ],\n 'activity_date' => time(),\n 'details' => $transcripts,\n 'parent' => $this->convertActivityAssociations($activity),\n ];\n\n $cpActivity = $this->copperClient->activities()->create($data);\n\n // Store CRM Activity ID in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $cpActivity['id'];\n $transcription->save();\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n if ($crmObject instanceof Lead) {\n $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->update($crmObject->crm_provider_id, [\n 'status_id' => $stage->crm_provider_id,\n ])\n );\n } else {\n $this->copperClient->opportunities()->update($crmObject->crm_provider_id, [\n 'pipeline_stage_id' => $stage->crm_provider_id,\n ]);\n }\n }\n\n public function prepareValueForUpdate(array $params): array\n {\n return [$params['fieldName'] => $params['fieldValue']];\n }\n\n /*\n * @inheritdoc\n */\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $preparedData = $data;\n\n if ($objectType === Field::OBJECT_OPPORTUNITY) {\n $preparedData = $this->prepareOpportunityFieldsForUpdate($data);\n }\n\n try {\n $this->copperClient\n ->createResourceFromObjectType($objectType)\n ->update($objectId, $preparedData)\n ;\n } catch (Exception $e) {\n $this->logger->error(self::RESOURCE_UPDATE_FAILED_ERROR_MESSAGE, [\n 'resource_id' => $objectId,\n 'data' => $preparedData,\n 'error' => $e->getMessage(),\n ]);\n\n throw new CrmException(self::RESOURCE_UPDATE_FAILED_ERROR_MESSAGE, $e->getCode(), $e);\n }\n }\n\n /**\n * @param array<string,string> $fieldData\n *\n * @throws CrmException\n *\n * @return array<string,array<int,array<string,bool|float|int|string|null>>|bool|float|int|string|null>\n */\n private function prepareOpportunityFieldsForUpdate(array $fieldData): array\n {\n $preparedData = [];\n $customFields = [];\n\n foreach ($fieldData as $fieldName => $fieldValue) {\n $field = $this->config\n ->fields()\n ->where('crm_provider_id', $fieldName)\n ->first();\n\n if (! $field instanceof Field) {\n throw new CrmException('Field not found');\n }\n\n $convertedValue = $this->fieldValueConverter->convertToCrm($field->getType(), $fieldValue);\n\n if ($this->isStandardField($fieldName)) {\n $preparedData[$fieldName] = $convertedValue;\n\n continue;\n }\n\n $customFields[] = [\n 'custom_field_definition_id' => $fieldName,\n 'value' => $convertedValue,\n ];\n }\n\n if (! empty($customFields)) {\n $preparedData['custom_fields'] = $customFields;\n }\n\n return $preparedData;\n }\n\n /*\n * @inheritdoc\n */\n public function getRecord(string $objectType, string $objectId, array $fields = []): array\n {\n return $this->copperClient->createResourceFromObjectType($objectType)->find($objectId);\n }\n\n private function fetchCustomFieldData(Activity $activity, string $objectType): array\n {\n $payload = [];\n\n $fieldData = FieldData::where([\n 'object_id' => $activity->id,\n ])->whereHas('field', function ($query) use ($objectType) {\n $query->where('object_type', $objectType);\n })->get();\n\n foreach ($fieldData as $data) {\n // Add the field and value to the payload.\n $payload += [\n 'custom_field_definition_id' => $data->field->crm_provider_id,\n 'value' => $data->value,\n ];\n }\n\n return $payload;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $baseUrl = 'https://app.prosperworks.com/companies/' . $this->config->crm_provider_id . '/app#/';\n switch ($objectType) {\n case 'lead':\n $url = $baseUrl . 'leads/' . $providerId;\n\n break;\n\n case 'account':\n $url = $baseUrl . 'organization/' . $providerId;\n\n break;\n\n case 'contact':\n $url = $baseUrl . 'contact/' . $providerId;\n\n break;\n\n case 'opportunity':\n $url = $baseUrl . 'deal/' . $providerId;\n\n break;\n\n default:\n case 'task':\n case 'activity':\n // Sadly we can't deeplink to these in Copper UI.\n $url = null;\n }\n\n return $url;\n }\n\n /**\n * Generate transcription for the activity.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! ($this->config->store_transcript)) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n return $this->transcriptionService\n ->findTranscriptionByActivity($activity)\n ->map(static function (array $transcriptionSegment): string {\n return $transcriptionSegment['formattedStartsAt'] . ' | ' . $transcriptionSegment['transcript'];\n })\n ->implode(PHP_EOL);\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n *\n * @return int|string|bool|float|null\n */\n private function extractFieldValue(array $opportunityData, string $fieldName)\n {\n $fieldValue = $this->isStandardField($fieldName)\n ? $opportunityData[$fieldName]\n : $this->resolveCustomFieldFromOpportunityData($opportunityData, $fieldName);\n\n if (is_array($fieldValue)) {\n $fieldValue = implode(', ', $fieldValue);\n }\n\n return $fieldValue;\n }\n\n private function isStandardField(string $fieldName): bool\n {\n return array_key_exists($fieldName, self::STANDARD_OPPORTUNITY_FIELDS);\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n *\n * @return string|int|float|bool|null|array<string, mixed>\n */\n private function resolveCustomFieldFromOpportunityData(array $opportunityData, string $fieldName)\n {\n $fieldData = array_filter(\n $opportunityData['custom_fields'],\n static fn ($field) => (string) $field['custom_field_definition_id'] === $fieldName\n );\n\n return array_pop($fieldData)['value'] ?? '';\n }\n\n private function isSupportedObjectType(string $objectType): bool\n {\n return $objectType !== self::UNSUPPORTED_OBJECT_TYPE;\n }\n\n private function syncStandardFields(): void\n {\n foreach (self::STANDARD_OPPORTUNITY_FIELDS as $fieldId => $fieldData) {\n $this->config->fields()->updateOrCreate([\n 'crm_provider_id' => mb_strimwidth($fieldId, 0, 128),\n 'object_type' => Field::OBJECT_OPPORTUNITY,\n ], [\n 'label' => mb_strimwidth($fieldData['label'], 0, Field::LABEL_MAX_LENGTH),\n 'type' => $fieldData['type'],\n ]);\n }\n\n $this->importStages([Stage::TYPE_OPPORTUNITY]);\n }\n\n private function requestWithExceptionHandling(\\Closure $apiRequest): iterable\n {\n try {\n return $apiRequest();\n } catch (\\Exception $exception) {\n if ($exception->getCode() === 403) {\n // Object might not be supported\n return [];\n }\n\n \\Sentry::captureException($exception);\n\n return [];\n }\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n if ($this->copperClient === null) {\n return false;\n }\n\n $task = $this->copperClient->tasks()->find($crmProviderId);\n\n return ! empty($task);\n } catch (HttpNotFoundException) {\n // Task not found in CRM - this is expected and permanent\n $this->logger->info('[Copper] Task not found during verification', [\n 'task_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n } catch (RequestFailedException $e) {\n // Handle 404 responses from Copper API\n if ($e->getCode() === 404) {\n $this->logger->info('[Copper] Task not found during verification (404)', [\n 'task_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n\n // Re-throw other Copper exceptions for retry\n throw $e;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","depth":4,"on_screen":true,"value":"SELECT\n# DISTINCT\nopp.id as opp_id, opp.uuid, opp.name,\n# COUNT(dr.id) AS deal_risk_count,\n\n# dr.id,\n# cfd.value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\n# LEFT JOIN group_deal_risk_types gdrt ON gdrt.group_id = usr.group_id\n# LEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id AND dr.group_deal_risk_type_id = gdrt.id\n\nLEFT JOIN crm_field_data cfd ON (cfd.object_id = opp.id and cfd.crm_field_id = 66814)\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 1\nAND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\nGROUP BY opp.id, cfd.value\nORDER BY\n# cfd.value\n CAST(cfd.value AS UNSIGNED)\n# owner_name\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1\n# AND gdrt.is_enabled = 1)\nDESC\nLIMIT 25\n# OFFSET 0\n;\n\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\nselect * from crm_layout_entities where crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4584045;\nSELECT * FROM crm_field_data WHERE object_id = 4584045;\n\nSELECT * FROM opportunities where team_id = 1 and crm_provider_id = '0061K00000lfb9IQAQ'\n\nSELECT\n opp.id as opportunity_id,\n opp.name,\n COUNT(dr.id) as risk_count\nFROM opportunities opp\nLEFT JOIN deal_risks dr ON dr.opportunity_id = opp.id\nWHERE opp.id IN (\n 6069574,8900938,9507638,9524799,9660490,9662824,9705675,9749758,4158460,4391812,6450439,4448422,5118945,5590675,4584045,7228149,9002408,9165534,9446720,9641778,9665149,9703344,9709280,5747948,4158491,6182565,6263970,5798120,5111315,4536978,6062352,6548383,6072095,6548225,4480986,5011422,6548381,8760540,8917554,9509986,9514392,9569009,9569011,9578490,9713604,5784397,7276612,7288405,8994421,9118219,9608148,9818911,4510535,6479693,5958049,6271674,6550448,4158331,4158483,6126571,6171615,6540943,4897466,5190896,5796182,5932762,8572433,8723698,8892697,9711001,9789264,4549188,6100831,6170064,6260799,6263653,6449936,6530871,6538978,7777651,8059269,8319918,8787049,8901150,9263153,9453207,9514738,9696700,9791062,5752018,6421452,7439134,7878923,9354763,9369285,9514396,9582506,9889949,9890216,4094311,4158495,4158496,6098128,5585661,3872564,6442149,5891604,6164746,6199593,6583474,6519684,9018490,9809006,4496897,5041324,5829430,6198319,6253504,6555763,7242914,7931055,8024125,8797814,8058559,8673347,8892695,8994420,9616219,9714970,9722004,9809439,9818918,6523177,8134147,9002915,9711422,9892713,9901719,9954210,9978435,5800810,6243518,6416114,6222251,6411974,6512456,5791953,6545606,9914780,5805540,6238986,6463838,6547680,9767049,9809437,9810885,9890855,6673493,9902036,4335521,6379871,6503799,6546077,8018765,9907556,9958433,9905855,9916179,9946741,9957877,5563344,6271838,6450815,7641128,7762567,7780592,8684810,8685786,8685787,8685788\n)\nGROUP BY opp.id;\n\nSELECT COUNT(dr.id)\n FROM deal_risks dr\n JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n WHERE dr.opportunity_id = 5563344\n# AND gdrt.group_id = usr.group_id\n\n\n\nEXPLAIN SELECT\n opp.id as opp_id, opp.uuid, opp.name,\n\ncfd.value,\ncfv.sequence,\ncfv.value,\n# MAX(cfd.value) AS max_cfd_value,\nusr.name AS owner_name,\nopp.value, opp.currency_code, opp.close_date, opp.remotely_created_at, opp.is_closed, opp.is_won,\nusr.uuid as owner_uuid,\nusr.photo_path as owner_photo,\nusr.id AS owner_id,\njt.name as owner_job,\nopp.stage_id, opp.stage_updated_at,\nacc.name AS acc_name, opp.stage_updated_at, acc.crm_provider_id AS acc_provider_id, opp.crm_provider_id AS opp_provider_id,\nrt.business_process_id AS pipeline_id\nFROM opportunities opp\n\nLEFT JOIN record_types rt ON opp.record_type_id = rt.id\nLEFT JOIN users usr ON opp.user_id = usr.id\nLEFT JOIN accounts acc ON opp.account_id = acc.id\nLEFT JOIN job_titles jt ON usr.job_title_id = jt.id\n\nLEFT JOIN crm_field_data cfd ON cfd.id = (SELECT sub_cfd.id\n FROM crm_field_data sub_cfd\n WHERE sub_cfd.object_id = opp.id\n AND sub_cfd.crm_field_id = 66810\n ORDER BY sub_cfd.updated_at DESC\n LIMIT 1)\n\nLEFT JOIN crm_field_values cfv ON cfv.crm_field_id = 66810 AND cfv.value = cfd.value\n\nWHERE opp.user_id IS NOT NULL\nAND opp.deleted_at IS NULL\nAND opp.is_closed = 0\n# AND opp.is_closed = 1\n# AND opp.is_won = 0\nAND opp.close_date >= '2024-01-01 00:00:00'\nAND opp.close_date <= '2024-12-31 23:59:59'\nAND usr.team_id = 1\n\n# and opp.id = 4823179\n\n# GROUP BY opp.id\nORDER BY\n cfv.sequence DESC,\n# opp.name\n# owner_name\n cfd.value\n# CAST(cfd.value AS UNSIGNED)\n# CAST(MAX(cfd.value) AS UNSIGNED)\n# (SELECT COUNT(dr.id)\n# FROM deal_risks dr\n# JOIN group_deal_risk_types gdrt ON dr.group_deal_risk_type_id = gdrt.id\n# WHERE dr.opportunity_id = opp.id\n# AND dr.is_active = 1 AND gdrt.is_enabled = 1)\nDESC\n# LIMIT 75, 25\n;\n\n\n\nSELECT * FROM crm_field_values WHERE crm_field_id = 66810;\n\nSELECT f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value, fd.updated_at, fd.id, fd.created_at\nFROM crm_fields f\nINNER JOIN crm_field_data fd ON fd.crm_field_id = f.id\n WHERE (f.crm_configuration_id = 1)\n AND (f.object_type = 'opportunity')\n# AND (fd.object_id IN (4158331,4158483,4158495,4158496,6069574,6263970,6171615,6540943,6545606,5829430,6198319,6263653,6548381,7242914,8797814,7228149,7439134,7878923,8134147,9002915,9118219,9165534,9354763,9369285,9446720))\n AND (fd.object_id IN (4158460))\n AND (f.crm_provider_id IN ('ForecastCategoryName'))\n ORDER BY fd.object_id ASC, fd.updated_at DESC;\n\nselect * from crm_layouts where crm_configuration_id = 1;\nselect cf.* from crm_fields cf\njoin crm_layout_entities cle on cf.id = cle.crm_field_id\nwhere crm_layout_id = 1493;\n\nSELECT * FROM opportunities WHERE id = 4158460;\nSELECT * FROM crm_field_data WHERE object_id = 4158460;\n\nselect * from users where team_id = 1;\nSELECT * FROM users WHERE id = 7160;\nselect * from role_user where user_id = 3248;\n\nselect * from crm_field_values where crm_field_id = 66824;\n\nSELECT * FROM users WHERE id = 23470;\nselect * from crm_configurations;\n\n# ******************************************\nselect * from teams where id = 1038; # 23521, 966\nselect * from users where team_id = 1038;\nselect * from crm_configurations where id = 966;\nSELECT * FROM activities WHERE uuid_to_bin('e8dc7c34-31f6-4430-bd81-2d9d8f00dd07') = uuid; # 54965762\nSELECT * FROM activities WHERE uuid_to_bin('4b5727c0-69d1-428f-b8d9-b649055166e2') = uuid; # 54965764\nSELECT * FROM participants WHERE activity_id = 54965764;\n\nSELECT id, uuid, title, recording_state FROM activities WHERE uuid_to_bin('355f105d-5606-4379-b0c5-d91daf59f4ce') = uuid; # 54964075\nSELECT * FROM participants WHERE activity_id = 54964075;\nselect f.id, slug, title, tf.team_id from team_features tf JOIN features f on tf.feature_id = f.id\n where tf.team_id = 1038;\n\n\n# ****************************************** PD *************************\nselect * from teams where id = 1029;\nSELECT * FROM crm_configurations WHERE id = 957;\nSELECT * FROM activities WHERE uuid_to_bin('581a33cb-4343-44bd-ac0c-4a5cee71c5ec') = uuid; # 54963423\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('8b6bb2f7-e7a7-4aec-8806-fbfea7093ccd') = uuid; # 54963421\n\n# ****************************************** Close *************************\nselect * from teams where id = 1031;\nSELECT * FROM crm_configurations WHERE id = 959;\nSELECT * FROM activities WHERE uuid_to_bin('59c517e0-96c9-4dad-bfeb-b7bef72f8725') = uuid; # 54963517\n\n\nSELECT * FROM activities WHERE uuid_to_bin('07238011-25fa-418e-838b-fb21e82b9ea2') = uuid; # 54963433\n\nSELECT * FROM activities WHERE uuid_to_bin('d68311e3-ac34-49bd-bf04-88323a7e5352') = uuid; # 54966009\n\n# ****************************************** SF *************************\nSELECT * FROM activities WHERE uuid_to_bin('2bd4cfa3-4eb5-4c77-84a7-9ed46a21c988') = uuid;\n\nselect * from roles;\nselect * from permissions;\nselect * from permission_role where permission_id = 136;\n\nselect * from migrations order by id desc;\n\nselect * from teams where id IN (1, 1037);\nselect * from crm_layouts where crm_configuration_id = 1;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1493;\nSELECT * FROM crm_fields WHERE id IN (1652,1661,66799,66814,66821,66836,66843,66846,66864,84752,182306,323580,380378);\n\nselect * from features;\nselect * from team_features where feature_id = 33;\nselect * from opportunities;\n\nselect * from teams;\nSELECT\n CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,\n u.email,\n sa.*,\n t.owner_id FROM social_accounts sa\nJOIN users u on u.id = sa.sociable_id\nJOIN teams t on t.id = u.team_id\nWHERE u.team_id = 1052 and sa.provider = 'hubspot';\n\nSELECT * FROM accounts where id = 11512582;\nselect * from activities where account_id = 11512582;","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Project","depth":3,"on_screen":false,"role_description":"text"},{"role":"AXButton","text":"Project","depth":3,"bounds":{"left":0.28224733,"top":1.0,"width":0.024268618,"height":-0.04788506},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"New File or Directory…","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Expand Selected","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Collapse All","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Options","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
8957564869086018857
|
-7959665055215941403
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
11
72
1
4
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Copper;
use Carbon\Carbon;
use Exception;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Facades\Cache;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\CopperInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\FieldValue;
use Jiminny\Models\Crm\LayoutEntity;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\PlaybookCategory;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\UserRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\Copper\Api\Client;
use Jiminny\Services\Crm\Copper\Api\ClientFactory;
use Jiminny\Services\Crm\Copper\Exception\RequestFailedException;
use Jiminny\Services\Crm\Helpers\FilterJoinedParticipants;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Services\Crm\Copper\Traits\SearchesCrmEntities;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
class Service extends BaseService implements
CopperInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
use SearchesCrmEntities;
private const int NOTE_BODY_MAX_LENGTH = 3000000;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const array STANDARD_OPPORTUNITY_FIELDS = [
'monetary_value' => [
'label' => 'Value',
'available_on' => Field::OBJECT_OPPORTUNITY,
'type' => Field::TYPE_CURRENCY,
],
'pipeline_stage_id' => [
'label' => 'Stage',
'type' => Field::TYPE_PICKLIST,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
'close_date' => [
'label' => 'Close date',
'type' => Field::TYPE_DATE,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
'win_probability' => [
'label' => 'Win probability',
'type' => Field::TYPE_NUMBER,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
];
private const string UNSUPPORTED_OBJECT_TYPE = 'unsupported';
private const string OPPORTUNITY_STATUS_OPEN = 'Open';
private const string OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE = 'Opportunity import failed';
private const string RESOURCE_UPDATE_FAILED_ERROR_MESSAGE = 'Failed to update resource';
private FieldValueConverter $fieldValueConverter;
private ClientFactory $clientFactory;
private ?Client $copperClient = null;
public function __construct(
ClientFactory $clientFactory,
FieldValueConverter $fieldValueConverter,
private readonly UserRepository $userRepository,
private readonly ProspectPhotoPathService $prospectPhotoPathService,
private readonly CrmEntityRepository $crmEntityRepository
) {
parent::__construct();
$this->clientFactory = $clientFactory;
$this->fieldValueConverter = $fieldValueConverter;
}
public function getDisplayName(): string
{
return 'Copper';
}
/**
* Get the CRM entity repository (used by SearchesCrmEntities trait)
*/
protected function getCrmEntityRepository(): CrmEntityRepository
{
return $this->crmEntityRepository;
}
public function getMinimumApiVersion(): string
{
return Client::MIN_API_VERSION;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_COPPER);
}
public function setUser(User $user): void
{
$this->configureSentryScope($user);
$this->team = $user->getTeam();
$this->teamService->setTeam($user->getTeam());
$this->setConfiguration($user->getTeam()->getCrmConfiguration());
// Reset state.
$this->profile = $user->getProfile();
if (! $this->profile instanceof Profile) {
// Try to fetch their profile, maybe it was not yet imported?
$this->profile = $this->getProfile($user);
}
}
public function setConfiguration(Configuration $configuration): void
{
$this->config = $configuration;
$this->copperClient = $this->clientFactory->create($configuration);
if ($this->team === null) {
$this->team = $configuration->getTeam();
}
}
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return $this->fieldValueConverter->convertFromCrm($fieldType, $fieldValue);
}
private function mapObjectType(string $objectType): string
{
$objectType = strtolower($objectType);
switch ($objectType) {
case Field::OBJECT_TASK:
case Field::OBJECT_OPPORTUNITY:
case Field::OBJECT_LEAD:
$mappedType = $objectType;
break;
case Field::OBJECT_ACCOUNT:
$mappedType = 'company';
break;
case Field::OBJECT_CONTACT:
$mappedType = 'person';
break;
default:
$mappedType = self::UNSUPPORTED_OBJECT_TYPE;
break;
}
return $mappedType;
}
/**
* @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact
*/
protected function getFields(string $crmObject): array
{
$mappedObjectType = $this->mapObjectType($crmObject);
if (! $this->isSupportedObjectType($mappedObjectType)) {
return [];
}
$customFields = $this->copperClient->fields()->all();
$filteredFields = array_filter(
$customFields,
static fn ($field) => in_array($mappedObjectType, $field['available_on'], true)
);
return array_map(
fn (array $property) => [
'name' => $property['id'],
'label' => $property['name'],
'type' => $this->convertFieldType($property['data_type']),
],
$filteredFields
);
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {
$defaultFields = FieldDefinitions::defaultTaskFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldFilters = FieldDefinitions::taskFollowupFieldsFilter();
foreach ($fieldFilters as $data) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
public function syncFields(): void
{
$this->syncStandardFields();
$this->syncCustomFields();
}
public function syncField(Field $field): void
{
if ($field->getCrmProviderId() === 'type') {
/**
* This field is a special case, it is not a custom field and is not returned by the Copper API.
*
* The field is created manually during layout setup.
*
* @see getDefaultFields()
*
* There is a separate endpoint to get the activity types.
* @see importPicklistValues()
*/
return;
}
if ($field->getCrmProviderId() === 'pipeline_stage_id') {
// Not a custom type
return;
}
$crmField = $this->copperClient->fields()->find($field->getCrmProviderId());
$field->label = $crmField['name'];
$field->type = $this->convertFieldType($crmField['data_type']);
$field->save();
}
/**
* @param string $fieldType How the data should be input
*/
private function convertFieldType(string $fieldType): string
{
$fieldType = strtolower($fieldType);
switch ($fieldType) {
case 'dropdown':
$convertedType = Field::TYPE_PICKLIST;
break;
case 'string':
$convertedType = Field::TYPE_TEXT;
break;
case 'float':
case 'percentage':
$convertedType = Field::TYPE_NUMBER;
break;
case 'text':
$convertedType = Field::TYPE_TEXTAREA;
break;
case 'checkbox':
$convertedType = Field::TYPE_BOOLEAN;
break;
case Field::TYPE_DATE:
case Field::TYPE_CURRENCY:
case Field::TYPE_URL:
$convertedType = $fieldType;
break;
default:
$convertedType = Field::TYPE_UNSUPPORTED;
break;
}
return $convertedType;
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$fieldValues = [];
if ($field->object_type === 'opportunity' && $field->crm_provider_id === 'pipeline_stage_id') {
return $this->importFieldValuesForDealInsights($field);
}
$values = [];
if ($field->object_type === Field::OBJECT_TASK && $field->crm_provider_id === 'type') {
$activityTypes = $this->copperClient->activityTypes()->all();
/**
* We ignore "system" activity types, disabled activity types and the "Note" activity type.
*/
$activityTypes = array_filter(
$activityTypes['user'],
fn (array $activityType) => ! $activityType['is_disabled'] && $activityType['id'] !== 0
);
// Import all activity values.
$i = 0;
foreach ($activityTypes as $activityType) {
$values[] = [
'value' => $activityType['id'],
'label' => mb_strimwidth($activityType['name'], 0, Field::LABEL_MAX_LENGTH),
'sequence' => $i++,
];
}
} else {
// We just check for the field in the custom definitions.
$crmField = $this->copperClient->fields()->find($field->crm_provider_id);
// Import all values.
foreach ($crmField['options'] as $option) {
$values[] = [
'value' => $option['id'],
'label' => mb_strimwidth($option['name'], 0, 191),
'sequence' => $option['rank'],
];
}
}
// Take the existing set of field values.
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
// For all current values, upsert the field.
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
$key = array_search($value['value'], $fieldsToPurge, false);
if ($key !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
return $fieldValues;
}
/**
*
* @return FieldValue[]
*/
private function importFieldValuesForDealInsights(Field $field): array
{
$fieldValues = [];
$pipelines = $this->copperClient->pipelines()->all();
foreach ($pipelines as $pipeline) {
foreach ($pipeline['stages'] as $i => $dealStage) {
$fieldValues[] = $field->values()->updateOrCreate(
['value' => $dealStage['id']],
[
'label' => $dealStage['name'],
'sequence' => $i,
]
);
}
}
return $fieldValues;
}
/**
* @inheritdoc
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
$missingStage = null;
foreach ($types as $type) {
if ($type === Stage::TYPE_LEAD) {
$statuses = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leadStatuses()->all()
);
if (count($statuses) > 0) {
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => BusinessProcess::TYPE_LEAD,
], [
'team_id' => $this->team->id,
'name' => BusinessProcess::TYPE_LEAD,
'type' => BusinessProcess::TYPE_LEAD,
'is_selectable' => true,
]);
// A record type is really a clone of the business process, used to store which record uses which pipeline.
$this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => BusinessProcess::TYPE_LEAD,
], [
'team_id' => $this->team->id,
'name' => BusinessProcess::TYPE_LEAD,
'is_selectable' => true,
'business_process_id' => $businessProcess->id ?? null,
]);
$leadStatuses = [];
foreach ($statuses as $status) {
// Upsert all statuses for the team.
$status = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $status['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($status['name'], 0, 50),
'label' => mb_strimwidth($status['name'], 0, 191),
'type' => Stage::TYPE_LEAD,
'sequence' => $status['order'],
'is_selectable' => true,
]);
if ($missingStageName && $missingStageName === $status['id']) {
$missingStage = $status;
}
$leadStatuses[] = $status['id'];
}
$businessProcess->stages()->sync($leadStatuses);
}
} else {
// We create a business process to contain the pipeline, and later store all stages against it.
foreach ($this->copperClient->pipelines()->all() as $pipeline) {
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => $pipeline['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($pipeline['name'], 0, 150),
'type' => BusinessProcess::TYPE_OPPORTUNITY,
'is_selectable' => true,
]);
// A record type is really a clone of the business process, used to store which record uses which pipeline.
$this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => $pipeline['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($pipeline['name'], 0, 150),
'is_selectable' => true,
'business_process_id' => $businessProcess->id ?? null,
]);
$stages = [];
foreach ($pipeline['stages'] as $i => $dealStage) {
// Upsert all stages for the team.
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $dealStage['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($dealStage['name'], 0, 50),
'label' => mb_strimwidth($dealStage['name'], 0, 191),
'type' => Stage::TYPE_OPPORTUNITY,
'sequence' => $i,
'is_selectable' => true,
'probability' => $dealStage['win_probability'],
]);
if ($missingStageName && $missingStageName === $dealStage['id']) {
$missingStage = $stage;
}
$stages[] = $stage['id'];
}
$businessProcess->stages()->sync($stages);
}
}
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$cpLeads = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->paginate([
'minimum_modified_date' => $since->timestamp,
'sort_by' => 'date_modified',
])
);
foreach ($cpLeads as $cpLead) {
// Only sync if previously imported.
if ($this->hasLead($cpLead['id']) === false) {
$this->importLead($cpLead);
$syncCount++;
}
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
$cpLead = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->find($crmId)
);
if (\count($cpLead) === 0) {
return null;
}
return $this->importLead($cpLead);
}
/**
* @inheritdoc
*/
private function importLead($crmData): ?Lead
{
$countryCode = null;
if (! empty($crmData['address']) && isset($crmData['address']['country'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$mobilePhone = $parsedNumber = null;
if (! empty($crmData['phone_numbers'])) {
foreach ($crmData['phone_numbers'] as $phoneNumber) {
if ($phoneNumber['category'] === 'mobile') {
$mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);
} else {
$parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);
}
}
}
$name = $crmData['name'];
if (empty($crmData['company_name'])) {
$company = 'Unknown';
} else {
$company = mb_strimwidth($crmData['company_name'], 0, 191);
}
$domain = null;
if (empty($crmData['websites']) === false) {
$domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$email = null;
if (empty($crmData['email']) === false) {
$email = mb_strimwidth($crmData['email']['email'], 0, 80);
}
$stage = $this->config
->stages()
->where('crm_provider_id', (string) $crmData['status_id'])
->where('type', Stage::TYPE_LEAD)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status_id']);
}
if (! $stage instanceof Stage) {
return null;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($name, 0, 191),
'company' => $company,
'domain' => $domain,
'title' => $crmData['title'] ? mb_strimwidth($crmData['title'], 0, 128) : null,
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'mobile_phone' => $mobilePhone,
'stage_id' => $stage->id,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Lead::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'country_code' => $countryCode,
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$cpAccounts = $this->copperClient->accounts()->paginate([
'minimum_modified_date' => $since->timestamp,
'sort_by' => 'date_modified',
]);
foreach ($cpAccounts as $cpAccount) {
// Only sync if previously imported.
if ($this->hasAccount($cpAccount['id'])) {
$this->importAccount($cpAccount);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
$cpAccount = $this->copperClient->accounts()->find($crmId);
if (empty($cpAccount)) {
return null;
}
return $this->importAccount($cpAccount);
}
/**
* @inheritdoc
*/
private function importAccount($crmData): Account
{
$countryCode = null;
if (empty($crmData['address']) === false && $crmData['address']['country']) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$name = $crmData['name'];
$parsedNumber = null;
foreach ($crmData['phone_numbers'] as $phoneNumber) {
$parsedNumber = parsePhoneNumber($countryCode, $phoneNumber['number']);
}
$domain = null;
if (empty($crmData['websites']) === false) {
$domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Account::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'country_code' => $countryCode,
'domain' => $domain,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->copperClient,
]);
$strategies = $strategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
try {
foreach ($strategies as $syncStrategy) {
foreach ($syncStrategy->fetchOpportunities($parameters) as $opportunityData) {
$this->importOpportunity($opportunityData);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
$this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => $exception->getMessage(),
]);
}
return $syncCount;
}
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->copperClient,
]);
$strategy = $strategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
$parameters['crm_id'] = $crmId;
$cpOpportunity = $strategy->fetchOpportunities($parameters);
return $this->importOpportunity($cpOpportunity);
}
private function importOpportunity($crmData): ?Opportunity
{
$companyId = (string) $crmData['company_id'];
if (empty($companyId)) {
$this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => 'No company id',
]);
return null;
}
$account = $this->config->accounts()->where('crm_provider_id', $companyId)->first();
if ($account === null) {
$account = $this->syncAccount($companyId);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', (string) $crmData['pipeline_id'])
->first();
if ($businessProcess === null) {
// It is possible for some deals to not be in a pipeline.
$this->logger->warning(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => 'Missing pipeline',
]);
return null;
}
$stage = $businessProcess
->stages()
->where('crm_provider_id', (string) $crmData['pipeline_stage_id'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
$this->logger->info('Stage not found, importing', [
'pipeline_id' => $crmData['pipeline_id'],
'stage_id' => $crmData['pipeline_stage_id'],
]);
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['pipeline_stage_id']);
}
$recordType = $businessProcess->recordTypes()->first();
$closeDate = null;
$isClosed = $crmData['status'] !== self::OPPORTUNITY_STATUS_OPEN;
if ($crmData['close_date']) {
$closeDate = Carbon::parse($crmData['close_date'])->format('Y-m-d');
}
$data = [
'team_id' => $this->team->getId(),
'account_id' => $account->id,
'user_id' => $profile->user_id ?? null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($crmData['name'], 0, 128),
'value' => $crmData['monetary_value'],
'currency_code' => CurrencyFormatter::formatCode($crmData['monetary_unit']),
'close_date' => $closeDate,
'is_closed' => $isClosed,
'is_won' => $crmData['status'] === 'Won',
'stage_id' => $stage->id,
'record_type_id' => $recordType->id ?? null,
'remotely_created_at' => $crmData['date_created'],
];
/** @var Opportunity $opportunity */
$opportunity = $this->config
->opportunities()
->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data)
;
// import external fields into crm_field_data if present
$dealInsightsFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData($crmData, $dealInsightsFields, $opportunity->id);
return $opportunity;
}
/**
* @param array<string, mixed> $opportunityData
* @param string[] $dealInsightsFields
*/
public function importOpportunityCrmFieldData(
array $opportunityData,
array $dealInsightsFields,
int $opportunityId
): void {
foreach ($dealInsightsFields as $fieldName) {
$field = $this->config->fields()->with('entities')
->where('crm_provider_id', $fieldName)
->where('object_type', Field::OBJECT_OPPORTUNITY)
->first();
if (! $field instanceof Field) {
$this->logger->warning('Field not found', [
'field' => $fieldName,
'opportunity_id' => $opportunityId,
]);
continue;
}
$entity = $field->getEntities()->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$fieldValue = $this->extractFieldValue($opportunityData, $fieldName);
$normalizedValue = $this->normalizeValue($field->getType(), (string) $fieldValue, true);
$field->data()
->updateOrCreate([
'crm_layout_entity_id' => $entity->id,
'crm_field_id' => $field->id,
'object_type' => 'opportunity',
'object_id' => $opportunityId,
], ['value' => $normalizedValue])
;
}
}
/**
* @inheritdoc
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$cpContacts = $this->copperClient->contacts()->paginate([
'minimum_interaction_date' => $since->timestamp,
'sort_by' => 'date_modified',
]);
foreach ($cpContacts as $cpContact) {
// Only sync if previously imported.
if ($this->hasContact($cpContact['id'])) {
$this->importContact($cpContact);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
throw $exception;
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncContact(string $crmId): ?Contact
{
$cpContact = $this->copperClient->contacts()->find($crmId);
if (empty($cpContact)) {
return null;
}
return $this->importContact($cpContact);
}
/**
* @inheritdoc
*/
private function importContact($crmData): Contact
{
$account = null;
if ($crmData['company_id']) {
$account = $this->team
->crm
->accounts()
->where('crm_provider_id', (string) $crmData['company_id'])
->first();
if ($account === null) {
$account = $this->syncAccount($crmData['company_id']);
}
}
$countryCode = null;
if (empty($crmData['address']) === false && $crmData['address']['country']) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$mobilePhone = $parsedNumber = null;
foreach ($crmData['phone_numbers'] as $phoneNumber) {
if ($phoneNumber['category'] === 'mobile') {
$mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);
} else {
$parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);
}
}
$email = null;
if (empty($crmData['emails']) === false) {
$email = mb_strimwidth($crmData['emails'][0]['email'], 0, 80);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => $crmData['name'],
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'mobile_phone' => $mobilePhone ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'title' => $crmData['title'],
'country_code' => $countryCode,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Contact::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function buildContactPhone(?string $countryCode, ?string $number): ?array
{
if ($number) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($number, 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
return $parsedNumber;
}
private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string
{
return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;
}
/**
* @inheritdoc
*/
public function syncOrganization(): void
{
$organization = $this->copperClient->organisation()->all();
if ($this->config->crm_provider_id !== $organization['id']) {
$this->config->update(['crm_provider_id' => $organization['id']]);
}
}
private function syncCustomFields(): void
{
foreach ($this->getFieldTypes() as $fieldType) {
$currentFields = $this->getFields($fieldType);
foreach ($currentFields as $field) {
/** @var Field $field */
$field = $this->config->fields()->updateOrCreate([
'crm_provider_id' => $field['name'],
'object_type' => $fieldType,
], [
'label' => mb_strimwidth($field['label'], 0, Field::LABEL_MAX_LENGTH),
'type' => $field['type'],
]);
if ($field->getType() === Field::TYPE_PICKLIST) {
$this->importPicklistValues($field);
}
}
}
$this->config->save();
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
parent::OBJECT_LEAD,
parent::OBJECT_ACCOUNT,
parent::OBJECT_CONTACT,
parent::OBJECT_OPPORTUNITY,
];
}
/**
* @inheritdoc
*/
public function syncProfiles(?User $userToSearch = null): ?Profile
{
$profiles = $this->copperClient->users()->all();
foreach ($profiles as $profile) {
$user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);
// Only import profiles for users we have locally.
if ($user) {
$profile = $user->crmProfile()->updateOrCreate([
'crm_configuration_id' => $this->config->id,
'crm_provider_id' => $profile['id'],
]);
if ($userToSearch && $userToSearch->id === $user->id) {
return $profile;
}
}
}
return null;
}
/**
* @inheritdoc
*/
public function syncProfileFields(): void
{
$fieldTypes = [
'task',
'lead',
'account',
'contact',
'opportunity',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields(ucfirst($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))
);
if (\count($changedFields) > 0) {
$fields = implode(',', $newFields);
$this->logger->debug(
ucfirst($fieldType)
. ' fields changed from '
. $this->profile->{$fieldType . '_fields'}
. ' to: '
. $fields
);
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (\Exception $exception) {
$this->logger->error('No access to ' . $fieldType . ' object, skipping...');
continue;
}
}
$this->profile->save();
}
/**
* @inheritdoc
*/
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$scopeValues = array_map(fn ($scope) => is_string($scope) ? $scope : $scope->value, $scopes);
$cacheKey = sprintf('copper-search-%d-%s-%s-%d-%d', $this->team->id, $name, implode('-', $scopeValues), $count, $offset);
return Cache::remember($cacheKey, 300, function () use ($name, $scopes, $count, $offset) {
// Try local search first
$localResults = $this->searchLocally($name, $scopes, $count, $offset);
// If no local results, fall back to remote API search
if (empty($localResults)) {
return $this->searchRemotely($name, $scopes, $count, $offset);
}
return $localResults;
});
}
/**
* @inheritdoc
*/
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$params = [
'company_ids' => [$account->crm_provider_id],
'status_ids' => [0], // The integer values are 0, 1, 2, 3, for "Open", "Won", "Lost", and "Abandoned".
'sort_by' => 'date_modified',
'sort_direction' => 'desc',
];
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort_by'] = 'date_modified';
$params['sort_direction'] = 'desc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort_by'] = 'date_created';
$params['sort_direction'] = 'desc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort_by'] = 'date_created';
$params['sort_direction'] = 'asc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort_by'] = 'date_modified';
$params['sort_direction'] = 'desc';
$params['status_ids'] = [0, 1, 2, 3];
}
$cpOpportunities = $this->copperClient->opportunities()->search($params);
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
foreach ($cpOpportunities as $cpOpportunity) {
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', (string) $cpOpportunity['pipeline_id'])
->first();
if ($businessProcess === null) {
// Import it.
$businessProcess = $this->importStages(
[Stage::TYPE_OPPORTUNITY],
$cpOpportunity['pipeline_stage_id']
);
}
$stage = $businessProcess
->stages()
->where('crm_provider_id', (string) $cpOpportunity['pipeline_stage_id'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $cpOpportunity['pipeline_stage_id']);
}
$recordType = $businessProcess->recordTypes()->first();
$record = [
'crmId' => $cpOpportunity['id'],
'name' => $cpOpportunity['name'],
'value' => currency_format($cpOpportunity['monetary_value'], $cpOpportunity['monetary_unit']),
'won' => $cpOpportunity['status'] === 'Won',
'stage' => [
'id' => $stage->id_string,
'name' => $stage->name,
],
'recordType' => [
'id' => $recordType->id_string,
'name' => $recordType->name,
],
];
if ($ownerId && isset($cpOpportunity['assignee_id']) && $cpOpportunity['assignee_id'] === $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
/**
* @inheritdoc
*/
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = $cpTasks = [];
switch ($objectType) {
case 'lead':
$cpTasks = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->relatedTasks($objectId)
);
break;
case 'account':
$cpTasks = $this->copperClient->accounts()->relatedTasks($objectId);
break;
case 'contact':
if ($opportunityId) {
$cpTasks = $this->copperClient->opportunities()->relatedTasks($opportunityId);
} elseif ($objectType === 'contact') {
$cpTasks = $this->copperClient->contacts()->relatedTasks($objectId);
}
break;
}
foreach ($cpTasks as $cpTask) {
// We only get the ID itself returned, so pull out the full object.
try {
$cpTask = $this->copperClient->tasks()->find($cpTask['id']);
} catch (Exception $exception) {
$this->logger->error('[Copper] Error fetching task', [
'resource_id' => $cpTask['id'],
'error' => $exception->getMessage(),
]);
continue;
}
// Only allow open tasks.
if ($cpTask['status'] === 'Open') {
$data[] = [
'crmId' => $cpTask['id'],
'subject' => $cpTask['name'],
'due' => $cpTask['due_date']
? Carbon::createFromTimestamp($cpTask['due_date'])->format('Y-m-d\TH:i:sO')
: null,
'type' => null,
];
}
}
return $data;
}
/**
* Try to find email address in CRM service
*
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchExactlyByEmail(string $email, ?int $userId = null): ?array
{
$cpObjectType = 'contact';
$cpObjects = $this->copperClient->contacts()->search([
'emails' => $email,
'sort_by' => 'date_modified',
'sort_direction' => 'desc',
]);
if (empty($cpObjects)) {
$cpObjectType = 'lead';
$cpObjects = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->search([
'emails' => ...
|
45363
|
NULL
|
NULL
|
NULL
|
|
45364
|
1625
|
19
|
2026-05-14T14:32:53.884487+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769173884_m1.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit K vabl19HandleHubspotRateLimitTest100% C* :8• Thu 14 May 17:32:53QProjectv=custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php© FieldDefinitions.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php© FieldValueConverter.php• DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© Service.php© DecorateActivity.php> D CrmObjects© Salesforce/Service.php© LogActivityTrait.phpPipedrive/Service.phpClose/Service.phpCopper/Service.php X• DecorateActivity© PlainTextDecorateActivity.phpT ActivityPlaybookTrait.php© CrmHelperRepository.phpAccountController.php18© BaseDecorateActivity.php© PlainTextDecorateActivity.plT IntegrationAppTrait.php.env.stagingE.env© DetachActivityObject.phpRematchActivityOnCrmObjectDetach.php> Dummy© MatchActivityCrmData.phpv Helpers52Client.phpclass Service extends BaseService implements© HubspotPaginationService.php© HandleHubspotRateLimit.phpA11 A72 X1 X4 ^T ActivityPlaybookTrait.php© Arraylterator.phpT ConnectionStateTrait.php16621663* Othrows CrmException© CrmHelperRepository.php*/1 usage© FilterJoinedParticipants.php1664private function buildCallPayload(Activity $activity): Activity© OpportunitySyncableFieldsT 1665v D Hubspot1666• AccountSyncStrategy1667> OJ Actions |1668• ContactSyncStrategy1669> ODTO1670> D Fields1671try {if (Sadtivity->crm_provider_id) {// The activity should be logged under the existing Task (not Activity).SnewActivityType = Sthis->getCrmType(Sactivity->category);if ($newActivityType === null) {$message = sprintf( format: '[Copper] invalid CRM Custom Activity Type: %s', $activity->caz224> 0J Journal1672D Metadata1673throw new CrmException(Smessage,code: 400):v C OpportunitySyncStrategy1674› D Concerns1675© HubspotLastModifiedByF 1676© HubspotLastModifiedCre1677© HubspotLastModifiedCre1678$this->copperClient->tasks()->update($activity->crm_provider_id, ['status'= 'Completed','custom_activity_type_id' => $newActivityType->valve,'details' => $this->generateActivityDescription(Sactivity),© HubspotLastModifiedOpe 1679© HubspotLastModifiedSyn16801):j else {© HubspotSingleSyncStrate1681© HubspotSyncStrategyBa:1682it.(Sthis-getCrmType(Sactivitx-2categ0cX2mm.nulWnf$message = sprintf( format:'[Copper] Invalid CRM Activity Type: %s',Sactivity->category→© HubspotWebhookBatchS1683v [ Pagination1684throw new CrmException($message,code: 400);© HubspotPaginationServic1685=A Daninstinnfanfin nhn1686Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]DGo jiminny084143 ×4 л215|•m_layout_id =2162,1661,66799,66217218219id = 33;=220=221==222=223id THEN '(own=225=226= 227228-229=230hubspat":-231: 232233 V= 11512582;234-W Windsurf Teams1667:20UTF-8Co 4 spaces...
|
NULL
|
-7172210613695292373
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit K vabl19HandleHubspotRateLimitTest100% C* :8• Thu 14 May 17:32:53QProjectv=custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php© FieldDefinitions.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php© FieldValueConverter.php• DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© Service.php© DecorateActivity.php> D CrmObjects© Salesforce/Service.php© LogActivityTrait.phpPipedrive/Service.phpClose/Service.phpCopper/Service.php X• DecorateActivity© PlainTextDecorateActivity.phpT ActivityPlaybookTrait.php© CrmHelperRepository.phpAccountController.php18© BaseDecorateActivity.php© PlainTextDecorateActivity.plT IntegrationAppTrait.php.env.stagingE.env© DetachActivityObject.phpRematchActivityOnCrmObjectDetach.php> Dummy© MatchActivityCrmData.phpv Helpers52Client.phpclass Service extends BaseService implements© HubspotPaginationService.php© HandleHubspotRateLimit.phpA11 A72 X1 X4 ^T ActivityPlaybookTrait.php© Arraylterator.phpT ConnectionStateTrait.php16621663* Othrows CrmException© CrmHelperRepository.php*/1 usage© FilterJoinedParticipants.php1664private function buildCallPayload(Activity $activity): Activity© OpportunitySyncableFieldsT 1665v D Hubspot1666• AccountSyncStrategy1667> OJ Actions |1668• ContactSyncStrategy1669> ODTO1670> D Fields1671try {if (Sadtivity->crm_provider_id) {// The activity should be logged under the existing Task (not Activity).SnewActivityType = Sthis->getCrmType(Sactivity->category);if ($newActivityType === null) {$message = sprintf( format: '[Copper] invalid CRM Custom Activity Type: %s', $activity->caz224> 0J Journal1672D Metadata1673throw new CrmException(Smessage,code: 400):v C OpportunitySyncStrategy1674› D Concerns1675© HubspotLastModifiedByF 1676© HubspotLastModifiedCre1677© HubspotLastModifiedCre1678$this->copperClient->tasks()->update($activity->crm_provider_id, ['status'= 'Completed','custom_activity_type_id' => $newActivityType->valve,'details' => $this->generateActivityDescription(Sactivity),© HubspotLastModifiedOpe 1679© HubspotLastModifiedSyn16801):j else {© HubspotSingleSyncStrate1681© HubspotSyncStrategyBa:1682it.(Sthis-getCrmType(Sactivitx-2categ0cX2mm.nulWnf$message = sprintf( format:'[Copper] Invalid CRM Activity Type: %s',Sactivity->category→© HubspotWebhookBatchS1683v [ Pagination1684throw new CrmException($message,code: 400);© HubspotPaginationServic1685=A Daninstinnfanfin nhn1686Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]DGo jiminny084143 ×4 л215|•m_layout_id =2162,1661,66799,66217218219id = 33;=220=221==222=223id THEN '(own=225=226= 227228-229=230hubspat":-231: 232233 V= 11512582;234-W Windsurf Teams1667:20UTF-8Co 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45363
|
1626
|
11
|
2026-05-14T14:32:51.284451+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769171284_m2.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeave~ (Q SearchDate ModifiedYesterdav at 13.36Yesterday at 13:36Yesterday at 13.30Yesterday at 13:34Yesterday at 13:34resterday at 15.5sYesterdav at 13:3kYesterday at 13:32Yesterday at 13.31Yesterday at 13:31Yesterday at 13:30resterday at 15.30Yesterdav at 13:29Yesterday at 13:29Yesterday at 13:28Yesterday at 13:28Yesterday at 13:27resterday at 13-40Yesterdav at 13:26Yesterday at 13:25Yesterday at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13.22Yesterdav at 13:21Yesterday at 13:20Yesterday at 13:19Yesterday at 13.18Yecterdav at 12:19Yesterday at 13-1/Yesterdav at 13:16Yesterday at 13:16Yesterday at 13:15Yecterdav at 12:1/Yesterday at 13:14Yesterday at 13.13Yecterdav at 13:10Yesterday at 13:12Yesterday at 13:11Yesterday at 13:11Yesterday at 13:10Yesterday at 13.10Yecterdav at 12:091Yesterday at 13:09Yesterdav at 13:0823K:MPEG-4 movie9KBMPEG-4 movie13 KB16 Kb17 KEMPEG-4 movieMPEG-4 movie29 KB6 KBMPE0"4 movie12 K:9 KBMPEG-4 movie7 KBMP2G-4 movie37 KBMPEG-4 movie10 KBI KDMPEG"4 movie8 KE9KBMPEG-4 movie8 KB72 KBMPEG-4 movie14 KBMPEG-4 movie13 KB9KBMPEG-4 movie18 KEMPEG-4 movie12 KBMPEG-4 movie10 KB16 K:MPEG-4 movie6 KBMPEG-4 movie12 KBMPEG-4 movie23 KBMPEG-4 movie8 KBMPEG-4 movie6 KBMPEG-4 movie16 K:11 KBMPEG-4 movie20 KBMPEG-4 movie21 KPMPEG-4 movie10 KB MPEG-4 movie7 KBMPEG-4 movie5 KB1MPEG-4 movie11 KBMPEG-4 movie26 KB111 KB102 KRMPEG-4 movieMDEG-A movie88 KB59 KBMPEG-4 movie08 KBIMPEG-A movie97 KB MPEG-4 movie66 KB44 KB02 KpMPEG-4 movieMPEG-4 movie78 KB50 KBMPEG-4 movie58 KГMPEG-A movid27 KBMPEG-4 movie7 KB12K8MPEG-4 movieFavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zipD report(2) xmlAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence hettertouchtoolMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•AlfredwPmazanoko.imnaoc.YWIfана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jpс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВZIP archivel148 KBZIP archive122 KBXML document111 KBAlfred...ferences94 KBPDF Document92 KBPDr DocumentPDF Document91 KB91 KB30 KB29 KBXML documentPDF Document28 KB28 KR28 KB27 KB14 KB11 KB6 KB6KB5KR4 KB3 KBPDF DocumentPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..umentWindo...n imageword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytes1,9 MB1,8 MB17 MB1,7 MBFoldeColdorJPEG imageJPEG ImageJPEG imageJPEG imageColdo1 of 58 selected, 8.5 GB availab!i• Inu 14 May 1/.32:00Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
-4264175401579078456
|
NULL
|
click
|
ocr
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIAl Notes: OffLeave~ (Q SearchDate ModifiedYesterdav at 13.36Yesterday at 13:36Yesterday at 13.30Yesterday at 13:34Yesterday at 13:34resterday at 15.5sYesterdav at 13:3kYesterday at 13:32Yesterday at 13.31Yesterday at 13:31Yesterday at 13:30resterday at 15.30Yesterdav at 13:29Yesterday at 13:29Yesterday at 13:28Yesterday at 13:28Yesterday at 13:27resterday at 13-40Yesterdav at 13:26Yesterday at 13:25Yesterday at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13.22Yesterdav at 13:21Yesterday at 13:20Yesterday at 13:19Yesterday at 13.18Yecterdav at 12:19Yesterday at 13-1/Yesterdav at 13:16Yesterday at 13:16Yesterday at 13:15Yecterdav at 12:1/Yesterday at 13:14Yesterday at 13.13Yecterdav at 13:10Yesterday at 13:12Yesterday at 13:11Yesterday at 13:11Yesterday at 13:10Yesterday at 13.10Yecterdav at 12:091Yesterday at 13:09Yesterdav at 13:0823K:MPEG-4 movie9KBMPEG-4 movie13 KB16 Kb17 KEMPEG-4 movieMPEG-4 movie29 KB6 KBMPE0"4 movie12 K:9 KBMPEG-4 movie7 KBMP2G-4 movie37 KBMPEG-4 movie10 KBI KDMPEG"4 movie8 KE9KBMPEG-4 movie8 KB72 KBMPEG-4 movie14 KBMPEG-4 movie13 KB9KBMPEG-4 movie18 KEMPEG-4 movie12 KBMPEG-4 movie10 KB16 K:MPEG-4 movie6 KBMPEG-4 movie12 KBMPEG-4 movie23 KBMPEG-4 movie8 KBMPEG-4 movie6 KBMPEG-4 movie16 K:11 KBMPEG-4 movie20 KBMPEG-4 movie21 KPMPEG-4 movie10 KB MPEG-4 movie7 KBMPEG-4 movie5 KB1MPEG-4 movie11 KBMPEG-4 movie26 KB111 KB102 KRMPEG-4 movieMDEG-A movie88 KB59 KBMPEG-4 movie08 KBIMPEG-A movie97 KB MPEG-4 movie66 KB44 KB02 KpMPEG-4 movieMPEG-4 movie78 KB50 KBMPEG-4 movie58 KГMPEG-A movid27 KBMPEG-4 movie7 KB12K8MPEG-4 movieFavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zip→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zipD report(2) xmlAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence hettertouchtoolMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•AlfredwPmazanoko.imnaoc.YWIfана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jpс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВZIP archivel148 KBZIP archive122 KBXML document111 KBAlfred...ferences94 KBPDF Document92 KBPDr DocumentPDF Document91 KB91 KB30 KB29 KBXML documentPDF Document28 KB28 KR28 KB27 KB14 KB11 KB6 KB6KB5KR4 KB3 KBPDF DocumentPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..umentWindo...n imageword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytes1,9 MB1,8 MB17 MB1,7 MBFoldeColdorJPEG imageJPEG ImageJPEG imageJPEG imageColdo1 of 58 selected, 8.5 GB availab!i• Inu 14 May 1/.32:00Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45361
|
1626
|
10
|
2026-05-14T14:32:45.610188+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769165610_m2.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pm~ (Q SearchDate ModifiedYesterdav at 13.36Yesterday at 13:35Yesterday at 13.34Yesterday at 13:34Yesterday at 13:33resterday at 15.5sYesterdav at 13:37Yesterday at 13:32Yesterday ar 13.31Yesterday at 13:30Yesterday at 13:30resterday at 15.4gYesterdav at 13:29Yesterday at 13:28Yesterday at 13:28Yesterday at 13:27Yesterday at 13:27resterday at 13-40Yesterdav at 13:25Yesterday at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13:23Yesterday at 13.21Yesterdav at 13:21Yesterday at 13:20Yesterday at 13:20Yesterday at 13:19Yesterday at 13:19Yesterday at 13.18Vecterdav at 12:17Yesterday at 13:16Yesterdav at 13:16Yesterday at 13:15Yesterday at 13:14Yecterdav at 12:1/Yesterday at 13:13Yesterday at 13.13Yecterdav at 12:12Yesterday at 13:12Yesterday at 13:11Yesterday at 13:10Yesterday at 13:10Yesterday at 13.09Yecterdav at 12:091Yesterday at 13:08Yesterdav at 13:07MPEG-4 movie13 KBMPEG-4 movie16 KB1/ Kb29 KBMPEG-4 movieMPEG-4 movie6 KB12 KBMPE0"4 movie9 K:7 KBMPEG-4 movie8 KB37 KBMP2G-4 movie10 KBMPEG-4 movie7 KBMPEG"4 movie9K:8KBMPEG-4 movie72 KB14 K8|13 KRIMPEG-4 movieMPEG-4 movie9 KB18 KBMPEG-4 movie12 KEMPEG-4 movie10 KBMPEG-4 movie16 KB6 KB1MPEG-4 movie6 KBMPEG-4 movie12 KB23 KBMPEG-4 movie8 KEMPEG-4 movie6 KBMPEG-4 movie6 KBMPEG-4 movie11 K:MPEG-4 movie11 KBMPEG-4 movie34 KBMPEG-4 movie10 KPMPEG-4 movie7 KBMPEG-4 movie5 KBMPEG-4 movie11 KBIMPEG-4 movie26 KBMPEG-4 movie111 KB102 KBRR KRMPEG-4 movieMDEG-A movie59 KB98 KBMPEG-4 movie07 K:MPEG-A movie66 KB MPEG-4 movie44 KB93 KB79 KpMPEG-4 movieMPEG-4 movie58 KBMPEG-4 movie27 KP7 KBMPEG-4 movie12 KB32 K8MPEG-4 movieAl Notes: OffLeave• 0FavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВ148 KB122 KB111 KB94 KBZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.5 GB availab!i• Inu 14 Mау 1/•32.42Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
-4760999809465567111
|
NULL
|
click
|
ocr
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pm~ (Q SearchDate ModifiedYesterdav at 13.36Yesterday at 13:35Yesterday at 13.34Yesterday at 13:34Yesterday at 13:33resterday at 15.5sYesterdav at 13:37Yesterday at 13:32Yesterday ar 13.31Yesterday at 13:30Yesterday at 13:30resterday at 15.4gYesterdav at 13:29Yesterday at 13:28Yesterday at 13:28Yesterday at 13:27Yesterday at 13:27resterday at 13-40Yesterdav at 13:25Yesterday at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13:23Yesterday at 13.21Yesterdav at 13:21Yesterday at 13:20Yesterday at 13:20Yesterday at 13:19Yesterday at 13:19Yesterday at 13.18Vecterdav at 12:17Yesterday at 13:16Yesterdav at 13:16Yesterday at 13:15Yesterday at 13:14Yecterdav at 12:1/Yesterday at 13:13Yesterday at 13.13Yecterdav at 12:12Yesterday at 13:12Yesterday at 13:11Yesterday at 13:10Yesterday at 13:10Yesterday at 13.09Yecterdav at 12:091Yesterday at 13:08Yesterdav at 13:07MPEG-4 movie13 KBMPEG-4 movie16 KB1/ Kb29 KBMPEG-4 movieMPEG-4 movie6 KB12 KBMPE0"4 movie9 K:7 KBMPEG-4 movie8 KB37 KBMP2G-4 movie10 KBMPEG-4 movie7 KBMPEG"4 movie9K:8KBMPEG-4 movie72 KB14 K8|13 KRIMPEG-4 movieMPEG-4 movie9 KB18 KBMPEG-4 movie12 KEMPEG-4 movie10 KBMPEG-4 movie16 KB6 KB1MPEG-4 movie6 KBMPEG-4 movie12 KB23 KBMPEG-4 movie8 KEMPEG-4 movie6 KBMPEG-4 movie6 KBMPEG-4 movie11 K:MPEG-4 movie11 KBMPEG-4 movie34 KBMPEG-4 movie10 KPMPEG-4 movie7 KBMPEG-4 movie5 KBMPEG-4 movie11 KBIMPEG-4 movie26 KBMPEG-4 movie111 KB102 KBRR KRMPEG-4 movieMDEG-A movie59 KB98 KBMPEG-4 movie07 K:MPEG-A movie66 KB MPEG-4 movie44 KB93 KB79 KpMPEG-4 movieMPEG-4 movie58 KBMPEG-4 movie27 KP7 KBMPEG-4 movie12 KB32 K8MPEG-4 movieAl Notes: OffLeave• 0FavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВ148 KB122 KB111 KB94 KBZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.5 GB availab!i• Inu 14 Mау 1/•32.42Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
45359
|
NULL
|
NULL
|
NULL
|
|
45360
|
1625
|
17
|
2026-05-14T14:32:44.935525+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769164935_m1.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit k vabl19HandleHubspotRateLimitTest100% C8• Thu 14 May 17:32:44* :QProjectv=custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php© FieldDefinitions.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php© FieldValueConverter.php• DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© Service.php© DecorateActivity.php© StandardFieldMetadata.php© Salesforce/Service.php© LogActivityTrait.phpPipedrive/Service.phpClose/Service.phpCopper/Service.php Xv D Copper© PlainTextDecorateActivity.phpT ActivityPlaybookTrait.php© CrmHelperRepository.phpAccountController.php18> D Api› D ExceptionT IntegrationAppTrait.php.env.stagingE.env© DetachActivityObject.phpRematchActivityOnCrmObjectDetach.php> C OpportunitySyncStrategy© MatchActivityCrmData.php> D ProspectSearchStrategy52© Client.phpclass Service extends BaseService implements© HubspotPaginationService.php© HandleHubspotRateLimit.phpA11 A72 X1 X4 ^> CJ Traits© FieldDefinitions.php16621663* Othrows CrmException© FieldValueConverter.php© Service.php*/1 usage> D CrmObjects1664private function buildCallPayload(Activity $activity): Activityv DecorateActivity1665© BaseDecorateActivity.php1666try{© PlainTextDecorateActivity.pl1667> D Dummy1668v Helpers1669T ActivityPlaybookTrait.php1670© Arraylterator.php1671if (Sactivity->crm_provider_id) {// The activity should be logged under the existing Task (not Activity).SnewActivityType = Sthis->getCrmType(Sactivity->category);if ($newActivityType === null) {$message = sprintf( format: '[Copper] invalid CRM Custom Activity Type: %s', $activity->ca224• ConnectionStateTrait.php1672© CrmHelperRepository.php1673throw new CrmException(Smessage,code: 400);© FilterJoinedParticipants.php1674* OpportunitySyncableFieldsT1675v D Hubspot1676• AccountSyncStrategy1677> OJ Actions |1678$this->copperClient->tasks()->update($activity->crm_provider_id, ['status'= 'Completed','custom_activity_type_id' => $newActivityType->value,'details' => $this->generateActivityDescription($activity),• ContactSyncStrategy1679> ODTO16801):j else {› Fields1681> • Journal1682if (Sthis-~getCrmType(SactivitX-scategocx)minulln$message = sprintf( format:' [Copper] Invalid CRM Activity Type: %s', Sactivity->category→D Metadata1683v D OpportunitySyncStrategy1684throw new CrmException($message,code: 400);> D Concerns1685=A Unhonntl actlAndifiaNDur 1686Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]DGo jiminny084143 ×4 л215|•m_layout_id =2162,1661,66799,66217218219id = 33;=220=221=222=223id THEN •(own=225=226= 227228229=230hubspat":.231I232233V= 11512582;=234-W Windsurf Teams1664:31UTF-8P. 4 spaces...
|
NULL
|
5212527082351262392
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorRun PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit k vabl19HandleHubspotRateLimitTest100% C8• Thu 14 May 17:32:44* :QProjectv=custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php© FieldDefinitions.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php© FieldValueConverter.php• DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© Service.php© DecorateActivity.php© StandardFieldMetadata.php© Salesforce/Service.php© LogActivityTrait.phpPipedrive/Service.phpClose/Service.phpCopper/Service.php Xv D Copper© PlainTextDecorateActivity.phpT ActivityPlaybookTrait.php© CrmHelperRepository.phpAccountController.php18> D Api› D ExceptionT IntegrationAppTrait.php.env.stagingE.env© DetachActivityObject.phpRematchActivityOnCrmObjectDetach.php> C OpportunitySyncStrategy© MatchActivityCrmData.php> D ProspectSearchStrategy52© Client.phpclass Service extends BaseService implements© HubspotPaginationService.php© HandleHubspotRateLimit.phpA11 A72 X1 X4 ^> CJ Traits© FieldDefinitions.php16621663* Othrows CrmException© FieldValueConverter.php© Service.php*/1 usage> D CrmObjects1664private function buildCallPayload(Activity $activity): Activityv DecorateActivity1665© BaseDecorateActivity.php1666try{© PlainTextDecorateActivity.pl1667> D Dummy1668v Helpers1669T ActivityPlaybookTrait.php1670© Arraylterator.php1671if (Sactivity->crm_provider_id) {// The activity should be logged under the existing Task (not Activity).SnewActivityType = Sthis->getCrmType(Sactivity->category);if ($newActivityType === null) {$message = sprintf( format: '[Copper] invalid CRM Custom Activity Type: %s', $activity->ca224• ConnectionStateTrait.php1672© CrmHelperRepository.php1673throw new CrmException(Smessage,code: 400);© FilterJoinedParticipants.php1674* OpportunitySyncableFieldsT1675v D Hubspot1676• AccountSyncStrategy1677> OJ Actions |1678$this->copperClient->tasks()->update($activity->crm_provider_id, ['status'= 'Completed','custom_activity_type_id' => $newActivityType->value,'details' => $this->generateActivityDescription($activity),• ContactSyncStrategy1679> ODTO16801):j else {› Fields1681> • Journal1682if (Sthis-~getCrmType(SactivitX-scategocx)minulln$message = sprintf( format:' [Copper] Invalid CRM Activity Type: %s', Sactivity->category→D Metadata1683v D OpportunitySyncStrategy1684throw new CrmException($message,code: 400);> D Concerns1685=A Unhonntl actlAndifiaNDur 1686Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]DGo jiminny084143 ×4 л215|•m_layout_id =2162,1661,66799,66217218219id = 33;=220=221=222=223id THEN •(own=225=226= 227228229=230hubspat":.231I232233V= 11512582;=234-W Windsurf Teams1664:31UTF-8P. 4 spaces...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45359
|
1626
|
9
|
2026-05-14T14:32:42.185935+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769162185_m2.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pm~ (Q SearchDate ModifiedYesterdav at 13.36Yesterday at 13:35Yesterday at 13.34Yesterday at 13:34Yesterday at 13:33resterday at 15.5sYesterdav at 13:37Yesterday at 13:32Yesterday ar 13.31Yesterday at 13:30Yesterday at 13:30resterday at 15.4gYesterdav at 13:29Yesterday at 13:28Yesterday at 13:28Yesterday at 13:27Yesterday at 13:27resterday at 13-40Yesterdav at 13:25Yesterday at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13:23Yesterday at 13.21Yesterdav at 13:21Yesterday at 13:20Yesterday at 13:20Yesterday at 13:19Yesterday at 13:19Yesterday at 13.18Vecterdav at 12:17Yesterday at 13:16Yesterdav at 13:16Yesterday at 13:15Yesterday at 13:14Yecterdav at 12:1/Yesterday at 13:13Yesterday at 13.13Yecterdav at 12:12Yesterday at 13:12Yesterday at 13:11Yesterday at 13:10Yesterday at 13:10Yesterday at 13.09Yecterdav at 12:091Yesterday at 13:08Yesterdav at 13:07MPEG-4 movie13 KBMPEG-4 movie16 KB1/ Kb29 KBMPEG-4 movieMPEG-4 movie6 KB12 KBMPE0"4 movie9 K:7 KBMPEG-4 movie8 KB37 KBMP2G-4 movie10 KBMPEG-4 movie7 KBMPEG"4 movie9K:8KBMPEG-4 movie72 KB14 K8|13 KRIMPEG-4 movieMPEG-4 movie9 KB18 KBMPEG-4 movie12 KEMPEG-4 movie10 KBMPEG-4 movie16 KB6 KB1MPEG-4 movie6 KBMPEG-4 movie12 KB23 KBMPEG-4 movie8 KEMPEG-4 movie6 KBMPEG-4 movie6 KBMPEG-4 movie11 K:MPEG-4 movie11 KBMPEG-4 movie34 KBMPEG-4 movie10 KPMPEG-4 movie7 KBMPEG-4 movie5 KBMPEG-4 movie11 KBIMPEG-4 movie26 KBMPEG-4 movie111 KB102 KBRR KRMPEG-4 movieMDEG-A movie59 KB98 KBMPEG-4 movie07 K:MPEG-A movie66 KB MPEG-4 movie44 KB93 KB79 KpMPEG-4 movieMPEG-4 movie58 KBMPEG-4 movie27 KP7 KBMPEG-4 movie12 KB32 K8MPEG-4 movieAl Notes: OffLeave• 0FavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВ148 KB122 KB111 KB94 KBZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageJPEG imageJPEG imageColdo1 of 58 selected, 8.5 GB availab!i• Inu 14 Mау 1/•32.4]Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
9187213961329440757
|
NULL
|
click
|
ocr
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pm~ (Q SearchDate ModifiedYesterdav at 13.36Yesterday at 13:35Yesterday at 13.34Yesterday at 13:34Yesterday at 13:33resterday at 15.5sYesterdav at 13:37Yesterday at 13:32Yesterday ar 13.31Yesterday at 13:30Yesterday at 13:30resterday at 15.4gYesterdav at 13:29Yesterday at 13:28Yesterday at 13:28Yesterday at 13:27Yesterday at 13:27resterday at 13-40Yesterdav at 13:25Yesterday at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13:23Yesterday at 13.21Yesterdav at 13:21Yesterday at 13:20Yesterday at 13:20Yesterday at 13:19Yesterday at 13:19Yesterday at 13.18Vecterdav at 12:17Yesterday at 13:16Yesterdav at 13:16Yesterday at 13:15Yesterday at 13:14Yecterdav at 12:1/Yesterday at 13:13Yesterday at 13.13Yecterdav at 12:12Yesterday at 13:12Yesterday at 13:11Yesterday at 13:10Yesterday at 13:10Yesterday at 13.09Yecterdav at 12:091Yesterday at 13:08Yesterdav at 13:07MPEG-4 movie13 KBMPEG-4 movie16 KB1/ Kb29 KBMPEG-4 movieMPEG-4 movie6 KB12 KBMPE0"4 movie9 K:7 KBMPEG-4 movie8 KB37 KBMP2G-4 movie10 KBMPEG-4 movie7 KBMPEG"4 movie9K:8KBMPEG-4 movie72 KB14 K8|13 KRIMPEG-4 movieMPEG-4 movie9 KB18 KBMPEG-4 movie12 KEMPEG-4 movie10 KBMPEG-4 movie16 KB6 KB1MPEG-4 movie6 KBMPEG-4 movie12 KB23 KBMPEG-4 movie8 KEMPEG-4 movie6 KBMPEG-4 movie6 KBMPEG-4 movie11 K:MPEG-4 movie11 KBMPEG-4 movie34 KBMPEG-4 movie10 KPMPEG-4 movie7 KBMPEG-4 movie5 KBMPEG-4 movie11 KBIMPEG-4 movie26 KBMPEG-4 movie111 KB102 KBRR KRMPEG-4 movieMDEG-A movie59 KB98 KBMPEG-4 movie07 K:MPEG-A movie66 KB MPEG-4 movie44 KB93 KB79 KpMPEG-4 movieMPEG-4 movie58 KBMPEG-4 movie27 KP7 KBMPEG-4 movie12 KB32 K8MPEG-4 movieAl Notes: OffLeave• 0FavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВ148 KB122 KB111 KB94 KBZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageJPEG imageJPEG imageColdo1 of 58 selected, 8.5 GB availab!i• Inu 14 Mау 1/•32.4]Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45358
|
1625
|
16
|
2026-05-14T14:32:43.744332+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769163744_m1.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
11
72
1
4
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Copper;
use Carbon\Carbon;
use Exception;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Facades\Cache;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\CopperInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\FieldValue;
use Jiminny\Models\Crm\LayoutEntity;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\PlaybookCategory;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\UserRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\Copper\Api\Client;
use Jiminny\Services\Crm\Copper\Api\ClientFactory;
use Jiminny\Services\Crm\Copper\Exception\RequestFailedException;
use Jiminny\Services\Crm\Helpers\FilterJoinedParticipants;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Services\Crm\Copper\Traits\SearchesCrmEntities;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
class Service extends BaseService implements
CopperInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
use SearchesCrmEntities;
private const int NOTE_BODY_MAX_LENGTH = 3000000;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const array STANDARD_OPPORTUNITY_FIELDS = [
'monetary_value' => [
'label' => 'Value',
'available_on' => Field::OBJECT_OPPORTUNITY,
'type' => Field::TYPE_CURRENCY,
],
'pipeline_stage_id' => [
'label' => 'Stage',
'type' => Field::TYPE_PICKLIST,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
'close_date' => [
'label' => 'Close date',
'type' => Field::TYPE_DATE,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
'win_probability' => [
'label' => 'Win probability',
'type' => Field::TYPE_NUMBER,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
];
private const string UNSUPPORTED_OBJECT_TYPE = 'unsupported';
private const string OPPORTUNITY_STATUS_OPEN = 'Open';
private const string OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE = 'Opportunity import failed';
private const string RESOURCE_UPDATE_FAILED_ERROR_MESSAGE = 'Failed to update resource';
private FieldValueConverter $fieldValueConverter;
private ClientFactory $clientFactory;
private ?Client $copperClient = null;
public function __construct(
ClientFactory $clientFactory,
FieldValueConverter $fieldValueConverter,
private readonly UserRepository $userRepository,
private readonly ProspectPhotoPathService $prospectPhotoPathService,
private readonly CrmEntityRepository $crmEntityRepository
) {
parent::__construct();
$this->clientFactory = $clientFactory;
$this->fieldValueConverter = $fieldValueConverter;
}
public function getDisplayName(): string
{
return 'Copper';
}
/**
* Get the CRM entity repository (used by SearchesCrmEntities trait)
*/
protected function getCrmEntityRepository(): CrmEntityRepository
{
return $this->crmEntityRepository;
}
public function getMinimumApiVersion(): string
{
return Client::MIN_API_VERSION;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_COPPER);
}
public function setUser(User $user): void
{
$this->configureSentryScope($user);
$this->team = $user->getTeam();
$this->teamService->setTeam($user->getTeam());
$this->setConfiguration($user->getTeam()->getCrmConfiguration());
// Reset state.
$this->profile = $user->getProfile();
if (! $this->profile instanceof Profile) {
// Try to fetch their profile, maybe it was not yet imported?
$this->profile = $this->getProfile($user);
}
}
public function setConfiguration(Configuration $configuration): void
{
$this->config = $configuration;
$this->copperClient = $this->clientFactory->create($configuration);
if ($this->team === null) {
$this->team = $configuration->getTeam();
}
}
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return $this->fieldValueConverter->convertFromCrm($fieldType, $fieldValue);
}
private function mapObjectType(string $objectType): string
{
$objectType = strtolower($objectType);
switch ($objectType) {
case Field::OBJECT_TASK:
case Field::OBJECT_OPPORTUNITY:
case Field::OBJECT_LEAD:
$mappedType = $objectType;
break;
case Field::OBJECT_ACCOUNT:
$mappedType = 'company';
break;
case Field::OBJECT_CONTACT:
$mappedType = 'person';
break;
default:
$mappedType = self::UNSUPPORTED_OBJECT_TYPE;
break;
}
return $mappedType;
}
/**
* @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact
*/
protected function getFields(string $crmObject): array
{
$mappedObjectType = $this->mapObjectType($crmObject);
if (! $this->isSupportedObjectType($mappedObjectType)) {
return [];
}
$customFields = $this->copperClient->fields()->all();
$filteredFields = array_filter(
$customFields,
static fn ($field) => in_array($mappedObjectType, $field['available_on'], true)
);
return array_map(
fn (array $property) => [
'name' => $property['id'],
'label' => $property['name'],
'type' => $this->convertFieldType($property['data_type']),
],
$filteredFields
);
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {
$defaultFields = FieldDefinitions::defaultTaskFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldFilters = FieldDefinitions::taskFollowupFieldsFilter();
foreach ($fieldFilters as $data) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
public function syncFields(): void
{
$this->syncStandardFields();
$this->syncCustomFields();
}
public function syncField(Field $field): void
{
if ($field->getCrmProviderId() === 'type') {
/**
* This field is a special case, it is not a custom field and is not returned by the Copper API.
*
* The field is created manually during layout setup.
*
* @see getDefaultFields()
*
* There is a separate endpoint to get the activity types.
* @see importPicklistValues()
*/
return;
}
if ($field->getCrmProviderId() === 'pipeline_stage_id') {
// Not a custom type
return;
}
$crmField = $this->copperClient->fields()->find($field->getCrmProviderId());
$field->label = $crmField['name'];
$field->type = $this->convertFieldType($crmField['data_type']);
$field->save();
}
/**
* @param string $fieldType How the data should be input
*/
private function convertFieldType(string $fieldType): string
{
$fieldType = strtolower($fieldType);
switch ($fieldType) {
case 'dropdown':
$convertedType = Field::TYPE_PICKLIST;
break;
case 'string':
$convertedType = Field::TYPE_TEXT;
break;
case 'float':
case 'percentage':
$convertedType = Field::TYPE_NUMBER;
break;
case 'text':
$convertedType = Field::TYPE_TEXTAREA;
break;
case 'checkbox':
$convertedType = Field::TYPE_BOOLEAN;
break;
case Field::TYPE_DATE:
case Field::TYPE_CURRENCY:
case Field::TYPE_URL:
$convertedType = $fieldType;
break;
default:
$convertedType = Field::TYPE_UNSUPPORTED;
break;
}
return $convertedType;
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$fieldValues = [];
if ($field->object_type === 'opportunity' && $field->crm_provider_id === 'pipeline_stage_id') {
return $this->importFieldValuesForDealInsights($field);
}
$values = [];
if ($field->object_type === Field::OBJECT_TASK && $field->crm_provider_id === 'type') {
$activityTypes = $this->copperClient->activityTypes()->all();
/**
* We ignore "system" activity types, disabled activity types and the "Note" activity type.
*/
$activityTypes = array_filter(
$activityTypes['user'],
fn (array $activityType) => ! $activityType['is_disabled'] && $activityType['id'] !== 0
);
// Import all activity values.
$i = 0;
foreach ($activityTypes as $activityType) {
$values[] = [
'value' => $activityType['id'],
'label' => mb_strimwidth($activityType['name'], 0, Field::LABEL_MAX_LENGTH),
'sequence' => $i++,
];
}
} else {
// We just check for the field in the custom definitions.
$crmField = $this->copperClient->fields()->find($field->crm_provider_id);
// Import all values.
foreach ($crmField['options'] as $option) {
$values[] = [
'value' => $option['id'],
'label' => mb_strimwidth($option['name'], 0, 191),
'sequence' => $option['rank'],
];
}
}
// Take the existing set of field values.
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
// For all current values, upsert the field.
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
$key = array_search($value['value'], $fieldsToPurge, false);
if ($key !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
return $fieldValues;
}
/**
*
* @return FieldValue[]
*/
private function importFieldValuesForDealInsights(Field $field): array
{
$fieldValues = [];
$pipelines = $this->copperClient->pipelines()->all();
foreach ($pipelines as $pipeline) {
foreach ($pipeline['stages'] as $i => $dealStage) {
$fieldValues[] = $field->values()->updateOrCreate(
['value' => $dealStage['id']],
[
'label' => $dealStage['name'],
'sequence' => $i,
]
);
}
}
return $fieldValues;
}
/**
* @inheritdoc
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
$missingStage = null;
foreach ($types as $type) {
if ($type === Stage::TYPE_LEAD) {
$statuses = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leadStatuses()->all()
);
if (count($statuses) > 0) {
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => BusinessProcess::TYPE_LEAD,
], [
'team_id' => $this->team->id,
'name' => BusinessProcess::TYPE_LEAD,
'type' => BusinessProcess::TYPE_LEAD,
'is_selectable' => true,
]);
// A record type is really a clone of the business process, used to store which record uses which pipeline.
$this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => BusinessProcess::TYPE_LEAD,
], [
'team_id' => $this->team->id,
'name' => BusinessProcess::TYPE_LEAD,
'is_selectable' => true,
'business_process_id' => $businessProcess->id ?? null,
]);
$leadStatuses = [];
foreach ($statuses as $status) {
// Upsert all statuses for the team.
$status = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $status['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($status['name'], 0, 50),
'label' => mb_strimwidth($status['name'], 0, 191),
'type' => Stage::TYPE_LEAD,
'sequence' => $status['order'],
'is_selectable' => true,
]);
if ($missingStageName && $missingStageName === $status['id']) {
$missingStage = $status;
}
$leadStatuses[] = $status['id'];
}
$businessProcess->stages()->sync($leadStatuses);
}
} else {
// We create a business process to contain the pipeline, and later store all stages against it.
foreach ($this->copperClient->pipelines()->all() as $pipeline) {
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => $pipeline['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($pipeline['name'], 0, 150),
'type' => BusinessProcess::TYPE_OPPORTUNITY,
'is_selectable' => true,
]);
// A record type is really a clone of the business process, used to store which record uses which pipeline.
$this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => $pipeline['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($pipeline['name'], 0, 150),
'is_selectable' => true,
'business_process_id' => $businessProcess->id ?? null,
]);
$stages = [];
foreach ($pipeline['stages'] as $i => $dealStage) {
// Upsert all stages for the team.
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $dealStage['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($dealStage['name'], 0, 50),
'label' => mb_strimwidth($dealStage['name'], 0, 191),
'type' => Stage::TYPE_OPPORTUNITY,
'sequence' => $i,
'is_selectable' => true,
'probability' => $dealStage['win_probability'],
]);
if ($missingStageName && $missingStageName === $dealStage['id']) {
$missingStage = $stage;
}
$stages[] = $stage['id'];
}
$businessProcess->stages()->sync($stages);
}
}
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$cpLeads = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->paginate([
'minimum_modified_date' => $since->timestamp,
'sort_by' => 'date_modified',
])
);
foreach ($cpLeads as $cpLead) {
// Only sync if previously imported.
if ($this->hasLead($cpLead['id']) === false) {
$this->importLead($cpLead);
$syncCount++;
}
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
$cpLead = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->find($crmId)
);
if (\count($cpLead) === 0) {
return null;
}
return $this->importLead($cpLead);
}
/**
* @inheritdoc
*/
private function importLead($crmData): ?Lead
{
$countryCode = null;
if (! empty($crmData['address']) && isset($crmData['address']['country'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$mobilePhone = $parsedNumber = null;
if (! empty($crmData['phone_numbers'])) {
foreach ($crmData['phone_numbers'] as $phoneNumber) {
if ($phoneNumber['category'] === 'mobile') {
$mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);
} else {
$parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);
}
}
}
$name = $crmData['name'];
if (empty($crmData['company_name'])) {
$company = 'Unknown';
} else {
$company = mb_strimwidth($crmData['company_name'], 0, 191);
}
$domain = null;
if (empty($crmData['websites']) === false) {
$domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$email = null;
if (empty($crmData['email']) === false) {
$email = mb_strimwidth($crmData['email']['email'], 0, 80);
}
$stage = $this->config
->stages()
->where('crm_provider_id', (string) $crmData['status_id'])
->where('type', Stage::TYPE_LEAD)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status_id']);
}
if (! $stage instanceof Stage) {
return null;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($name, 0, 191),
'company' => $company,
'domain' => $domain,
'title' => $crmData['title'] ? mb_strimwidth($crmData['title'], 0, 128) : null,
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'mobile_phone' => $mobilePhone,
'stage_id' => $stage->id,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Lead::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'country_code' => $countryCode,
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$cpAccounts = $this->copperClient->accounts()->paginate([
'minimum_modified_date' => $since->timestamp,
'sort_by' => 'date_modified',
]);
foreach ($cpAccounts as $cpAccount) {
// Only sync if previously imported.
if ($this->hasAccount($cpAccount['id'])) {
$this->importAccount($cpAccount);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
$cpAccount = $this->copperClient->accounts()->find($crmId);
if (empty($cpAccount)) {
return null;
}
return $this->importAccount($cpAccount);
}
/**
* @inheritdoc
*/
private function importAccount($crmData): Account
{
$countryCode = null;
if (empty($crmData['address']) === false && $crmData['address']['country']) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$name = $crmData['name'];
$parsedNumber = null;
foreach ($crmData['phone_numbers'] as $phoneNumber) {
$parsedNumber = parsePhoneNumber($countryCode, $phoneNumber['number']);
}
$domain = null;
if (empty($crmData['websites']) === false) {
$domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Account::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'country_code' => $countryCode,
'domain' => $domain,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->copperClient,
]);
$strategies = $strategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
try {
foreach ($strategies as $syncStrategy) {
foreach ($syncStrategy->fetchOpportunities($parameters) as $opportunityData) {
$this->importOpportunity($opportunityData);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
$this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => $exception->getMessage(),
]);
}
return $syncCount;
}
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->copperClient,
]);
$strategy = $strategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
$parameters['crm_id'] = $crmId;
$cpOpportunity = $strategy->fetchOpportunities($parameters);
return $this->importOpportunity($cpOpportunity);
}
private function importOpportunity($crmData): ?Opportunity
{
$companyId = (string) $crmData['company_id'];
if (empty($companyId)) {
$this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => 'No company id',
]);
return null;
}
$account = $this->config->accounts()->where('crm_provider_id', $companyId)->first();
if ($account === null) {
$account = $this->syncAccount($companyId);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', (string) $crmData['pipeline_id'])
->first();
if ($businessProcess === null) {
// It is possible for some deals to not be in a pipeline.
$this->logger->warning(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => 'Missing pipeline',
]);
return null;
}
$stage = $businessProcess
->stages()
->where('crm_provider_id', (string) $crmData['pipeline_stage_id'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
$this->logger->info('Stage not found, importing', [
'pipeline_id' => $crmData['pipeline_id'],
'stage_id' => $crmData['pipeline_stage_id'],
]);
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['pipeline_stage_id']);
}
$recordType = $businessProcess->recordTypes()->first();
$closeDate = null;
$isClosed = $crmData['status'] !== self::OPPORTUNITY_STATUS_OPEN;
if ($crmData['close_date']) {
$closeDate = Carbon::parse($crmData['close_date'])->format('Y-m-d');
}
$data = [
'team_id' => $this->team->getId(),
'account_id' => $account->id,
'user_id' => $profile->user_id ?? null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($crmData['name'], 0, 128),
'value' => $crmData['monetary_value'],
'currency_code' => CurrencyFormatter::formatCode($crmData['monetary_unit']),
'close_date' => $closeDate,
'is_closed' => $isClosed,
'is_won' => $crmData['status'] === 'Won',
'stage_id' => $stage->id,
'record_type_id' => $recordType->id ?? null,
'remotely_created_at' => $crmData['date_created'],
];
/** @var Opportunity $opportunity */
$opportunity = $this->config
->opportunities()
->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data)
;
// import external fields into crm_field_data if present
$dealInsightsFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData($crmData, $dealInsightsFields, $opportunity->id);
return $opportunity;
}
/**
* @param array<string, mixed> $opportunityData
* @param string[] $dealInsightsFields
*/
public function importOpportunityCrmFieldData(
array $opportunityData,
array $dealInsightsFields,
int $opportunityId
): void {
foreach ($dealInsightsFields as $fieldName) {
$field = $this->config->fields()->with('entities')
->where('crm_provider_id', $fieldName)
->where('object_type', Field::OBJECT_OPPORTUNITY)
->first();
if (! $field instanceof Field) {
$this->logger->warning('Field not found', [
'field' => $fieldName,
'opportunity_id' => $opportunityId,
]);
continue;
}
$entity = $field->getEntities()->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$fieldValue = $this->extractFieldValue($opportunityData, $fieldName);
$normalizedValue = $this->normalizeValue($field->getType(), (string) $fieldValue, true);
$field->data()
->updateOrCreate([
'crm_layout_entity_id' => $entity->id,
'crm_field_id' => $field->id,
'object_type' => 'opportunity',
'object_id' => $opportunityId,
], ['value' => $normalizedValue])
;
}
}
/**
* @inheritdoc
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$cpContacts = $this->copperClient->contacts()->paginate([
'minimum_interaction_date' => $since->timestamp,
'sort_by' => 'date_modified',
]);
foreach ($cpContacts as $cpContact) {
// Only sync if previously imported.
if ($this->hasContact($cpContact['id'])) {
$this->importContact($cpContact);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
throw $exception;
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncContact(string $crmId): ?Contact
{
$cpContact = $this->copperClient->contacts()->find($crmId);
if (empty($cpContact)) {
return null;
}
return $this->importContact($cpContact);
}
/**
* @inheritdoc
*/
private function importContact($crmData): Contact
{
$account = null;
if ($crmData['company_id']) {
$account = $this->team
->crm
->accounts()
->where('crm_provider_id', (string) $crmData['company_id'])
->first();
if ($account === null) {
$account = $this->syncAccount($crmData['company_id']);
}
}
$countryCode = null;
if (empty($crmData['address']) === false && $crmData['address']['country']) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$mobilePhone = $parsedNumber = null;
foreach ($crmData['phone_numbers'] as $phoneNumber) {
if ($phoneNumber['category'] === 'mobile') {
$mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);
} else {
$parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);
}
}
$email = null;
if (empty($crmData['emails']) === false) {
$email = mb_strimwidth($crmData['emails'][0]['email'], 0, 80);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => $crmData['name'],
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'mobile_phone' => $mobilePhone ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'title' => $crmData['title'],
'country_code' => $countryCode,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Contact::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function buildContactPhone(?string $countryCode, ?string $number): ?array
{
if ($number) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($number, 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
return $parsedNumber;
}
private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string
{
return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;
}
/**
* @inheritdoc
*/
public function syncOrganization(): void
{
$organization = $this->copperClient->organisation()->all();
if ($this->config->crm_provider_id !== $organization['id']) {
$this->config->update(['crm_provider_id' => $organization['id']]);
}
}
private function syncCustomFields(): void
{
foreach ($this->getFieldTypes() as $fieldType) {
$currentFields = $this->getFields($fieldType);
foreach ($currentFields as $field) {
/** @var Field $field */
$field = $this->config->fields()->updateOrCreate([
'crm_provider_id' => $field['name'],
'object_type' => $fieldType,
], [
'label' => mb_strimwidth($field['label'], 0, Field::LABEL_MAX_LENGTH),
'type' => $field['type'],
]);
if ($field->getType() === Field::TYPE_PICKLIST) {
$this->importPicklistValues($field);
}
}
}
$this->config->save();
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
parent::OBJECT_LEAD,
parent::OBJECT_ACCOUNT,
parent::OBJECT_CONTACT,
parent::OBJECT_OPPORTUNITY,
];
}
/**
* @inheritdoc
*/
public function syncProfiles(?User $userToSearch = null): ?Profile
{
$profiles = $this->copperClient->users()->all();
foreach ($profiles as $profile) {
$user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);
// Only import profiles for users we have locally.
if ($user) {
$profile = $user->crmProfile()->updateOrCreate([
'crm_configuration_id' => $this->config->id,
'crm_provider_id' => $profile['id'],
]);
if ($userToSearch && $userToSearch->id === $user->id) {
return $profile;
}
}
}
return null;
}
/**
* @inheritdoc
*/
public function syncProfileFields(): void
{
$fieldTypes = [
'task',
'lead',
'account',
'contact',
'opportunity',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields(ucfirst($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))
);
if (\count($changedFields) > 0) {
$fields = implode(',', $newFields);
$this->logger->debug(
ucfirst($fieldType)
. ' fields changed from '
. $this->profile->{$fieldType . '_fields'}
. ' to: '
. $fields
);
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (\Exception $exception) {
$this->logger->error('No access to ' . $fieldType . ' object, skipping...');
continue;
}
}
$this->profile->save();
}
/**
* @inheritdoc
*/
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$scopeValues = array_map(fn ($scope) => is_string($scope) ? $scope : $scope->value, $scopes);
$cacheKey = sprintf('copper-search-%d-%s-%s-%d-%d', $this->team->id, $name, implode('-', $scopeValues), $count, $offset);
return Cache::remember($cacheKey, 300, function () use ($name, $scopes, $count, $offset) {
// Try local search first
$localResults = $this->searchLocally($name, $scopes, $count, $offset);
// If no local results, fall back to remote API search
if (empty($localResults)) {
return $this->searchRemotely($name, $scopes, $count, $offset);
}
return $localResults;
});
}
/**
* @inheritdoc
*/
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$params = [
'company_ids' => [$account->crm_provider_id],
'status_ids' => [0], // The integer values are 0, 1, 2, 3, for "Open", "Won", "Lost", and "Abandoned".
'sort_by' => 'date_modified',
'sort_direction' => 'desc',
];
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort_by'] = 'date_modified';
$params['sort_direction'] = 'desc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort_by'] = 'date_created';
$params['sort_direction'] = 'desc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort_by'] = 'date_created';
$params['sort_direction'] = 'asc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort_by'] = 'date_modified';
$params['sort_direction'] = 'desc';
$params['status_ids'] = [0, 1, 2, 3];
}
$cpOpportunities = $this->copperClient->opportunities()->search($params);
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
foreach ($cpOpportunities as $cpOpportunity) {
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', (string) $cpOpportunity['pipeline_id'])
->first();
if ($businessProcess === null) {
// Import it.
$businessProcess = $this->importStages(
[Stage::TYPE_OPPORTUNITY],
$cpOpportunity['pipeline_stage_id']
);
}
$stage = $businessProcess
->stages()
->where('crm_provider_id', (string) $cpOpportunity['pipeline_stage_id'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $cpOpportunity['pipeline_stage_id']);
}
$recordType = $businessProcess->recordTypes()->first();
$record = [
'crmId' => $cpOpportunity['id'],
'name' => $cpOpportunity['name'],
'value' => currency_format($cpOpportunity['monetary_value'], $cpOpportunity['monetary_unit']),
'won' => $cpOpportunity['status'] === 'Won',
'stage' => [
'id' => $stage->id_string,
'name' => $stage->name,
],
'recordType' => [
'id' => $recordType->id_string,
'name' => $recordType->name,
],
];
if ($ownerId && isset($cpOpportunity['assignee_id']) && $cpOpportunity['assignee_id'] === $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
/**
* @inheritdoc
*/
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = $cpTasks = [];
switch ($objectType) {
case 'lead':
$cpTasks = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->relatedTasks($objectId)
);
break;
case 'account':
$cpTasks = $this->copperClient->accounts()->relatedTasks($objectId);
break;
case 'contact':
if ($opportunityId) {
$cpTasks = $this->copperClient->opportunities()->relatedTasks($opportunityId);
} elseif ($objectType === 'contact') {
$cpTasks = $this->copperClient->contacts()->relatedTasks($objectId);
}
break;
}
foreach ($cpTasks as $cpTask) {
// We only get the ID itself returned, so pull out the full object.
try {
$cpTask = $this->copperClient->tasks()->find($cpTask['id']);
} catch (Exception $exception) {
$this->logger->error('[Copper] Error fetching task', [
'resource_id' => $cpTask['id'],
'error' => $exception->getMessage(),
]);
continue;
}
// Only allow open tasks.
if ($cpTask['status'] === 'Open') {
$data[] = [
'crmId' => $cpTask['id'],
'subject' => $cpTask['name'],
'due' => $cpTask['due_date']
? Carbon::createFromTimestamp($cpTask['due_date'])->format('Y-m-d\TH:i:sO')
: null,
'type' => null,
];
}
}
return $data;
}
/**
* Try to find email address in CRM service
*
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchExactlyByEmail(string $email, ?int $userId = null): ?array
{
$cpObjectType = 'contact';
$cpObjects = $this->copperClient->contacts()->search([
'emails' => $email,
'sort_by' => 'date_modified',
'sort_direction' => 'desc',
]);
if (empty($cpObjects)) {
$cpObjectType = 'lead';
$cpObjects = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->search([
'emails' => ...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.6326389,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.6645833,"top":0.027777778,"width":0.15902779,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.82361114,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.8472222,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.87083334,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.9291667,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.9527778,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.9763889,"top":0.027777778,"width":0.023611112,"height":0.035555556},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.088194445,"height":0.027777778},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.0,"top":0.0,"width":0.018055556,"height":0.026666667},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"11","depth":4,"bounds":{"left":0.7340278,"top":0.3122222,"width":0.01875,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"72","depth":4,"bounds":{"left":0.7569444,"top":0.3122222,"width":0.020833334,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"bounds":{"left":0.78194445,"top":0.3122222,"width":0.015277778,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"4","depth":4,"bounds":{"left":0.80138886,"top":0.3122222,"width":0.016666668,"height":0.02111111},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.8215278,"top":0.31,"width":0.015277778,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"bounds":{"left":0.8368056,"top":0.31,"width":0.014583333,"height":0.025555555},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Copper;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse GuzzleHttp\\Exception\\ClientException;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\CopperInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\FieldValue;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\PlaybookCategory;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\UserRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\Copper\\Api\\Client;\nuse Jiminny\\Services\\Crm\\Copper\\Api\\ClientFactory;\nuse Jiminny\\Services\\Crm\\Copper\\Exception\\RequestFailedException;\nuse Jiminny\\Services\\Crm\\Helpers\\FilterJoinedParticipants;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Services\\Crm\\Copper\\Traits\\SearchesCrmEntities;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\n\nclass Service extends BaseService implements\n CopperInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n use SearchesCrmEntities;\n private const int NOTE_BODY_MAX_LENGTH = 3000000;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const array STANDARD_OPPORTUNITY_FIELDS = [\n 'monetary_value' => [\n 'label' => 'Value',\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n 'type' => Field::TYPE_CURRENCY,\n ],\n 'pipeline_stage_id' => [\n 'label' => 'Stage',\n 'type' => Field::TYPE_PICKLIST,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n 'close_date' => [\n 'label' => 'Close date',\n 'type' => Field::TYPE_DATE,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n 'win_probability' => [\n 'label' => 'Win probability',\n 'type' => Field::TYPE_NUMBER,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n ];\n private const string UNSUPPORTED_OBJECT_TYPE = 'unsupported';\n private const string OPPORTUNITY_STATUS_OPEN = 'Open';\n private const string OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE = 'Opportunity import failed';\n private const string RESOURCE_UPDATE_FAILED_ERROR_MESSAGE = 'Failed to update resource';\n\n private FieldValueConverter $fieldValueConverter;\n private ClientFactory $clientFactory;\n private ?Client $copperClient = null;\n\n public function __construct(\n ClientFactory $clientFactory,\n FieldValueConverter $fieldValueConverter,\n private readonly UserRepository $userRepository,\n private readonly ProspectPhotoPathService $prospectPhotoPathService,\n private readonly CrmEntityRepository $crmEntityRepository\n ) {\n parent::__construct();\n\n $this->clientFactory = $clientFactory;\n $this->fieldValueConverter = $fieldValueConverter;\n }\n\n public function getDisplayName(): string\n {\n return 'Copper';\n }\n\n /**\n * Get the CRM entity repository (used by SearchesCrmEntities trait)\n */\n protected function getCrmEntityRepository(): CrmEntityRepository\n {\n return $this->crmEntityRepository;\n }\n\n public function getMinimumApiVersion(): string\n {\n return Client::MIN_API_VERSION;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_COPPER);\n }\n\n public function setUser(User $user): void\n {\n $this->configureSentryScope($user);\n\n $this->team = $user->getTeam();\n $this->teamService->setTeam($user->getTeam());\n $this->setConfiguration($user->getTeam()->getCrmConfiguration());\n\n // Reset state.\n $this->profile = $user->getProfile();\n\n if (! $this->profile instanceof Profile) {\n // Try to fetch their profile, maybe it was not yet imported?\n $this->profile = $this->getProfile($user);\n }\n }\n\n public function setConfiguration(Configuration $configuration): void\n {\n $this->config = $configuration;\n $this->copperClient = $this->clientFactory->create($configuration);\n\n if ($this->team === null) {\n $this->team = $configuration->getTeam();\n }\n }\n\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return $this->fieldValueConverter->convertFromCrm($fieldType, $fieldValue);\n }\n\n private function mapObjectType(string $objectType): string\n {\n $objectType = strtolower($objectType);\n\n switch ($objectType) {\n case Field::OBJECT_TASK:\n case Field::OBJECT_OPPORTUNITY:\n case Field::OBJECT_LEAD:\n $mappedType = $objectType;\n\n break;\n case Field::OBJECT_ACCOUNT:\n $mappedType = 'company';\n\n break;\n case Field::OBJECT_CONTACT:\n $mappedType = 'person';\n\n break;\n default:\n $mappedType = self::UNSUPPORTED_OBJECT_TYPE;\n\n break;\n }\n\n return $mappedType;\n }\n\n /**\n * @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact\n */\n protected function getFields(string $crmObject): array\n {\n $mappedObjectType = $this->mapObjectType($crmObject);\n\n if (! $this->isSupportedObjectType($mappedObjectType)) {\n return [];\n }\n\n $customFields = $this->copperClient->fields()->all();\n\n $filteredFields = array_filter(\n $customFields,\n static fn ($field) => in_array($mappedObjectType, $field['available_on'], true)\n );\n\n return array_map(\n fn (array $property) => [\n 'name' => $property['id'],\n 'label' => $property['name'],\n 'type' => $this->convertFieldType($property['data_type']),\n ],\n $filteredFields\n );\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {\n $defaultFields = FieldDefinitions::defaultTaskFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n $fieldFilters = FieldDefinitions::taskFollowupFieldsFilter();\n\n foreach ($fieldFilters as $data) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n public function syncFields(): void\n {\n $this->syncStandardFields();\n $this->syncCustomFields();\n }\n\n public function syncField(Field $field): void\n {\n if ($field->getCrmProviderId() === 'type') {\n /**\n * This field is a special case, it is not a custom field and is not returned by the Copper API.\n *\n * The field is created manually during layout setup.\n *\n * @see getDefaultFields()\n *\n * There is a separate endpoint to get the activity types.\n * @see importPicklistValues()\n */\n return;\n }\n\n if ($field->getCrmProviderId() === 'pipeline_stage_id') {\n // Not a custom type\n return;\n }\n\n $crmField = $this->copperClient->fields()->find($field->getCrmProviderId());\n $field->label = $crmField['name'];\n $field->type = $this->convertFieldType($crmField['data_type']);\n\n $field->save();\n }\n\n /**\n * @param string $fieldType How the data should be input\n */\n private function convertFieldType(string $fieldType): string\n {\n $fieldType = strtolower($fieldType);\n\n switch ($fieldType) {\n case 'dropdown':\n $convertedType = Field::TYPE_PICKLIST;\n\n break;\n case 'string':\n $convertedType = Field::TYPE_TEXT;\n\n break;\n case 'float':\n case 'percentage':\n $convertedType = Field::TYPE_NUMBER;\n\n break;\n case 'text':\n $convertedType = Field::TYPE_TEXTAREA;\n\n break;\n case 'checkbox':\n $convertedType = Field::TYPE_BOOLEAN;\n\n break;\n case Field::TYPE_DATE:\n case Field::TYPE_CURRENCY:\n case Field::TYPE_URL:\n $convertedType = $fieldType;\n\n break;\n default:\n $convertedType = Field::TYPE_UNSUPPORTED;\n\n break;\n }\n\n return $convertedType;\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $fieldValues = [];\n\n if ($field->object_type === 'opportunity' && $field->crm_provider_id === 'pipeline_stage_id') {\n return $this->importFieldValuesForDealInsights($field);\n }\n\n $values = [];\n\n if ($field->object_type === Field::OBJECT_TASK && $field->crm_provider_id === 'type') {\n $activityTypes = $this->copperClient->activityTypes()->all();\n\n /**\n * We ignore \"system\" activity types, disabled activity types and the \"Note\" activity type.\n */\n $activityTypes = array_filter(\n $activityTypes['user'],\n fn (array $activityType) => ! $activityType['is_disabled'] && $activityType['id'] !== 0\n );\n\n // Import all activity values.\n $i = 0;\n foreach ($activityTypes as $activityType) {\n $values[] = [\n 'value' => $activityType['id'],\n 'label' => mb_strimwidth($activityType['name'], 0, Field::LABEL_MAX_LENGTH),\n 'sequence' => $i++,\n ];\n }\n } else {\n // We just check for the field in the custom definitions.\n $crmField = $this->copperClient->fields()->find($field->crm_provider_id);\n\n // Import all values.\n foreach ($crmField['options'] as $option) {\n $values[] = [\n 'value' => $option['id'],\n 'label' => mb_strimwidth($option['name'], 0, 191),\n 'sequence' => $option['rank'],\n ];\n }\n }\n\n // Take the existing set of field values.\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n // For all current values, upsert the field.\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n $key = array_search($value['value'], $fieldsToPurge, false);\n if ($key !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n\n return $fieldValues;\n }\n\n /**\n *\n * @return FieldValue[]\n */\n private function importFieldValuesForDealInsights(Field $field): array\n {\n $fieldValues = [];\n $pipelines = $this->copperClient->pipelines()->all();\n\n foreach ($pipelines as $pipeline) {\n foreach ($pipeline['stages'] as $i => $dealStage) {\n $fieldValues[] = $field->values()->updateOrCreate(\n ['value' => $dealStage['id']],\n [\n 'label' => $dealStage['name'],\n 'sequence' => $i,\n ]\n );\n }\n }\n\n return $fieldValues;\n }\n\n /**\n * @inheritdoc\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n $missingStage = null;\n\n foreach ($types as $type) {\n if ($type === Stage::TYPE_LEAD) {\n $statuses = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leadStatuses()->all()\n );\n\n if (count($statuses) > 0) {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => BusinessProcess::TYPE_LEAD,\n ], [\n 'team_id' => $this->team->id,\n 'name' => BusinessProcess::TYPE_LEAD,\n 'type' => BusinessProcess::TYPE_LEAD,\n 'is_selectable' => true,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => BusinessProcess::TYPE_LEAD,\n ], [\n 'team_id' => $this->team->id,\n 'name' => BusinessProcess::TYPE_LEAD,\n 'is_selectable' => true,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $leadStatuses = [];\n foreach ($statuses as $status) {\n // Upsert all statuses for the team.\n $status = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $status['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($status['name'], 0, 50),\n 'label' => mb_strimwidth($status['name'], 0, 191),\n 'type' => Stage::TYPE_LEAD,\n 'sequence' => $status['order'],\n 'is_selectable' => true,\n ]);\n\n if ($missingStageName && $missingStageName === $status['id']) {\n $missingStage = $status;\n }\n\n $leadStatuses[] = $status['id'];\n }\n\n $businessProcess->stages()->sync($leadStatuses);\n }\n } else {\n // We create a business process to contain the pipeline, and later store all stages against it.\n foreach ($this->copperClient->pipelines()->all() as $pipeline) {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $pipeline['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline['name'], 0, 150),\n 'type' => BusinessProcess::TYPE_OPPORTUNITY,\n 'is_selectable' => true,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $pipeline['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline['name'], 0, 150),\n 'is_selectable' => true,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $stages = [];\n\n foreach ($pipeline['stages'] as $i => $dealStage) {\n // Upsert all stages for the team.\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $dealStage['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($dealStage['name'], 0, 50),\n 'label' => mb_strimwidth($dealStage['name'], 0, 191),\n 'type' => Stage::TYPE_OPPORTUNITY,\n 'sequence' => $i,\n 'is_selectable' => true,\n 'probability' => $dealStage['win_probability'],\n ]);\n\n if ($missingStageName && $missingStageName === $dealStage['id']) {\n $missingStage = $stage;\n }\n\n $stages[] = $stage['id'];\n }\n\n $businessProcess->stages()->sync($stages);\n }\n }\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n\n $cpLeads = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->paginate([\n 'minimum_modified_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ])\n );\n\n foreach ($cpLeads as $cpLead) {\n // Only sync if previously imported.\n if ($this->hasLead($cpLead['id']) === false) {\n $this->importLead($cpLead);\n $syncCount++;\n }\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n $cpLead = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->find($crmId)\n );\n\n if (\\count($cpLead) === 0) {\n return null;\n }\n\n return $this->importLead($cpLead);\n }\n\n /**\n * @inheritdoc\n */\n private function importLead($crmData): ?Lead\n {\n $countryCode = null;\n if (! empty($crmData['address']) && isset($crmData['address']['country'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $mobilePhone = $parsedNumber = null;\n if (! empty($crmData['phone_numbers'])) {\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n if ($phoneNumber['category'] === 'mobile') {\n $mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);\n } else {\n $parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);\n }\n }\n }\n\n $name = $crmData['name'];\n\n if (empty($crmData['company_name'])) {\n $company = 'Unknown';\n } else {\n $company = mb_strimwidth($crmData['company_name'], 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['websites']) === false) {\n $domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $email = null;\n if (empty($crmData['email']) === false) {\n $email = mb_strimwidth($crmData['email']['email'], 0, 80);\n }\n\n $stage = $this->config\n ->stages()\n ->where('crm_provider_id', (string) $crmData['status_id'])\n ->where('type', Stage::TYPE_LEAD)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status_id']);\n }\n\n if (! $stage instanceof Stage) {\n return null;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($name, 0, 191),\n 'company' => $company,\n 'domain' => $domain,\n 'title' => $crmData['title'] ? mb_strimwidth($crmData['title'], 0, 128) : null,\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'mobile_phone' => $mobilePhone,\n 'stage_id' => $stage->id,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Lead::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'country_code' => $countryCode,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $cpAccounts = $this->copperClient->accounts()->paginate([\n 'minimum_modified_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ]);\n\n foreach ($cpAccounts as $cpAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($cpAccount['id'])) {\n $this->importAccount($cpAccount);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n $cpAccount = $this->copperClient->accounts()->find($crmId);\n\n if (empty($cpAccount)) {\n return null;\n }\n\n return $this->importAccount($cpAccount);\n }\n\n /**\n * @inheritdoc\n */\n private function importAccount($crmData): Account\n {\n $countryCode = null;\n if (empty($crmData['address']) === false && $crmData['address']['country']) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $name = $crmData['name'];\n\n $parsedNumber = null;\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n $parsedNumber = parsePhoneNumber($countryCode, $phoneNumber['number']);\n }\n\n $domain = null;\n if (empty($crmData['websites']) === false) {\n $domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Account::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'country_code' => $countryCode,\n 'domain' => $domain,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->copperClient,\n ]);\n $strategies = $strategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n\n try {\n foreach ($strategies as $syncStrategy) {\n foreach ($syncStrategy->fetchOpportunities($parameters) as $opportunityData) {\n $this->importOpportunity($opportunityData);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n $this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => $exception->getMessage(),\n ]);\n }\n\n return $syncCount;\n }\n\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->copperClient,\n ]);\n $strategy = $strategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n $parameters['crm_id'] = $crmId;\n\n $cpOpportunity = $strategy->fetchOpportunities($parameters);\n\n return $this->importOpportunity($cpOpportunity);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n $companyId = (string) $crmData['company_id'];\n\n if (empty($companyId)) {\n $this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => 'No company id',\n ]);\n\n return null;\n }\n\n $account = $this->config->accounts()->where('crm_provider_id', $companyId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($companyId);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', (string) $crmData['pipeline_id'])\n ->first();\n\n if ($businessProcess === null) {\n // It is possible for some deals to not be in a pipeline.\n $this->logger->warning(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => 'Missing pipeline',\n ]);\n\n return null;\n }\n\n $stage = $businessProcess\n ->stages()\n ->where('crm_provider_id', (string) $crmData['pipeline_stage_id'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n $this->logger->info('Stage not found, importing', [\n 'pipeline_id' => $crmData['pipeline_id'],\n 'stage_id' => $crmData['pipeline_stage_id'],\n ]);\n\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['pipeline_stage_id']);\n }\n\n $recordType = $businessProcess->recordTypes()->first();\n $closeDate = null;\n $isClosed = $crmData['status'] !== self::OPPORTUNITY_STATUS_OPEN;\n\n if ($crmData['close_date']) {\n $closeDate = Carbon::parse($crmData['close_date'])->format('Y-m-d');\n }\n\n $data = [\n 'team_id' => $this->team->getId(),\n 'account_id' => $account->id,\n 'user_id' => $profile->user_id ?? null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($crmData['name'], 0, 128),\n 'value' => $crmData['monetary_value'],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['monetary_unit']),\n 'close_date' => $closeDate,\n 'is_closed' => $isClosed,\n 'is_won' => $crmData['status'] === 'Won',\n 'stage_id' => $stage->id,\n 'record_type_id' => $recordType->id ?? null,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n /** @var Opportunity $opportunity */\n $opportunity = $this->config\n ->opportunities()\n ->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data)\n ;\n\n // import external fields into crm_field_data if present\n $dealInsightsFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData($crmData, $dealInsightsFields, $opportunity->id);\n\n return $opportunity;\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n * @param string[] $dealInsightsFields\n */\n public function importOpportunityCrmFieldData(\n array $opportunityData,\n array $dealInsightsFields,\n int $opportunityId\n ): void {\n foreach ($dealInsightsFields as $fieldName) {\n $field = $this->config->fields()->with('entities')\n ->where('crm_provider_id', $fieldName)\n ->where('object_type', Field::OBJECT_OPPORTUNITY)\n ->first();\n\n if (! $field instanceof Field) {\n $this->logger->warning('Field not found', [\n 'field' => $fieldName,\n 'opportunity_id' => $opportunityId,\n ]);\n\n continue;\n }\n\n $entity = $field->getEntities()->first();\n\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $fieldValue = $this->extractFieldValue($opportunityData, $fieldName);\n $normalizedValue = $this->normalizeValue($field->getType(), (string) $fieldValue, true);\n\n $field->data()\n ->updateOrCreate([\n 'crm_layout_entity_id' => $entity->id,\n 'crm_field_id' => $field->id,\n 'object_type' => 'opportunity',\n 'object_id' => $opportunityId,\n ], ['value' => $normalizedValue])\n ;\n }\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $cpContacts = $this->copperClient->contacts()->paginate([\n 'minimum_interaction_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ]);\n\n foreach ($cpContacts as $cpContact) {\n // Only sync if previously imported.\n if ($this->hasContact($cpContact['id'])) {\n $this->importContact($cpContact);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n throw $exception;\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n $cpContact = $this->copperClient->contacts()->find($crmId);\n\n if (empty($cpContact)) {\n return null;\n }\n\n return $this->importContact($cpContact);\n }\n\n /**\n * @inheritdoc\n */\n private function importContact($crmData): Contact\n {\n $account = null;\n if ($crmData['company_id']) {\n $account = $this->team\n ->crm\n ->accounts()\n ->where('crm_provider_id', (string) $crmData['company_id'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['company_id']);\n }\n }\n\n $countryCode = null;\n if (empty($crmData['address']) === false && $crmData['address']['country']) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $mobilePhone = $parsedNumber = null;\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n if ($phoneNumber['category'] === 'mobile') {\n $mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);\n } else {\n $parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);\n }\n }\n\n $email = null;\n if (empty($crmData['emails']) === false) {\n $email = mb_strimwidth($crmData['emails'][0]['email'], 0, 80);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => $crmData['name'],\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'mobile_phone' => $mobilePhone ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'title' => $crmData['title'],\n 'country_code' => $countryCode,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Contact::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function buildContactPhone(?string $countryCode, ?string $number): ?array\n {\n if ($number) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($number, 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n return $parsedNumber;\n }\n\n private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string\n {\n return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n $organization = $this->copperClient->organisation()->all();\n\n if ($this->config->crm_provider_id !== $organization['id']) {\n $this->config->update(['crm_provider_id' => $organization['id']]);\n }\n }\n\n private function syncCustomFields(): void\n {\n foreach ($this->getFieldTypes() as $fieldType) {\n $currentFields = $this->getFields($fieldType);\n\n foreach ($currentFields as $field) {\n /** @var Field $field */\n $field = $this->config->fields()->updateOrCreate([\n 'crm_provider_id' => $field['name'],\n 'object_type' => $fieldType,\n ], [\n 'label' => mb_strimwidth($field['label'], 0, Field::LABEL_MAX_LENGTH),\n 'type' => $field['type'],\n ]);\n\n if ($field->getType() === Field::TYPE_PICKLIST) {\n $this->importPicklistValues($field);\n }\n }\n }\n\n $this->config->save();\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n parent::OBJECT_LEAD,\n parent::OBJECT_ACCOUNT,\n parent::OBJECT_CONTACT,\n parent::OBJECT_OPPORTUNITY,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $profiles = $this->copperClient->users()->all();\n\n foreach ($profiles as $profile) {\n $user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);\n\n // Only import profiles for users we have locally.\n if ($user) {\n $profile = $user->crmProfile()->updateOrCreate([\n 'crm_configuration_id' => $this->config->id,\n 'crm_provider_id' => $profile['id'],\n ]);\n\n if ($userToSearch && $userToSearch->id === $user->id) {\n return $profile;\n }\n }\n }\n\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'task',\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields(ucfirst($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))\n );\n\n if (\\count($changedFields) > 0) {\n $fields = implode(',', $newFields);\n $this->logger->debug(\n ucfirst($fieldType)\n . ' fields changed from '\n . $this->profile->{$fieldType . '_fields'}\n . ' to: '\n . $fields\n );\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (\\Exception $exception) {\n $this->logger->error('No access to ' . $fieldType . ' object, skipping...');\n\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $scopeValues = array_map(fn ($scope) => is_string($scope) ? $scope : $scope->value, $scopes);\n $cacheKey = sprintf('copper-search-%d-%s-%s-%d-%d', $this->team->id, $name, implode('-', $scopeValues), $count, $offset);\n\n return Cache::remember($cacheKey, 300, function () use ($name, $scopes, $count, $offset) {\n // Try local search first\n $localResults = $this->searchLocally($name, $scopes, $count, $offset);\n\n // If no local results, fall back to remote API search\n if (empty($localResults)) {\n return $this->searchRemotely($name, $scopes, $count, $offset);\n }\n\n return $localResults;\n });\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $params = [\n 'company_ids' => [$account->crm_provider_id],\n 'status_ids' => [0], // The integer values are 0, 1, 2, 3, for \"Open\", \"Won\", \"Lost\", and \"Abandoned\".\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ];\n\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort_by'] = 'date_modified';\n $params['sort_direction'] = 'desc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort_by'] = 'date_created';\n $params['sort_direction'] = 'desc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort_by'] = 'date_created';\n $params['sort_direction'] = 'asc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort_by'] = 'date_modified';\n $params['sort_direction'] = 'desc';\n $params['status_ids'] = [0, 1, 2, 3];\n }\n\n $cpOpportunities = $this->copperClient->opportunities()->search($params);\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n foreach ($cpOpportunities as $cpOpportunity) {\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', (string) $cpOpportunity['pipeline_id'])\n ->first();\n\n if ($businessProcess === null) {\n // Import it.\n $businessProcess = $this->importStages(\n [Stage::TYPE_OPPORTUNITY],\n $cpOpportunity['pipeline_stage_id']\n );\n }\n\n $stage = $businessProcess\n ->stages()\n ->where('crm_provider_id', (string) $cpOpportunity['pipeline_stage_id'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $cpOpportunity['pipeline_stage_id']);\n }\n\n $recordType = $businessProcess->recordTypes()->first();\n\n $record = [\n 'crmId' => $cpOpportunity['id'],\n 'name' => $cpOpportunity['name'],\n 'value' => currency_format($cpOpportunity['monetary_value'], $cpOpportunity['monetary_unit']),\n 'won' => $cpOpportunity['status'] === 'Won',\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n\n if ($ownerId && isset($cpOpportunity['assignee_id']) && $cpOpportunity['assignee_id'] === $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $cpTasks = [];\n\n switch ($objectType) {\n case 'lead':\n $cpTasks = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->relatedTasks($objectId)\n );\n\n break;\n\n case 'account':\n $cpTasks = $this->copperClient->accounts()->relatedTasks($objectId);\n\n break;\n case 'contact':\n if ($opportunityId) {\n $cpTasks = $this->copperClient->opportunities()->relatedTasks($opportunityId);\n } elseif ($objectType === 'contact') {\n $cpTasks = $this->copperClient->contacts()->relatedTasks($objectId);\n }\n\n break;\n }\n\n foreach ($cpTasks as $cpTask) {\n // We only get the ID itself returned, so pull out the full object.\n try {\n $cpTask = $this->copperClient->tasks()->find($cpTask['id']);\n } catch (Exception $exception) {\n $this->logger->error('[Copper] Error fetching task', [\n 'resource_id' => $cpTask['id'],\n 'error' => $exception->getMessage(),\n ]);\n\n continue;\n }\n\n // Only allow open tasks.\n if ($cpTask['status'] === 'Open') {\n $data[] = [\n 'crmId' => $cpTask['id'],\n 'subject' => $cpTask['name'],\n 'due' => $cpTask['due_date']\n ? Carbon::createFromTimestamp($cpTask['due_date'])->format('Y-m-d\\TH:i:sO')\n : null,\n 'type' => null,\n ];\n }\n }\n\n return $data;\n }\n\n /**\n * Try to find email address in CRM service\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $cpObjectType = 'contact';\n\n $cpObjects = $this->copperClient->contacts()->search([\n 'emails' => $email,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (empty($cpObjects)) {\n $cpObjectType = 'lead';\n $cpObjects = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'emails' => $email,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (empty($cpObjects)) {\n return null;\n }\n\n // Search returns an array of results, but we only want the first\n $cpObject = reset($cpObjects);\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember === false) {\n $cpObjectType = 'contact';\n $cpObject = $this->copperClient->contacts()->search([\n 'phone_number' => $phone,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (\\count($cpObject) === 0) {\n $cpObjectType = 'lead';\n $cpObject = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'phone_number' => $phone,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (empty($cpObject)) {\n return null;\n }\n\n $cpObject = reset($cpObject);\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n return null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n $result = \\Cache::remember($this->team->id . $name, 60, function () use ($name, $userId) {\n $cpObjectType = 'contact';\n $cpObject = $this->copperClient->contacts()->search([\n 'name' => $name,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (\\count($cpObject) === 0) {\n $cpObjectType = 'lead';\n $cpObject = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'name' => $name,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (! empty($cpObject)) {\n $cpObject = reset($cpObject);\n }\n\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n private function convertCrmData(array $object, string $objectType, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n if ($objectType === 'lead') {\n $lead = $this->importLead($object);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } else {\n $contact = $this->importContact($object);\n $account = $contact->account;\n\n if ($contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $cpOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact->crm_provider_id,\n $userId,\n );\n\n if (! empty($cpOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($cpOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n } catch (\\Exception $e) {\n // Nothing to see here.\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n public function saveActivity(Activity $activity): Activity\n {\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n $activity = $this->buildCallPayload($activity);\n\n break;\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildTextMessagePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n private function convertActivityAssociations(Activity $activity): array\n {\n if ($activity->lead) {\n $type = 'lead';\n $id = $activity->lead->crm_provider_id;\n } elseif ($activity->contact) {\n $type = 'person';\n $id = $activity->contact->crm_provider_id;\n } elseif ($activity->opportunity) {\n $type = 'opportunity';\n $id = $activity->opportunity->crm_provider_id;\n } else {\n $type = 'company';\n $id = $activity->account->crm_provider_id;\n }\n\n return [\n 'type' => $type,\n 'id' => $id,\n ];\n }\n\n private function convertActivityType(PlaybookCategory $activityType): array\n {\n return [\n 'category' => 'user',\n 'id' => $this->getCrmType($activityType)->value,\n ];\n }\n\n /**\n * @throws CrmException\n */\n private function buildCallPayload(Activity $activity): Activity\n {\n try {\n if ($activity->crm_provider_id) {\n // The activity should be logged under the existing Task (not Activity).\n $newActivityType = $this->getCrmType($activity->category);\n if ($newActivityType === null) {\n $message = sprintf('[Copper] invalid CRM Custom Activity Type: %s', $activity->category);\n\n throw new CrmException($message, 400);\n }\n $this->copperClient->tasks()->update($activity->crm_provider_id, [\n 'status' => 'Completed',\n 'custom_activity_type_id' => $newActivityType->value,\n 'details' => $this->generateActivityDescription($activity),\n ]);\n } else {\n if ($this->getCrmType($activity->category) === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n if ($this->getCrmType($activity->category)->value === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n // Just create an activity.\n $cpActivity = $this->copperClient->activities()->create([\n 'user_id' => $this->profile->crm_provider_id,\n 'activity_date' => $activity->scheduled_start_time->timestamp,\n 'parent' => $this->convertActivityAssociations($activity),\n 'type' => $this->convertActivityType($activity->category),\n 'details' => $this->generateActivityDescription($activity),\n ]);\n\n $activity->crm_provider_id = $cpActivity['id'];\n $activity->save();\n }\n } catch (ClientException $exception) {\n //Log all errors to Sentry\n \\Sentry::captureException($exception);\n\n $response = $exception->getResponse();\n\n $responseBody = $response->getBody();\n $message = $responseBody;\n $errorCode = $response->getStatusCode();\n\n $jsonResponse = json_decode($responseBody, true);\n if (isset($jsonResponse[0]['message'])) {\n $message = $jsonResponse[0]['message'];\n }\n\n throw new CrmException($message, $errorCode);\n }\n\n return $activity;\n }\n\n private function buildTextMessagePayload(Activity $activity): Activity\n {\n if ($this->getCrmType($activity->category) === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n if ($this->getCrmType($activity->category)->value === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n $cpActivity = $this->copperClient->activities()->create([\n 'user_id' => $this->profile->crm_provider_id,\n 'activity_date' => $activity->created_at->timestamp,\n 'parent' => $this->convertActivityAssociations($activity),\n 'type' => $this->convertActivityType($activity->category),\n 'details' => $this->generateActivityDescription($activity),\n ]);\n\n $activity->crm_provider_id = $cpActivity['id'];\n $activity->save();\n\n return $activity;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = '';\n\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n $description = 'Jiminny Call Summary' . PHP_EOL . PHP_EOL;\n $description .= 'Call Duration: ' . $activity->duration_for_humans . PHP_EOL . PHP_EOL;\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= 'Dialed: ' . $activity->to->phone_number . PHP_EOL . PHP_EOL;\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= 'Notetaker removed from this meeting' . PHP_EOL . PHP_EOL;\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= 'Notetaker did not join due to recording consent not being provided by attendees' . PHP_EOL . PHP_EOL;\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= 'Review Activity:' . PHP_EOL . $playbackUrl . PHP_EOL . PHP_EOL;\n }\n\n if ($activity->getCrmType() === Activity::TYPE_CONFERENCE) {\n $description .= 'Attendees:'\n . PHP_EOL\n . (new FilterJoinedParticipants())->toString($activity);\n }\n\n if (\\count($activity->notes) > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Notes: ' . PHP_EOL;\n\n foreach ($activity->notes as $note) {\n $nTime = (int) ceil($note->time);\n $time = ($nTime > 3600) ? gmdate('H:i:s', $nTime) : gmdate('i:s', $nTime);\n $description .= $time . ' ' . $note->note . PHP_EOL;\n }\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Coaching Chat: ' . PHP_EOL;\n\n foreach ($messages->get() as $message) {\n $description .= $message->participant->name . ': ' . $message->message . PHP_EOL;\n }\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Customer Chat: ' . PHP_EOL;\n\n foreach ($messages->get() as $message) {\n $description .= $message->participant->name . ': ' . $message->message . PHP_EOL;\n }\n }\n\n if ($activity->summary) {\n $description .= PHP_EOL . PHP_EOL . 'Summary: ' . PHP_EOL . $activity->summary;\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $description = $activity->description;\n\n break;\n }\n\n return $description;\n }\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // This is the user provided activity subject field.\n if (empty($fields['type'])) {\n return null;\n }\n\n $reminder = null;\n if (empty($fields['reminder_date']) === false) {\n $formatReminder = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['reminder_date']);\n $reminder = $formatReminder->getTimestamp();\n }\n\n $due = null;\n if (empty($fields['due_date']) === false) {\n $formatDue = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['due_date']);\n $due = $formatDue->getTimestamp();\n }\n\n $data = [\n 'custom_activity_type_id' => $fields['type'],\n 'status' => 'Open',\n 'assignee_id' => $this->profile->crm_provider_id,\n 'due_date' => $due,\n 'details' => $fields['details'] ?? '',\n 'reminder_date' => $reminder,\n 'name' => $fields['name'] ?? 'Follow-up',\n 'related_resource' => $this->convertActivityAssociations($activity),\n 'custom_fields' => $this->fetchCustomFieldData($activity, Field::OBJECT_TASK),\n ];\n\n // We don't actually create a corresponding activity object on our side yet.\n return $this->copperClient->tasks()->create($data)['id'];\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws \\Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // Generate activity transcription.\n $transcriptionData = $this->generateTranscription($activity);\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $transcripts = mb_strimwidth($transcriptionData, 0, static::NOTE_BODY_MAX_LENGTH);\n\n $data = [\n 'user_id' => $this->profile->crm_provider_id,\n 'type' => [\n 'category' => 'user',\n 'id' => 0, // This creates a note.\n ],\n 'activity_date' => time(),\n 'details' => $transcripts,\n 'parent' => $this->convertActivityAssociations($activity),\n ];\n\n $cpActivity = $this->copperClient->activities()->create($data);\n\n // Store CRM Activity ID in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $cpActivity['id'];\n $transcription->save();\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n if ($crmObject instanceof Lead) {\n $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->update($crmObject->crm_provider_id, [\n 'status_id' => $stage->crm_provider_id,\n ])\n );\n } else {\n $this->copperClient->opportunities()->update($crmObject->crm_provider_id, [\n 'pipeline_stage_id' => $stage->crm_provider_id,\n ]);\n }\n }\n\n public function prepareValueForUpdate(array $params): array\n {\n return [$params['fieldName'] => $params['fieldValue']];\n }\n\n /*\n * @inheritdoc\n */\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $preparedData = $data;\n\n if ($objectType === Field::OBJECT_OPPORTUNITY) {\n $preparedData = $this->prepareOpportunityFieldsForUpdate($data);\n }\n\n try {\n $this->copperClient\n ->createResourceFromObjectType($objectType)\n ->update($objectId, $preparedData)\n ;\n } catch (Exception $e) {\n $this->logger->error(self::RESOURCE_UPDATE_FAILED_ERROR_MESSAGE, [\n 'resource_id' => $objectId,\n 'data' => $preparedData,\n 'error' => $e->getMessage(),\n ]);\n\n throw new CrmException(self::RESOURCE_UPDATE_FAILED_ERROR_MESSAGE, $e->getCode(), $e);\n }\n }\n\n /**\n * @param array<string,string> $fieldData\n *\n * @throws CrmException\n *\n * @return array<string,array<int,array<string,bool|float|int|string|null>>|bool|float|int|string|null>\n */\n private function prepareOpportunityFieldsForUpdate(array $fieldData): array\n {\n $preparedData = [];\n $customFields = [];\n\n foreach ($fieldData as $fieldName => $fieldValue) {\n $field = $this->config\n ->fields()\n ->where('crm_provider_id', $fieldName)\n ->first();\n\n if (! $field instanceof Field) {\n throw new CrmException('Field not found');\n }\n\n $convertedValue = $this->fieldValueConverter->convertToCrm($field->getType(), $fieldValue);\n\n if ($this->isStandardField($fieldName)) {\n $preparedData[$fieldName] = $convertedValue;\n\n continue;\n }\n\n $customFields[] = [\n 'custom_field_definition_id' => $fieldName,\n 'value' => $convertedValue,\n ];\n }\n\n if (! empty($customFields)) {\n $preparedData['custom_fields'] = $customFields;\n }\n\n return $preparedData;\n }\n\n /*\n * @inheritdoc\n */\n public function getRecord(string $objectType, string $objectId, array $fields = []): array\n {\n return $this->copperClient->createResourceFromObjectType($objectType)->find($objectId);\n }\n\n private function fetchCustomFieldData(Activity $activity, string $objectType): array\n {\n $payload = [];\n\n $fieldData = FieldData::where([\n 'object_id' => $activity->id,\n ])->whereHas('field', function ($query) use ($objectType) {\n $query->where('object_type', $objectType);\n })->get();\n\n foreach ($fieldData as $data) {\n // Add the field and value to the payload.\n $payload += [\n 'custom_field_definition_id' => $data->field->crm_provider_id,\n 'value' => $data->value,\n ];\n }\n\n return $payload;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $baseUrl = 'https://app.prosperworks.com/companies/' . $this->config->crm_provider_id . '/app#/';\n switch ($objectType) {\n case 'lead':\n $url = $baseUrl . 'leads/' . $providerId;\n\n break;\n\n case 'account':\n $url = $baseUrl . 'organization/' . $providerId;\n\n break;\n\n case 'contact':\n $url = $baseUrl . 'contact/' . $providerId;\n\n break;\n\n case 'opportunity':\n $url = $baseUrl . 'deal/' . $providerId;\n\n break;\n\n default:\n case 'task':\n case 'activity':\n // Sadly we can't deeplink to these in Copper UI.\n $url = null;\n }\n\n return $url;\n }\n\n /**\n * Generate transcription for the activity.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! ($this->config->store_transcript)) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n return $this->transcriptionService\n ->findTranscriptionByActivity($activity)\n ->map(static function (array $transcriptionSegment): string {\n return $transcriptionSegment['formattedStartsAt'] . ' | ' . $transcriptionSegment['transcript'];\n })\n ->implode(PHP_EOL);\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n *\n * @return int|string|bool|float|null\n */\n private function extractFieldValue(array $opportunityData, string $fieldName)\n {\n $fieldValue = $this->isStandardField($fieldName)\n ? $opportunityData[$fieldName]\n : $this->resolveCustomFieldFromOpportunityData($opportunityData, $fieldName);\n\n if (is_array($fieldValue)) {\n $fieldValue = implode(', ', $fieldValue);\n }\n\n return $fieldValue;\n }\n\n private function isStandardField(string $fieldName): bool\n {\n return array_key_exists($fieldName, self::STANDARD_OPPORTUNITY_FIELDS);\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n *\n * @return string|int|float|bool|null|array<string, mixed>\n */\n private function resolveCustomFieldFromOpportunityData(array $opportunityData, string $fieldName)\n {\n $fieldData = array_filter(\n $opportunityData['custom_fields'],\n static fn ($field) => (string) $field['custom_field_definition_id'] === $fieldName\n );\n\n return array_pop($fieldData)['value'] ?? '';\n }\n\n private function isSupportedObjectType(string $objectType): bool\n {\n return $objectType !== self::UNSUPPORTED_OBJECT_TYPE;\n }\n\n private function syncStandardFields(): void\n {\n foreach (self::STANDARD_OPPORTUNITY_FIELDS as $fieldId => $fieldData) {\n $this->config->fields()->updateOrCreate([\n 'crm_provider_id' => mb_strimwidth($fieldId, 0, 128),\n 'object_type' => Field::OBJECT_OPPORTUNITY,\n ], [\n 'label' => mb_strimwidth($fieldData['label'], 0, Field::LABEL_MAX_LENGTH),\n 'type' => $fieldData['type'],\n ]);\n }\n\n $this->importStages([Stage::TYPE_OPPORTUNITY]);\n }\n\n private function requestWithExceptionHandling(\\Closure $apiRequest): iterable\n {\n try {\n return $apiRequest();\n } catch (\\Exception $exception) {\n if ($exception->getCode() === 403) {\n // Object might not be supported\n return [];\n }\n\n \\Sentry::captureException($exception);\n\n return [];\n }\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n if ($this->copperClient === null) {\n return false;\n }\n\n $task = $this->copperClient->tasks()->find($crmProviderId);\n\n return ! empty($task);\n } catch (HttpNotFoundException) {\n // Task not found in CRM - this is expected and permanent\n $this->logger->info('[Copper] Task not found during verification', [\n 'task_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n } catch (RequestFailedException $e) {\n // Handle 404 responses from Copper API\n if ($e->getCode() === 404) {\n $this->logger->info('[Copper] Task not found during verification (404)', [\n 'task_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n\n // Re-throw other Copper exceptions for retry\n throw $e;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Copper;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse GuzzleHttp\\Exception\\ClientException;\nuse Illuminate\\Support\\Facades\\Cache;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\CopperInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\FieldValue;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\PlaybookCategory;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\UserRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\Copper\\Api\\Client;\nuse Jiminny\\Services\\Crm\\Copper\\Api\\ClientFactory;\nuse Jiminny\\Services\\Crm\\Copper\\Exception\\RequestFailedException;\nuse Jiminny\\Services\\Crm\\Helpers\\FilterJoinedParticipants;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Services\\Crm\\Copper\\Traits\\SearchesCrmEntities;\nuse Jiminny\\Utils\\CurrencyFormatter;\nuse Jiminny\\Utils\\StringUtil;\n\nclass Service extends BaseService implements\n CopperInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n RemoteEntityManipulationInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n use SearchesCrmEntities;\n private const int NOTE_BODY_MAX_LENGTH = 3000000;\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n private const array STANDARD_OPPORTUNITY_FIELDS = [\n 'monetary_value' => [\n 'label' => 'Value',\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n 'type' => Field::TYPE_CURRENCY,\n ],\n 'pipeline_stage_id' => [\n 'label' => 'Stage',\n 'type' => Field::TYPE_PICKLIST,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n 'close_date' => [\n 'label' => 'Close date',\n 'type' => Field::TYPE_DATE,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n 'win_probability' => [\n 'label' => 'Win probability',\n 'type' => Field::TYPE_NUMBER,\n 'available_on' => Field::OBJECT_OPPORTUNITY,\n ],\n ];\n private const string UNSUPPORTED_OBJECT_TYPE = 'unsupported';\n private const string OPPORTUNITY_STATUS_OPEN = 'Open';\n private const string OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE = 'Opportunity import failed';\n private const string RESOURCE_UPDATE_FAILED_ERROR_MESSAGE = 'Failed to update resource';\n\n private FieldValueConverter $fieldValueConverter;\n private ClientFactory $clientFactory;\n private ?Client $copperClient = null;\n\n public function __construct(\n ClientFactory $clientFactory,\n FieldValueConverter $fieldValueConverter,\n private readonly UserRepository $userRepository,\n private readonly ProspectPhotoPathService $prospectPhotoPathService,\n private readonly CrmEntityRepository $crmEntityRepository\n ) {\n parent::__construct();\n\n $this->clientFactory = $clientFactory;\n $this->fieldValueConverter = $fieldValueConverter;\n }\n\n public function getDisplayName(): string\n {\n return 'Copper';\n }\n\n /**\n * Get the CRM entity repository (used by SearchesCrmEntities trait)\n */\n protected function getCrmEntityRepository(): CrmEntityRepository\n {\n return $this->crmEntityRepository;\n }\n\n public function getMinimumApiVersion(): string\n {\n return Client::MIN_API_VERSION;\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_COPPER);\n }\n\n public function setUser(User $user): void\n {\n $this->configureSentryScope($user);\n\n $this->team = $user->getTeam();\n $this->teamService->setTeam($user->getTeam());\n $this->setConfiguration($user->getTeam()->getCrmConfiguration());\n\n // Reset state.\n $this->profile = $user->getProfile();\n\n if (! $this->profile instanceof Profile) {\n // Try to fetch their profile, maybe it was not yet imported?\n $this->profile = $this->getProfile($user);\n }\n }\n\n public function setConfiguration(Configuration $configuration): void\n {\n $this->config = $configuration;\n $this->copperClient = $this->clientFactory->create($configuration);\n\n if ($this->team === null) {\n $this->team = $configuration->getTeam();\n }\n }\n\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return $this->fieldValueConverter->convertFromCrm($fieldType, $fieldValue);\n }\n\n private function mapObjectType(string $objectType): string\n {\n $objectType = strtolower($objectType);\n\n switch ($objectType) {\n case Field::OBJECT_TASK:\n case Field::OBJECT_OPPORTUNITY:\n case Field::OBJECT_LEAD:\n $mappedType = $objectType;\n\n break;\n case Field::OBJECT_ACCOUNT:\n $mappedType = 'company';\n\n break;\n case Field::OBJECT_CONTACT:\n $mappedType = 'person';\n\n break;\n default:\n $mappedType = self::UNSUPPORTED_OBJECT_TYPE;\n\n break;\n }\n\n return $mappedType;\n }\n\n /**\n * @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact\n */\n protected function getFields(string $crmObject): array\n {\n $mappedObjectType = $this->mapObjectType($crmObject);\n\n if (! $this->isSupportedObjectType($mappedObjectType)) {\n return [];\n }\n\n $customFields = $this->copperClient->fields()->all();\n\n $filteredFields = array_filter(\n $customFields,\n static fn ($field) => in_array($mappedObjectType, $field['available_on'], true)\n );\n\n return array_map(\n fn (array $property) => [\n 'name' => $property['id'],\n 'label' => $property['name'],\n 'type' => $this->convertFieldType($property['data_type']),\n ],\n $filteredFields\n );\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {\n $defaultFields = FieldDefinitions::defaultTaskFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n // Setup the activity field as the default Type.\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'type',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n $fieldFilters = FieldDefinitions::taskFollowupFieldsFilter();\n\n foreach ($fieldFilters as $data) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n public function syncFields(): void\n {\n $this->syncStandardFields();\n $this->syncCustomFields();\n }\n\n public function syncField(Field $field): void\n {\n if ($field->getCrmProviderId() === 'type') {\n /**\n * This field is a special case, it is not a custom field and is not returned by the Copper API.\n *\n * The field is created manually during layout setup.\n *\n * @see getDefaultFields()\n *\n * There is a separate endpoint to get the activity types.\n * @see importPicklistValues()\n */\n return;\n }\n\n if ($field->getCrmProviderId() === 'pipeline_stage_id') {\n // Not a custom type\n return;\n }\n\n $crmField = $this->copperClient->fields()->find($field->getCrmProviderId());\n $field->label = $crmField['name'];\n $field->type = $this->convertFieldType($crmField['data_type']);\n\n $field->save();\n }\n\n /**\n * @param string $fieldType How the data should be input\n */\n private function convertFieldType(string $fieldType): string\n {\n $fieldType = strtolower($fieldType);\n\n switch ($fieldType) {\n case 'dropdown':\n $convertedType = Field::TYPE_PICKLIST;\n\n break;\n case 'string':\n $convertedType = Field::TYPE_TEXT;\n\n break;\n case 'float':\n case 'percentage':\n $convertedType = Field::TYPE_NUMBER;\n\n break;\n case 'text':\n $convertedType = Field::TYPE_TEXTAREA;\n\n break;\n case 'checkbox':\n $convertedType = Field::TYPE_BOOLEAN;\n\n break;\n case Field::TYPE_DATE:\n case Field::TYPE_CURRENCY:\n case Field::TYPE_URL:\n $convertedType = $fieldType;\n\n break;\n default:\n $convertedType = Field::TYPE_UNSUPPORTED;\n\n break;\n }\n\n return $convertedType;\n }\n\n /**\n * @inheritdoc\n */\n public function importPicklistValues(Field $field): array\n {\n $fieldValues = [];\n\n if ($field->object_type === 'opportunity' && $field->crm_provider_id === 'pipeline_stage_id') {\n return $this->importFieldValuesForDealInsights($field);\n }\n\n $values = [];\n\n if ($field->object_type === Field::OBJECT_TASK && $field->crm_provider_id === 'type') {\n $activityTypes = $this->copperClient->activityTypes()->all();\n\n /**\n * We ignore \"system\" activity types, disabled activity types and the \"Note\" activity type.\n */\n $activityTypes = array_filter(\n $activityTypes['user'],\n fn (array $activityType) => ! $activityType['is_disabled'] && $activityType['id'] !== 0\n );\n\n // Import all activity values.\n $i = 0;\n foreach ($activityTypes as $activityType) {\n $values[] = [\n 'value' => $activityType['id'],\n 'label' => mb_strimwidth($activityType['name'], 0, Field::LABEL_MAX_LENGTH),\n 'sequence' => $i++,\n ];\n }\n } else {\n // We just check for the field in the custom definitions.\n $crmField = $this->copperClient->fields()->find($field->crm_provider_id);\n\n // Import all values.\n foreach ($crmField['options'] as $option) {\n $values[] = [\n 'value' => $option['id'],\n 'label' => mb_strimwidth($option['name'], 0, 191),\n 'sequence' => $option['rank'],\n ];\n }\n }\n\n // Take the existing set of field values.\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n // For all current values, upsert the field.\n $value['value'] = substr($value['value'] ?? '', 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n $key = array_search($value['value'], $fieldsToPurge, false);\n if ($key !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n\n return $fieldValues;\n }\n\n /**\n *\n * @return FieldValue[]\n */\n private function importFieldValuesForDealInsights(Field $field): array\n {\n $fieldValues = [];\n $pipelines = $this->copperClient->pipelines()->all();\n\n foreach ($pipelines as $pipeline) {\n foreach ($pipeline['stages'] as $i => $dealStage) {\n $fieldValues[] = $field->values()->updateOrCreate(\n ['value' => $dealStage['id']],\n [\n 'label' => $dealStage['name'],\n 'sequence' => $i,\n ]\n );\n }\n }\n\n return $fieldValues;\n }\n\n /**\n * @inheritdoc\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n if ($types === null) {\n $types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];\n }\n $missingStage = null;\n\n foreach ($types as $type) {\n if ($type === Stage::TYPE_LEAD) {\n $statuses = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leadStatuses()->all()\n );\n\n if (count($statuses) > 0) {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => BusinessProcess::TYPE_LEAD,\n ], [\n 'team_id' => $this->team->id,\n 'name' => BusinessProcess::TYPE_LEAD,\n 'type' => BusinessProcess::TYPE_LEAD,\n 'is_selectable' => true,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => BusinessProcess::TYPE_LEAD,\n ], [\n 'team_id' => $this->team->id,\n 'name' => BusinessProcess::TYPE_LEAD,\n 'is_selectable' => true,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $leadStatuses = [];\n foreach ($statuses as $status) {\n // Upsert all statuses for the team.\n $status = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $status['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($status['name'], 0, 50),\n 'label' => mb_strimwidth($status['name'], 0, 191),\n 'type' => Stage::TYPE_LEAD,\n 'sequence' => $status['order'],\n 'is_selectable' => true,\n ]);\n\n if ($missingStageName && $missingStageName === $status['id']) {\n $missingStage = $status;\n }\n\n $leadStatuses[] = $status['id'];\n }\n\n $businessProcess->stages()->sync($leadStatuses);\n }\n } else {\n // We create a business process to contain the pipeline, and later store all stages against it.\n foreach ($this->copperClient->pipelines()->all() as $pipeline) {\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $pipeline['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline['name'], 0, 150),\n 'type' => BusinessProcess::TYPE_OPPORTUNITY,\n 'is_selectable' => true,\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $pipeline['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($pipeline['name'], 0, 150),\n 'is_selectable' => true,\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n $stages = [];\n\n foreach ($pipeline['stages'] as $i => $dealStage) {\n // Upsert all stages for the team.\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $dealStage['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($dealStage['name'], 0, 50),\n 'label' => mb_strimwidth($dealStage['name'], 0, 191),\n 'type' => Stage::TYPE_OPPORTUNITY,\n 'sequence' => $i,\n 'is_selectable' => true,\n 'probability' => $dealStage['win_probability'],\n ]);\n\n if ($missingStageName && $missingStageName === $dealStage['id']) {\n $missingStage = $stage;\n }\n\n $stages[] = $stage['id'];\n }\n\n $businessProcess->stages()->sync($stages);\n }\n }\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int\n {\n $syncCount = 0;\n\n $cpLeads = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->paginate([\n 'minimum_modified_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ])\n );\n\n foreach ($cpLeads as $cpLead) {\n // Only sync if previously imported.\n if ($this->hasLead($cpLead['id']) === false) {\n $this->importLead($cpLead);\n $syncCount++;\n }\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncLead(string $crmId): ?Lead\n {\n $cpLead = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->find($crmId)\n );\n\n if (\\count($cpLead) === 0) {\n return null;\n }\n\n return $this->importLead($cpLead);\n }\n\n /**\n * @inheritdoc\n */\n private function importLead($crmData): ?Lead\n {\n $countryCode = null;\n if (! empty($crmData['address']) && isset($crmData['address']['country'])) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $mobilePhone = $parsedNumber = null;\n if (! empty($crmData['phone_numbers'])) {\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n if ($phoneNumber['category'] === 'mobile') {\n $mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);\n } else {\n $parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);\n }\n }\n }\n\n $name = $crmData['name'];\n\n if (empty($crmData['company_name'])) {\n $company = 'Unknown';\n } else {\n $company = mb_strimwidth($crmData['company_name'], 0, 191);\n }\n\n $domain = null;\n if (empty($crmData['websites']) === false) {\n $domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $email = null;\n if (empty($crmData['email']) === false) {\n $email = mb_strimwidth($crmData['email']['email'], 0, 80);\n }\n\n $stage = $this->config\n ->stages()\n ->where('crm_provider_id', (string) $crmData['status_id'])\n ->where('type', Stage::TYPE_LEAD)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status_id']);\n }\n\n if (! $stage instanceof Stage) {\n return null;\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($name, 0, 191),\n 'company' => $company,\n 'domain' => $domain,\n 'title' => $crmData['title'] ? mb_strimwidth($crmData['title'], 0, 128) : null,\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'mobile_phone' => $mobilePhone,\n 'stage_id' => $stage->id,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Lead::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'country_code' => $countryCode,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccounts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $cpAccounts = $this->copperClient->accounts()->paginate([\n 'minimum_modified_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ]);\n\n foreach ($cpAccounts as $cpAccount) {\n // Only sync if previously imported.\n if ($this->hasAccount($cpAccount['id'])) {\n $this->importAccount($cpAccount);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncAccount(string $crmId): ?Account\n {\n $cpAccount = $this->copperClient->accounts()->find($crmId);\n\n if (empty($cpAccount)) {\n return null;\n }\n\n return $this->importAccount($cpAccount);\n }\n\n /**\n * @inheritdoc\n */\n private function importAccount($crmData): Account\n {\n $countryCode = null;\n if (empty($crmData['address']) === false && $crmData['address']['country']) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $name = $crmData['name'];\n\n $parsedNumber = null;\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n $parsedNumber = parsePhoneNumber($countryCode, $phoneNumber['number']);\n }\n\n $domain = null;\n if (empty($crmData['websites']) === false) {\n $domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);\n $domain = StringUtil::resolveDomain($domain);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($name, 0, 191),\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Account::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'country_code' => $countryCode,\n 'domain' => $domain,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->copperClient,\n ]);\n $strategies = $strategyResolver->getStrategies($this->config, $strategy);\n\n $syncCount = 0;\n\n try {\n foreach ($strategies as $syncStrategy) {\n foreach ($syncStrategy->fetchOpportunities($parameters) as $opportunityData) {\n $this->importOpportunity($opportunityData);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n $this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => $exception->getMessage(),\n ]);\n }\n\n return $syncCount;\n }\n\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->copperClient,\n ]);\n $strategy = $strategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY\n );\n\n $parameters['crm_id'] = $crmId;\n\n $cpOpportunity = $strategy->fetchOpportunities($parameters);\n\n return $this->importOpportunity($cpOpportunity);\n }\n\n private function importOpportunity($crmData): ?Opportunity\n {\n $companyId = (string) $crmData['company_id'];\n\n if (empty($companyId)) {\n $this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => 'No company id',\n ]);\n\n return null;\n }\n\n $account = $this->config->accounts()->where('crm_provider_id', $companyId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($companyId);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', (string) $crmData['pipeline_id'])\n ->first();\n\n if ($businessProcess === null) {\n // It is possible for some deals to not be in a pipeline.\n $this->logger->warning(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [\n 'error' => 'Missing pipeline',\n ]);\n\n return null;\n }\n\n $stage = $businessProcess\n ->stages()\n ->where('crm_provider_id', (string) $crmData['pipeline_stage_id'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n $this->logger->info('Stage not found, importing', [\n 'pipeline_id' => $crmData['pipeline_id'],\n 'stage_id' => $crmData['pipeline_stage_id'],\n ]);\n\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['pipeline_stage_id']);\n }\n\n $recordType = $businessProcess->recordTypes()->first();\n $closeDate = null;\n $isClosed = $crmData['status'] !== self::OPPORTUNITY_STATUS_OPEN;\n\n if ($crmData['close_date']) {\n $closeDate = Carbon::parse($crmData['close_date'])->format('Y-m-d');\n }\n\n $data = [\n 'team_id' => $this->team->getId(),\n 'account_id' => $account->id,\n 'user_id' => $profile->user_id ?? null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => mb_strimwidth($crmData['name'], 0, 128),\n 'value' => $crmData['monetary_value'],\n 'currency_code' => CurrencyFormatter::formatCode($crmData['monetary_unit']),\n 'close_date' => $closeDate,\n 'is_closed' => $isClosed,\n 'is_won' => $crmData['status'] === 'Won',\n 'stage_id' => $stage->id,\n 'record_type_id' => $recordType->id ?? null,\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n /** @var Opportunity $opportunity */\n $opportunity = $this->config\n ->opportunities()\n ->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data)\n ;\n\n // import external fields into crm_field_data if present\n $dealInsightsFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData($crmData, $dealInsightsFields, $opportunity->id);\n\n return $opportunity;\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n * @param string[] $dealInsightsFields\n */\n public function importOpportunityCrmFieldData(\n array $opportunityData,\n array $dealInsightsFields,\n int $opportunityId\n ): void {\n foreach ($dealInsightsFields as $fieldName) {\n $field = $this->config->fields()->with('entities')\n ->where('crm_provider_id', $fieldName)\n ->where('object_type', Field::OBJECT_OPPORTUNITY)\n ->first();\n\n if (! $field instanceof Field) {\n $this->logger->warning('Field not found', [\n 'field' => $fieldName,\n 'opportunity_id' => $opportunityId,\n ]);\n\n continue;\n }\n\n $entity = $field->getEntities()->first();\n\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $fieldValue = $this->extractFieldValue($opportunityData, $fieldName);\n $normalizedValue = $this->normalizeValue($field->getType(), (string) $fieldValue, true);\n\n $field->data()\n ->updateOrCreate([\n 'crm_layout_entity_id' => $entity->id,\n 'crm_field_id' => $field->id,\n 'object_type' => 'opportunity',\n 'object_id' => $opportunityId,\n ], ['value' => $normalizedValue])\n ;\n }\n }\n\n /**\n * @inheritdoc\n */\n public function syncContacts(Carbon $since, ?Carbon $to = null): int\n {\n $syncCount = 0;\n\n try {\n $cpContacts = $this->copperClient->contacts()->paginate([\n 'minimum_interaction_date' => $since->timestamp,\n 'sort_by' => 'date_modified',\n ]);\n\n foreach ($cpContacts as $cpContact) {\n // Only sync if previously imported.\n if ($this->hasContact($cpContact['id'])) {\n $this->importContact($cpContact);\n $syncCount++;\n }\n }\n } catch (\\Exception $exception) {\n // Do nothing for now.\n throw $exception;\n }\n\n return $syncCount;\n }\n\n /**\n * @inheritdoc\n */\n public function syncContact(string $crmId): ?Contact\n {\n $cpContact = $this->copperClient->contacts()->find($crmId);\n\n if (empty($cpContact)) {\n return null;\n }\n\n return $this->importContact($cpContact);\n }\n\n /**\n * @inheritdoc\n */\n private function importContact($crmData): Contact\n {\n $account = null;\n if ($crmData['company_id']) {\n $account = $this->team\n ->crm\n ->accounts()\n ->where('crm_provider_id', (string) $crmData['company_id'])\n ->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmData['company_id']);\n }\n }\n\n $countryCode = null;\n if (empty($crmData['address']) === false && $crmData['address']['country']) {\n $countryCode = $this->convertCountryNameToCode($crmData['address']['country']);\n }\n\n $mobilePhone = $parsedNumber = null;\n foreach ($crmData['phone_numbers'] as $phoneNumber) {\n if ($phoneNumber['category'] === 'mobile') {\n $mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);\n } else {\n $parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);\n }\n }\n\n $email = null;\n if (empty($crmData['emails']) === false) {\n $email = mb_strimwidth($crmData['emails'][0]['email'], 0, 80);\n }\n\n $profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();\n\n $data = [\n 'team_id' => $this->team->id,\n 'account_id' => $account->id ?? null,\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $crmData['assignee_id'],\n 'name' => $crmData['name'],\n 'email' => $email,\n 'phone' => $parsedNumber['phone'] ?? null,\n 'mobile_phone' => $mobilePhone ?? null,\n 'ext' => $parsedNumber['ext'] ?? null,\n 'title' => $crmData['title'],\n 'country_code' => $countryCode,\n 'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(\n crmConfiguration: $this->config,\n crmProviderId: $crmData['id'],\n modelType: Contact::class,\n fileName: $crmData['id'],\n avatarText: $crmData['name']\n ),\n 'remotely_created_at' => $crmData['date_created'],\n ];\n\n return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);\n }\n\n private function buildContactPhone(?string $countryCode, ?string $number): ?array\n {\n if ($number) {\n // Trim to our width and attempt to parse it.\n $number = mb_strimwidth($number, 0, 25);\n $parsedNumber = parsePhoneNumber($countryCode, $number);\n } else {\n $parsedNumber = [];\n }\n\n return $parsedNumber;\n }\n\n private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string\n {\n return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n $organization = $this->copperClient->organisation()->all();\n\n if ($this->config->crm_provider_id !== $organization['id']) {\n $this->config->update(['crm_provider_id' => $organization['id']]);\n }\n }\n\n private function syncCustomFields(): void\n {\n foreach ($this->getFieldTypes() as $fieldType) {\n $currentFields = $this->getFields($fieldType);\n\n foreach ($currentFields as $field) {\n /** @var Field $field */\n $field = $this->config->fields()->updateOrCreate([\n 'crm_provider_id' => $field['name'],\n 'object_type' => $fieldType,\n ], [\n 'label' => mb_strimwidth($field['label'], 0, Field::LABEL_MAX_LENGTH),\n 'type' => $field['type'],\n ]);\n\n if ($field->getType() === Field::TYPE_PICKLIST) {\n $this->importPicklistValues($field);\n }\n }\n }\n\n $this->config->save();\n }\n\n protected function getFieldTypes(): array\n {\n return [\n parent::OBJECT_TASK,\n parent::OBJECT_LEAD,\n parent::OBJECT_ACCOUNT,\n parent::OBJECT_CONTACT,\n parent::OBJECT_OPPORTUNITY,\n ];\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $profiles = $this->copperClient->users()->all();\n\n foreach ($profiles as $profile) {\n $user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);\n\n // Only import profiles for users we have locally.\n if ($user) {\n $profile = $user->crmProfile()->updateOrCreate([\n 'crm_configuration_id' => $this->config->id,\n 'crm_provider_id' => $profile['id'],\n ]);\n\n if ($userToSearch && $userToSearch->id === $user->id) {\n return $profile;\n }\n }\n }\n\n return null;\n }\n\n /**\n * @inheritdoc\n */\n public function syncProfileFields(): void\n {\n $fieldTypes = [\n 'task',\n 'lead',\n 'account',\n 'contact',\n 'opportunity',\n ];\n\n foreach ($fieldTypes as $fieldType) {\n try {\n $currentFields = $this->getFields(ucfirst($fieldType));\n\n $newFields = array_column($currentFields, 'name');\n $changedFields = array_merge(\n array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),\n array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))\n );\n\n if (\\count($changedFields) > 0) {\n $fields = implode(',', $newFields);\n $this->logger->debug(\n ucfirst($fieldType)\n . ' fields changed from '\n . $this->profile->{$fieldType . '_fields'}\n . ' to: '\n . $fields\n );\n\n $this->profile->{$fieldType . '_fields'} = $fields;\n }\n } catch (\\Exception $exception) {\n $this->logger->error('No access to ' . $fieldType . ' object, skipping...');\n\n continue;\n }\n }\n\n $this->profile->save();\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n $scopeValues = array_map(fn ($scope) => is_string($scope) ? $scope : $scope->value, $scopes);\n $cacheKey = sprintf('copper-search-%d-%s-%s-%d-%d', $this->team->id, $name, implode('-', $scopeValues), $count, $offset);\n\n return Cache::remember($cacheKey, 300, function () use ($name, $scopes, $count, $offset) {\n // Try local search first\n $localResults = $this->searchLocally($name, $scopes, $count, $offset);\n\n // If no local results, fall back to remote API search\n if (empty($localResults)) {\n return $this->searchRemotely($name, $scopes, $count, $offset);\n }\n\n return $localResults;\n });\n }\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n $contact = null;\n $account = null;\n\n if ($crmAccountId) {\n $account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();\n\n if ($account === null) {\n $account = $this->syncAccount($crmAccountId);\n }\n }\n\n if ($crmContactId) {\n $contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();\n\n if ($contact === null) {\n $contact = $this->syncContact($crmContactId);\n }\n }\n\n if ($contact || $account) {\n if ($contact && $account === null) {\n $account = $contact->account;\n }\n\n if ($account === null) {\n return [];\n }\n\n $params = [\n 'company_ids' => [$account->crm_provider_id],\n 'status_ids' => [0], // The integer values are 0, 1, 2, 3, for \"Open\", \"Won\", \"Lost\", and \"Abandoned\".\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ];\n\n switch ($this->config->opportunity_assignment_rule) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $params['sort_by'] = 'date_modified';\n $params['sort_direction'] = 'desc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $params['sort_by'] = 'date_created';\n $params['sort_direction'] = 'desc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $params['sort_by'] = 'date_created';\n $params['sort_direction'] = 'asc';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n $params['sort_by'] = 'date_modified';\n $params['sort_direction'] = 'desc';\n $params['status_ids'] = [0, 1, 2, 3];\n }\n\n $cpOpportunities = $this->copperClient->opportunities()->search($params);\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n foreach ($cpOpportunities as $cpOpportunity) {\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', (string) $cpOpportunity['pipeline_id'])\n ->first();\n\n if ($businessProcess === null) {\n // Import it.\n $businessProcess = $this->importStages(\n [Stage::TYPE_OPPORTUNITY],\n $cpOpportunity['pipeline_stage_id']\n );\n }\n\n $stage = $businessProcess\n ->stages()\n ->where('crm_provider_id', (string) $cpOpportunity['pipeline_stage_id'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $cpOpportunity['pipeline_stage_id']);\n }\n\n $recordType = $businessProcess->recordTypes()->first();\n\n $record = [\n 'crmId' => $cpOpportunity['id'],\n 'name' => $cpOpportunity['name'],\n 'value' => currency_format($cpOpportunity['monetary_value'], $cpOpportunity['monetary_unit']),\n 'won' => $cpOpportunity['status'] === 'Won',\n 'stage' => [\n 'id' => $stage->id_string,\n 'name' => $stage->name,\n ],\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n\n if ($ownerId && isset($cpOpportunity['assignee_id']) && $cpOpportunity['assignee_id'] === $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = $cpTasks = [];\n\n switch ($objectType) {\n case 'lead':\n $cpTasks = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->relatedTasks($objectId)\n );\n\n break;\n\n case 'account':\n $cpTasks = $this->copperClient->accounts()->relatedTasks($objectId);\n\n break;\n case 'contact':\n if ($opportunityId) {\n $cpTasks = $this->copperClient->opportunities()->relatedTasks($opportunityId);\n } elseif ($objectType === 'contact') {\n $cpTasks = $this->copperClient->contacts()->relatedTasks($objectId);\n }\n\n break;\n }\n\n foreach ($cpTasks as $cpTask) {\n // We only get the ID itself returned, so pull out the full object.\n try {\n $cpTask = $this->copperClient->tasks()->find($cpTask['id']);\n } catch (Exception $exception) {\n $this->logger->error('[Copper] Error fetching task', [\n 'resource_id' => $cpTask['id'],\n 'error' => $exception->getMessage(),\n ]);\n\n continue;\n }\n\n // Only allow open tasks.\n if ($cpTask['status'] === 'Open') {\n $data[] = [\n 'crmId' => $cpTask['id'],\n 'subject' => $cpTask['name'],\n 'due' => $cpTask['due_date']\n ? Carbon::createFromTimestamp($cpTask['due_date'])->format('Y-m-d\\TH:i:sO')\n : null,\n 'type' => null,\n ];\n }\n }\n\n return $data;\n }\n\n /**\n * Try to find email address in CRM service\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $cpObjectType = 'contact';\n\n $cpObjects = $this->copperClient->contacts()->search([\n 'emails' => $email,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (empty($cpObjects)) {\n $cpObjectType = 'lead';\n $cpObjects = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'emails' => $email,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (empty($cpObjects)) {\n return null;\n }\n\n // Search returns an array of results, but we only want the first\n $cpObject = reset($cpObjects);\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n // Check if the user is internal.\n $teamMember = $this->team->users()->where('phone', $phone)->exists();\n\n // Skip the attendee if internal.\n if ($teamMember === false) {\n $cpObjectType = 'contact';\n $cpObject = $this->copperClient->contacts()->search([\n 'phone_number' => $phone,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (\\count($cpObject) === 0) {\n $cpObjectType = 'lead';\n $cpObject = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'phone_number' => $phone,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (empty($cpObject)) {\n return null;\n }\n\n $cpObject = reset($cpObject);\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n return null;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n $result = \\Cache::remember($this->team->id . $name, 60, function () use ($name, $userId) {\n $cpObjectType = 'contact';\n $cpObject = $this->copperClient->contacts()->search([\n 'name' => $name,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ]);\n\n if (\\count($cpObject) === 0) {\n $cpObjectType = 'lead';\n $cpObject = $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->search([\n 'name' => $name,\n 'sort_by' => 'date_modified',\n 'sort_direction' => 'desc',\n ])\n );\n }\n\n if (! empty($cpObject)) {\n $cpObject = reset($cpObject);\n }\n\n $data = $this->convertCrmData($cpObject, $cpObjectType, $userId);\n\n return ! empty(array_filter($data)) ? $data : false;\n });\n\n return is_array($result) ? $result : null;\n }\n\n private function convertCrmData(array $object, string $objectType, ?int $userId = null): array\n {\n $lead = null;\n $contact = null;\n $opportunity = null;\n $account = null;\n $stage = null;\n $countryCode = null;\n\n if ($objectType === 'lead') {\n $lead = $this->importLead($object);\n\n // Lead might not be imported if the Stage is null for example.\n if ($lead) {\n $countryCode = $lead->country_code;\n $stage = $lead->stage;\n }\n } else {\n $contact = $this->importContact($object);\n $account = $contact->account;\n\n if ($contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account) {\n $countryCode = $account->country_code;\n }\n\n try {\n $cpOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact->crm_provider_id,\n $userId,\n );\n\n if (! empty($cpOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($cpOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n } catch (\\Exception $e) {\n // Nothing to see here.\n }\n }\n\n return [\n $lead,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n public function saveActivity(Activity $activity): Activity\n {\n switch ($activity->type) {\n case Activity::TYPE_CONFERENCE:\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n $activity = $this->buildCallPayload($activity);\n\n break;\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $activity = $this->buildTextMessagePayload($activity);\n\n break;\n }\n\n return $activity;\n }\n\n private function convertActivityAssociations(Activity $activity): array\n {\n if ($activity->lead) {\n $type = 'lead';\n $id = $activity->lead->crm_provider_id;\n } elseif ($activity->contact) {\n $type = 'person';\n $id = $activity->contact->crm_provider_id;\n } elseif ($activity->opportunity) {\n $type = 'opportunity';\n $id = $activity->opportunity->crm_provider_id;\n } else {\n $type = 'company';\n $id = $activity->account->crm_provider_id;\n }\n\n return [\n 'type' => $type,\n 'id' => $id,\n ];\n }\n\n private function convertActivityType(PlaybookCategory $activityType): array\n {\n return [\n 'category' => 'user',\n 'id' => $this->getCrmType($activityType)->value,\n ];\n }\n\n /**\n * @throws CrmException\n */\n private function buildCallPayload(Activity $activity): Activity\n {\n try {\n if ($activity->crm_provider_id) {\n // The activity should be logged under the existing Task (not Activity).\n $newActivityType = $this->getCrmType($activity->category);\n if ($newActivityType === null) {\n $message = sprintf('[Copper] invalid CRM Custom Activity Type: %s', $activity->category);\n\n throw new CrmException($message, 400);\n }\n $this->copperClient->tasks()->update($activity->crm_provider_id, [\n 'status' => 'Completed',\n 'custom_activity_type_id' => $newActivityType->value,\n 'details' => $this->generateActivityDescription($activity),\n ]);\n } else {\n if ($this->getCrmType($activity->category) === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n if ($this->getCrmType($activity->category)->value === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n // Just create an activity.\n $cpActivity = $this->copperClient->activities()->create([\n 'user_id' => $this->profile->crm_provider_id,\n 'activity_date' => $activity->scheduled_start_time->timestamp,\n 'parent' => $this->convertActivityAssociations($activity),\n 'type' => $this->convertActivityType($activity->category),\n 'details' => $this->generateActivityDescription($activity),\n ]);\n\n $activity->crm_provider_id = $cpActivity['id'];\n $activity->save();\n }\n } catch (ClientException $exception) {\n //Log all errors to Sentry\n \\Sentry::captureException($exception);\n\n $response = $exception->getResponse();\n\n $responseBody = $response->getBody();\n $message = $responseBody;\n $errorCode = $response->getStatusCode();\n\n $jsonResponse = json_decode($responseBody, true);\n if (isset($jsonResponse[0]['message'])) {\n $message = $jsonResponse[0]['message'];\n }\n\n throw new CrmException($message, $errorCode);\n }\n\n return $activity;\n }\n\n private function buildTextMessagePayload(Activity $activity): Activity\n {\n if ($this->getCrmType($activity->category) === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n if ($this->getCrmType($activity->category)->value === null) {\n $message = sprintf('[Copper] Invalid CRM Activity Type: %s value', $activity->category->getName());\n\n throw new CrmException($message, 400);\n }\n\n $cpActivity = $this->copperClient->activities()->create([\n 'user_id' => $this->profile->crm_provider_id,\n 'activity_date' => $activity->created_at->timestamp,\n 'parent' => $this->convertActivityAssociations($activity),\n 'type' => $this->convertActivityType($activity->category),\n 'details' => $this->generateActivityDescription($activity),\n ]);\n\n $activity->crm_provider_id = $cpActivity['id'];\n $activity->save();\n\n return $activity;\n }\n\n private function generateActivityDescription(Activity $activity): string\n {\n $description = '';\n\n switch ($activity->type) {\n case Activity::TYPE_SOFTPHONE:\n case Activity::TYPE_SOFTPHONE_INBOUND:\n case Activity::TYPE_CONFERENCE:\n\n $description = 'Jiminny Call Summary' . PHP_EOL . PHP_EOL;\n $description .= 'Call Duration: ' . $activity->duration_for_humans . PHP_EOL . PHP_EOL;\n\n // Tell them which number was dialed.\n if ($activity->to) {\n $description .= 'Dialed: ' . $activity->to->phone_number . PHP_EOL . PHP_EOL;\n }\n\n if ($activity->hasReasonCodeBotKicked()) {\n $description .= 'Notetaker removed from this meeting' . PHP_EOL . PHP_EOL;\n // When we fix the state to be Activity::RECORDING_RECORDED as it should be this can change.\n } elseif ($activity->hasReasonCodeNotCompliant()) {\n $description .= 'Notetaker did not join due to recording consent not being provided by attendees' . PHP_EOL . PHP_EOL;\n } elseif ($activity->canReviewActivity()) {\n $playbackUrl = $activity->user->team->partner->getPlaybackUrl($activity);\n $description .= 'Review Activity:' . PHP_EOL . $playbackUrl . PHP_EOL . PHP_EOL;\n }\n\n if ($activity->getCrmType() === Activity::TYPE_CONFERENCE) {\n $description .= 'Attendees:'\n . PHP_EOL\n . (new FilterJoinedParticipants())->toString($activity);\n }\n\n if (\\count($activity->notes) > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Notes: ' . PHP_EOL;\n\n foreach ($activity->notes as $note) {\n $nTime = (int) ceil($note->time);\n $time = ($nTime > 3600) ? gmdate('H:i:s', $nTime) : gmdate('i:s', $nTime);\n $description .= $time . ' ' . $note->note . PHP_EOL;\n }\n }\n\n // Get all private messages.\n $messages = $activity->messages()\n ->where('is_private', 1)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Coaching Chat: ' . PHP_EOL;\n\n foreach ($messages->get() as $message) {\n $description .= $message->participant->name . ': ' . $message->message . PHP_EOL;\n }\n }\n\n // Get all public messages.\n $messages = $activity->messages()\n ->where('is_private', 0)\n ->orderBy('created_at', 'asc');\n\n if ($messages->count() > 0) {\n $description .= PHP_EOL . PHP_EOL . 'Customer Chat: ' . PHP_EOL;\n\n foreach ($messages->get() as $message) {\n $description .= $message->participant->name . ': ' . $message->message . PHP_EOL;\n }\n }\n\n if ($activity->summary) {\n $description .= PHP_EOL . PHP_EOL . 'Summary: ' . PHP_EOL . $activity->summary;\n }\n\n break;\n\n case Activity::TYPE_SMS_INBOUND:\n case Activity::TYPE_SMS_OUTBOUND:\n $description = $activity->description;\n\n break;\n }\n\n return $description;\n }\n\n public function saveFollowupActivity(Activity $activity, array $fields): ?string\n {\n // This is the user provided activity subject field.\n if (empty($fields['type'])) {\n return null;\n }\n\n $reminder = null;\n if (empty($fields['reminder_date']) === false) {\n $formatReminder = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['reminder_date']);\n $reminder = $formatReminder->getTimestamp();\n }\n\n $due = null;\n if (empty($fields['due_date']) === false) {\n $formatDue = Carbon::createFromFormat('Y-m-d\\TH:i:s\\Z', $fields['due_date']);\n $due = $formatDue->getTimestamp();\n }\n\n $data = [\n 'custom_activity_type_id' => $fields['type'],\n 'status' => 'Open',\n 'assignee_id' => $this->profile->crm_provider_id,\n 'due_date' => $due,\n 'details' => $fields['details'] ?? '',\n 'reminder_date' => $reminder,\n 'name' => $fields['name'] ?? 'Follow-up',\n 'related_resource' => $this->convertActivityAssociations($activity),\n 'custom_fields' => $this->fetchCustomFieldData($activity, Field::OBJECT_TASK),\n ];\n\n // We don't actually create a corresponding activity object on our side yet.\n return $this->copperClient->tasks()->create($data)['id'];\n }\n\n /**\n * Store transcripts as note.\n *\n * @throws \\Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // Generate activity transcription.\n $transcriptionData = $this->generateTranscription($activity);\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $transcripts = mb_strimwidth($transcriptionData, 0, static::NOTE_BODY_MAX_LENGTH);\n\n $data = [\n 'user_id' => $this->profile->crm_provider_id,\n 'type' => [\n 'category' => 'user',\n 'id' => 0, // This creates a note.\n ],\n 'activity_date' => time(),\n 'details' => $transcripts,\n 'parent' => $this->convertActivityAssociations($activity),\n ];\n\n $cpActivity = $this->copperClient->activities()->create($data);\n\n // Store CRM Activity ID in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $cpActivity['id'];\n $transcription->save();\n }\n\n /**\n * @inheritdoc\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n if ($crmObject instanceof Lead) {\n $this->requestWithExceptionHandling(\n fn () => $this->copperClient->leads()->update($crmObject->crm_provider_id, [\n 'status_id' => $stage->crm_provider_id,\n ])\n );\n } else {\n $this->copperClient->opportunities()->update($crmObject->crm_provider_id, [\n 'pipeline_stage_id' => $stage->crm_provider_id,\n ]);\n }\n }\n\n public function prepareValueForUpdate(array $params): array\n {\n return [$params['fieldName'] => $params['fieldValue']];\n }\n\n /*\n * @inheritdoc\n */\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $preparedData = $data;\n\n if ($objectType === Field::OBJECT_OPPORTUNITY) {\n $preparedData = $this->prepareOpportunityFieldsForUpdate($data);\n }\n\n try {\n $this->copperClient\n ->createResourceFromObjectType($objectType)\n ->update($objectId, $preparedData)\n ;\n } catch (Exception $e) {\n $this->logger->error(self::RESOURCE_UPDATE_FAILED_ERROR_MESSAGE, [\n 'resource_id' => $objectId,\n 'data' => $preparedData,\n 'error' => $e->getMessage(),\n ]);\n\n throw new CrmException(self::RESOURCE_UPDATE_FAILED_ERROR_MESSAGE, $e->getCode(), $e);\n }\n }\n\n /**\n * @param array<string,string> $fieldData\n *\n * @throws CrmException\n *\n * @return array<string,array<int,array<string,bool|float|int|string|null>>|bool|float|int|string|null>\n */\n private function prepareOpportunityFieldsForUpdate(array $fieldData): array\n {\n $preparedData = [];\n $customFields = [];\n\n foreach ($fieldData as $fieldName => $fieldValue) {\n $field = $this->config\n ->fields()\n ->where('crm_provider_id', $fieldName)\n ->first();\n\n if (! $field instanceof Field) {\n throw new CrmException('Field not found');\n }\n\n $convertedValue = $this->fieldValueConverter->convertToCrm($field->getType(), $fieldValue);\n\n if ($this->isStandardField($fieldName)) {\n $preparedData[$fieldName] = $convertedValue;\n\n continue;\n }\n\n $customFields[] = [\n 'custom_field_definition_id' => $fieldName,\n 'value' => $convertedValue,\n ];\n }\n\n if (! empty($customFields)) {\n $preparedData['custom_fields'] = $customFields;\n }\n\n return $preparedData;\n }\n\n /*\n * @inheritdoc\n */\n public function getRecord(string $objectType, string $objectId, array $fields = []): array\n {\n return $this->copperClient->createResourceFromObjectType($objectType)->find($objectId);\n }\n\n private function fetchCustomFieldData(Activity $activity, string $objectType): array\n {\n $payload = [];\n\n $fieldData = FieldData::where([\n 'object_id' => $activity->id,\n ])->whereHas('field', function ($query) use ($objectType) {\n $query->where('object_type', $objectType);\n })->get();\n\n foreach ($fieldData as $data) {\n // Add the field and value to the payload.\n $payload += [\n 'custom_field_definition_id' => $data->field->crm_provider_id,\n 'value' => $data->value,\n ];\n }\n\n return $payload;\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $baseUrl = 'https://app.prosperworks.com/companies/' . $this->config->crm_provider_id . '/app#/';\n switch ($objectType) {\n case 'lead':\n $url = $baseUrl . 'leads/' . $providerId;\n\n break;\n\n case 'account':\n $url = $baseUrl . 'organization/' . $providerId;\n\n break;\n\n case 'contact':\n $url = $baseUrl . 'contact/' . $providerId;\n\n break;\n\n case 'opportunity':\n $url = $baseUrl . 'deal/' . $providerId;\n\n break;\n\n default:\n case 'task':\n case 'activity':\n // Sadly we can't deeplink to these in Copper UI.\n $url = null;\n }\n\n return $url;\n }\n\n /**\n * Generate transcription for the activity.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! ($this->config->store_transcript)) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n return $this->transcriptionService\n ->findTranscriptionByActivity($activity)\n ->map(static function (array $transcriptionSegment): string {\n return $transcriptionSegment['formattedStartsAt'] . ' | ' . $transcriptionSegment['transcript'];\n })\n ->implode(PHP_EOL);\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n *\n * @return int|string|bool|float|null\n */\n private function extractFieldValue(array $opportunityData, string $fieldName)\n {\n $fieldValue = $this->isStandardField($fieldName)\n ? $opportunityData[$fieldName]\n : $this->resolveCustomFieldFromOpportunityData($opportunityData, $fieldName);\n\n if (is_array($fieldValue)) {\n $fieldValue = implode(', ', $fieldValue);\n }\n\n return $fieldValue;\n }\n\n private function isStandardField(string $fieldName): bool\n {\n return array_key_exists($fieldName, self::STANDARD_OPPORTUNITY_FIELDS);\n }\n\n /**\n * @param array<string, mixed> $opportunityData\n *\n * @return string|int|float|bool|null|array<string, mixed>\n */\n private function resolveCustomFieldFromOpportunityData(array $opportunityData, string $fieldName)\n {\n $fieldData = array_filter(\n $opportunityData['custom_fields'],\n static fn ($field) => (string) $field['custom_field_definition_id'] === $fieldName\n );\n\n return array_pop($fieldData)['value'] ?? '';\n }\n\n private function isSupportedObjectType(string $objectType): bool\n {\n return $objectType !== self::UNSUPPORTED_OBJECT_TYPE;\n }\n\n private function syncStandardFields(): void\n {\n foreach (self::STANDARD_OPPORTUNITY_FIELDS as $fieldId => $fieldData) {\n $this->config->fields()->updateOrCreate([\n 'crm_provider_id' => mb_strimwidth($fieldId, 0, 128),\n 'object_type' => Field::OBJECT_OPPORTUNITY,\n ], [\n 'label' => mb_strimwidth($fieldData['label'], 0, Field::LABEL_MAX_LENGTH),\n 'type' => $fieldData['type'],\n ]);\n }\n\n $this->importStages([Stage::TYPE_OPPORTUNITY]);\n }\n\n private function requestWithExceptionHandling(\\Closure $apiRequest): iterable\n {\n try {\n return $apiRequest();\n } catch (\\Exception $exception) {\n if ($exception->getCode() === 403) {\n // Object might not be supported\n return [];\n }\n\n \\Sentry::captureException($exception);\n\n return [];\n }\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n if ($this->copperClient === null) {\n return false;\n }\n\n $task = $this->copperClient->tasks()->find($crmProviderId);\n\n return ! empty($task);\n } catch (HttpNotFoundException) {\n // Task not found in CRM - this is expected and permanent\n $this->logger->info('[Copper] Task not found during verification', [\n 'task_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n } catch (RequestFailedException $e) {\n // Handle 404 responses from Copper API\n if ($e->getCode() === 404) {\n $this->logger->info('[Copper] Task not found during verification (404)', [\n 'task_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n\n // Re-throw other Copper exceptions for retry\n throw $e;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":true,"is_selected":false,"is_expanded":false}]...
|
8957564869086018857
|
-7959665055215941403
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
11
72
1
4
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Copper;
use Carbon\Carbon;
use Exception;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Facades\Cache;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\CopperInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\FieldValue;
use Jiminny\Models\Crm\LayoutEntity;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Playbook;
use Jiminny\Models\PlaybookCategory;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\UserRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\Copper\Api\Client;
use Jiminny\Services\Crm\Copper\Api\ClientFactory;
use Jiminny\Services\Crm\Copper\Exception\RequestFailedException;
use Jiminny\Services\Crm\Helpers\FilterJoinedParticipants;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Services\Crm\Copper\Traits\SearchesCrmEntities;
use Jiminny\Utils\CurrencyFormatter;
use Jiminny\Utils\StringUtil;
class Service extends BaseService implements
CopperInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
RemoteEntityManipulationInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
use SearchesCrmEntities;
private const int NOTE_BODY_MAX_LENGTH = 3000000;
private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day
private const array STANDARD_OPPORTUNITY_FIELDS = [
'monetary_value' => [
'label' => 'Value',
'available_on' => Field::OBJECT_OPPORTUNITY,
'type' => Field::TYPE_CURRENCY,
],
'pipeline_stage_id' => [
'label' => 'Stage',
'type' => Field::TYPE_PICKLIST,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
'close_date' => [
'label' => 'Close date',
'type' => Field::TYPE_DATE,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
'win_probability' => [
'label' => 'Win probability',
'type' => Field::TYPE_NUMBER,
'available_on' => Field::OBJECT_OPPORTUNITY,
],
];
private const string UNSUPPORTED_OBJECT_TYPE = 'unsupported';
private const string OPPORTUNITY_STATUS_OPEN = 'Open';
private const string OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE = 'Opportunity import failed';
private const string RESOURCE_UPDATE_FAILED_ERROR_MESSAGE = 'Failed to update resource';
private FieldValueConverter $fieldValueConverter;
private ClientFactory $clientFactory;
private ?Client $copperClient = null;
public function __construct(
ClientFactory $clientFactory,
FieldValueConverter $fieldValueConverter,
private readonly UserRepository $userRepository,
private readonly ProspectPhotoPathService $prospectPhotoPathService,
private readonly CrmEntityRepository $crmEntityRepository
) {
parent::__construct();
$this->clientFactory = $clientFactory;
$this->fieldValueConverter = $fieldValueConverter;
}
public function getDisplayName(): string
{
return 'Copper';
}
/**
* Get the CRM entity repository (used by SearchesCrmEntities trait)
*/
protected function getCrmEntityRepository(): CrmEntityRepository
{
return $this->crmEntityRepository;
}
public function getMinimumApiVersion(): string
{
return Client::MIN_API_VERSION;
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_COPPER);
}
public function setUser(User $user): void
{
$this->configureSentryScope($user);
$this->team = $user->getTeam();
$this->teamService->setTeam($user->getTeam());
$this->setConfiguration($user->getTeam()->getCrmConfiguration());
// Reset state.
$this->profile = $user->getProfile();
if (! $this->profile instanceof Profile) {
// Try to fetch their profile, maybe it was not yet imported?
$this->profile = $this->getProfile($user);
}
}
public function setConfiguration(Configuration $configuration): void
{
$this->config = $configuration;
$this->copperClient = $this->clientFactory->create($configuration);
if ($this->team === null) {
$this->team = $configuration->getTeam();
}
}
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return $this->fieldValueConverter->convertFromCrm($fieldType, $fieldValue);
}
private function mapObjectType(string $objectType): string
{
$objectType = strtolower($objectType);
switch ($objectType) {
case Field::OBJECT_TASK:
case Field::OBJECT_OPPORTUNITY:
case Field::OBJECT_LEAD:
$mappedType = $objectType;
break;
case Field::OBJECT_ACCOUNT:
$mappedType = 'company';
break;
case Field::OBJECT_CONTACT:
$mappedType = 'person';
break;
default:
$mappedType = self::UNSUPPORTED_OBJECT_TYPE;
break;
}
return $mappedType;
}
/**
* @param string $crmObject The name of the CRM object. i.e. Opportunity or Contact
*/
protected function getFields(string $crmObject): array
{
$mappedObjectType = $this->mapObjectType($crmObject);
if (! $this->isSupportedObjectType($mappedObjectType)) {
return [];
}
$customFields = $this->copperClient->fields()->all();
$filteredFields = array_filter(
$customFields,
static fn ($field) => in_array($mappedObjectType, $field['available_on'], true)
);
return array_map(
fn (array $property) => [
'name' => $property['id'],
'label' => $property['name'],
'type' => $this->convertFieldType($property['data_type']),
],
$filteredFields
);
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {
$defaultFields = FieldDefinitions::defaultTaskFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
// Setup the activity field as the default Type.
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'type',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldFilters = FieldDefinitions::taskFollowupFieldsFilter();
foreach ($fieldFilters as $data) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
public function syncFields(): void
{
$this->syncStandardFields();
$this->syncCustomFields();
}
public function syncField(Field $field): void
{
if ($field->getCrmProviderId() === 'type') {
/**
* This field is a special case, it is not a custom field and is not returned by the Copper API.
*
* The field is created manually during layout setup.
*
* @see getDefaultFields()
*
* There is a separate endpoint to get the activity types.
* @see importPicklistValues()
*/
return;
}
if ($field->getCrmProviderId() === 'pipeline_stage_id') {
// Not a custom type
return;
}
$crmField = $this->copperClient->fields()->find($field->getCrmProviderId());
$field->label = $crmField['name'];
$field->type = $this->convertFieldType($crmField['data_type']);
$field->save();
}
/**
* @param string $fieldType How the data should be input
*/
private function convertFieldType(string $fieldType): string
{
$fieldType = strtolower($fieldType);
switch ($fieldType) {
case 'dropdown':
$convertedType = Field::TYPE_PICKLIST;
break;
case 'string':
$convertedType = Field::TYPE_TEXT;
break;
case 'float':
case 'percentage':
$convertedType = Field::TYPE_NUMBER;
break;
case 'text':
$convertedType = Field::TYPE_TEXTAREA;
break;
case 'checkbox':
$convertedType = Field::TYPE_BOOLEAN;
break;
case Field::TYPE_DATE:
case Field::TYPE_CURRENCY:
case Field::TYPE_URL:
$convertedType = $fieldType;
break;
default:
$convertedType = Field::TYPE_UNSUPPORTED;
break;
}
return $convertedType;
}
/**
* @inheritdoc
*/
public function importPicklistValues(Field $field): array
{
$fieldValues = [];
if ($field->object_type === 'opportunity' && $field->crm_provider_id === 'pipeline_stage_id') {
return $this->importFieldValuesForDealInsights($field);
}
$values = [];
if ($field->object_type === Field::OBJECT_TASK && $field->crm_provider_id === 'type') {
$activityTypes = $this->copperClient->activityTypes()->all();
/**
* We ignore "system" activity types, disabled activity types and the "Note" activity type.
*/
$activityTypes = array_filter(
$activityTypes['user'],
fn (array $activityType) => ! $activityType['is_disabled'] && $activityType['id'] !== 0
);
// Import all activity values.
$i = 0;
foreach ($activityTypes as $activityType) {
$values[] = [
'value' => $activityType['id'],
'label' => mb_strimwidth($activityType['name'], 0, Field::LABEL_MAX_LENGTH),
'sequence' => $i++,
];
}
} else {
// We just check for the field in the custom definitions.
$crmField = $this->copperClient->fields()->find($field->crm_provider_id);
// Import all values.
foreach ($crmField['options'] as $option) {
$values[] = [
'value' => $option['id'],
'label' => mb_strimwidth($option['name'], 0, 191),
'sequence' => $option['rank'],
];
}
}
// Take the existing set of field values.
$fieldsToPurge = $field->values()->get()->pluck('value')->toArray();
foreach ($values as $value) {
// For all current values, upsert the field.
$value['value'] = substr($value['value'] ?? '', 0, 255);
$fieldValues[] = $field->values()->updateOrCreate([
'value' => $value['value'],
], $value);
// Remove this value from the ones we are going to purge.
$key = array_search($value['value'], $fieldsToPurge, false);
if ($key !== false) {
unset($fieldsToPurge[$key]);
}
}
// Delete the old values that are no longer used.
$field->values()->whereIn('value', $fieldsToPurge)->delete();
return $fieldValues;
}
/**
*
* @return FieldValue[]
*/
private function importFieldValuesForDealInsights(Field $field): array
{
$fieldValues = [];
$pipelines = $this->copperClient->pipelines()->all();
foreach ($pipelines as $pipeline) {
foreach ($pipeline['stages'] as $i => $dealStage) {
$fieldValues[] = $field->values()->updateOrCreate(
['value' => $dealStage['id']],
[
'label' => $dealStage['name'],
'sequence' => $i,
]
);
}
}
return $fieldValues;
}
/**
* @inheritdoc
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
if ($types === null) {
$types = [Stage::TYPE_LEAD, Stage::TYPE_OPPORTUNITY];
}
$missingStage = null;
foreach ($types as $type) {
if ($type === Stage::TYPE_LEAD) {
$statuses = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leadStatuses()->all()
);
if (count($statuses) > 0) {
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => BusinessProcess::TYPE_LEAD,
], [
'team_id' => $this->team->id,
'name' => BusinessProcess::TYPE_LEAD,
'type' => BusinessProcess::TYPE_LEAD,
'is_selectable' => true,
]);
// A record type is really a clone of the business process, used to store which record uses which pipeline.
$this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => BusinessProcess::TYPE_LEAD,
], [
'team_id' => $this->team->id,
'name' => BusinessProcess::TYPE_LEAD,
'is_selectable' => true,
'business_process_id' => $businessProcess->id ?? null,
]);
$leadStatuses = [];
foreach ($statuses as $status) {
// Upsert all statuses for the team.
$status = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $status['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($status['name'], 0, 50),
'label' => mb_strimwidth($status['name'], 0, 191),
'type' => Stage::TYPE_LEAD,
'sequence' => $status['order'],
'is_selectable' => true,
]);
if ($missingStageName && $missingStageName === $status['id']) {
$missingStage = $status;
}
$leadStatuses[] = $status['id'];
}
$businessProcess->stages()->sync($leadStatuses);
}
} else {
// We create a business process to contain the pipeline, and later store all stages against it.
foreach ($this->copperClient->pipelines()->all() as $pipeline) {
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => $pipeline['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($pipeline['name'], 0, 150),
'type' => BusinessProcess::TYPE_OPPORTUNITY,
'is_selectable' => true,
]);
// A record type is really a clone of the business process, used to store which record uses which pipeline.
$this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => $pipeline['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($pipeline['name'], 0, 150),
'is_selectable' => true,
'business_process_id' => $businessProcess->id ?? null,
]);
$stages = [];
foreach ($pipeline['stages'] as $i => $dealStage) {
// Upsert all stages for the team.
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $dealStage['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($dealStage['name'], 0, 50),
'label' => mb_strimwidth($dealStage['name'], 0, 191),
'type' => Stage::TYPE_OPPORTUNITY,
'sequence' => $i,
'is_selectable' => true,
'probability' => $dealStage['win_probability'],
]);
if ($missingStageName && $missingStageName === $dealStage['id']) {
$missingStage = $stage;
}
$stages[] = $stage['id'];
}
$businessProcess->stages()->sync($stages);
}
}
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncLeads(Carbon $since, ?Carbon $to = null, ?string $crmProfileId = null): int
{
$syncCount = 0;
$cpLeads = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->paginate([
'minimum_modified_date' => $since->timestamp,
'sort_by' => 'date_modified',
])
);
foreach ($cpLeads as $cpLead) {
// Only sync if previously imported.
if ($this->hasLead($cpLead['id']) === false) {
$this->importLead($cpLead);
$syncCount++;
}
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncLead(string $crmId): ?Lead
{
$cpLead = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->find($crmId)
);
if (\count($cpLead) === 0) {
return null;
}
return $this->importLead($cpLead);
}
/**
* @inheritdoc
*/
private function importLead($crmData): ?Lead
{
$countryCode = null;
if (! empty($crmData['address']) && isset($crmData['address']['country'])) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$mobilePhone = $parsedNumber = null;
if (! empty($crmData['phone_numbers'])) {
foreach ($crmData['phone_numbers'] as $phoneNumber) {
if ($phoneNumber['category'] === 'mobile') {
$mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);
} else {
$parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);
}
}
}
$name = $crmData['name'];
if (empty($crmData['company_name'])) {
$company = 'Unknown';
} else {
$company = mb_strimwidth($crmData['company_name'], 0, 191);
}
$domain = null;
if (empty($crmData['websites']) === false) {
$domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$email = null;
if (empty($crmData['email']) === false) {
$email = mb_strimwidth($crmData['email']['email'], 0, 80);
}
$stage = $this->config
->stages()
->where('crm_provider_id', (string) $crmData['status_id'])
->where('type', Stage::TYPE_LEAD)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_LEAD], $crmData['status_id']);
}
if (! $stage instanceof Stage) {
return null;
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($name, 0, 191),
'company' => $company,
'domain' => $domain,
'title' => $crmData['title'] ? mb_strimwidth($crmData['title'], 0, 128) : null,
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'mobile_phone' => $mobilePhone,
'stage_id' => $stage->id,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Lead::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'country_code' => $countryCode,
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->leads()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
/**
* @inheritdoc
*/
public function syncAccounts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$cpAccounts = $this->copperClient->accounts()->paginate([
'minimum_modified_date' => $since->timestamp,
'sort_by' => 'date_modified',
]);
foreach ($cpAccounts as $cpAccount) {
// Only sync if previously imported.
if ($this->hasAccount($cpAccount['id'])) {
$this->importAccount($cpAccount);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncAccount(string $crmId): ?Account
{
$cpAccount = $this->copperClient->accounts()->find($crmId);
if (empty($cpAccount)) {
return null;
}
return $this->importAccount($cpAccount);
}
/**
* @inheritdoc
*/
private function importAccount($crmData): Account
{
$countryCode = null;
if (empty($crmData['address']) === false && $crmData['address']['country']) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$name = $crmData['name'];
$parsedNumber = null;
foreach ($crmData['phone_numbers'] as $phoneNumber) {
$parsedNumber = parsePhoneNumber($countryCode, $phoneNumber['number']);
}
$domain = null;
if (empty($crmData['websites']) === false) {
$domain = mb_strimwidth($crmData['websites'][0]['url'], 0, 191);
$domain = StringUtil::resolveDomain($domain);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($name, 0, 191),
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Account::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'country_code' => $countryCode,
'domain' => $domain,
'phone' => $parsedNumber['phone'] ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->accounts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->copperClient,
]);
$strategies = $strategyResolver->getStrategies($this->config, $strategy);
$syncCount = 0;
try {
foreach ($strategies as $syncStrategy) {
foreach ($syncStrategy->fetchOpportunities($parameters) as $opportunityData) {
$this->importOpportunity($opportunityData);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
$this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => $exception->getMessage(),
]);
}
return $syncCount;
}
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->copperClient,
]);
$strategy = $strategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY
);
$parameters['crm_id'] = $crmId;
$cpOpportunity = $strategy->fetchOpportunities($parameters);
return $this->importOpportunity($cpOpportunity);
}
private function importOpportunity($crmData): ?Opportunity
{
$companyId = (string) $crmData['company_id'];
if (empty($companyId)) {
$this->logger->error(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => 'No company id',
]);
return null;
}
$account = $this->config->accounts()->where('crm_provider_id', $companyId)->first();
if ($account === null) {
$account = $this->syncAccount($companyId);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', (string) $crmData['pipeline_id'])
->first();
if ($businessProcess === null) {
// It is possible for some deals to not be in a pipeline.
$this->logger->warning(self::OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE, [
'error' => 'Missing pipeline',
]);
return null;
}
$stage = $businessProcess
->stages()
->where('crm_provider_id', (string) $crmData['pipeline_stage_id'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
$this->logger->info('Stage not found, importing', [
'pipeline_id' => $crmData['pipeline_id'],
'stage_id' => $crmData['pipeline_stage_id'],
]);
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $crmData['pipeline_stage_id']);
}
$recordType = $businessProcess->recordTypes()->first();
$closeDate = null;
$isClosed = $crmData['status'] !== self::OPPORTUNITY_STATUS_OPEN;
if ($crmData['close_date']) {
$closeDate = Carbon::parse($crmData['close_date'])->format('Y-m-d');
}
$data = [
'team_id' => $this->team->getId(),
'account_id' => $account->id,
'user_id' => $profile->user_id ?? null,
'owner_id' => $crmData['assignee_id'],
'name' => mb_strimwidth($crmData['name'], 0, 128),
'value' => $crmData['monetary_value'],
'currency_code' => CurrencyFormatter::formatCode($crmData['monetary_unit']),
'close_date' => $closeDate,
'is_closed' => $isClosed,
'is_won' => $crmData['status'] === 'Won',
'stage_id' => $stage->id,
'record_type_id' => $recordType->id ?? null,
'remotely_created_at' => $crmData['date_created'],
];
/** @var Opportunity $opportunity */
$opportunity = $this->config
->opportunities()
->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data)
;
// import external fields into crm_field_data if present
$dealInsightsFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData($crmData, $dealInsightsFields, $opportunity->id);
return $opportunity;
}
/**
* @param array<string, mixed> $opportunityData
* @param string[] $dealInsightsFields
*/
public function importOpportunityCrmFieldData(
array $opportunityData,
array $dealInsightsFields,
int $opportunityId
): void {
foreach ($dealInsightsFields as $fieldName) {
$field = $this->config->fields()->with('entities')
->where('crm_provider_id', $fieldName)
->where('object_type', Field::OBJECT_OPPORTUNITY)
->first();
if (! $field instanceof Field) {
$this->logger->warning('Field not found', [
'field' => $fieldName,
'opportunity_id' => $opportunityId,
]);
continue;
}
$entity = $field->getEntities()->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$fieldValue = $this->extractFieldValue($opportunityData, $fieldName);
$normalizedValue = $this->normalizeValue($field->getType(), (string) $fieldValue, true);
$field->data()
->updateOrCreate([
'crm_layout_entity_id' => $entity->id,
'crm_field_id' => $field->id,
'object_type' => 'opportunity',
'object_id' => $opportunityId,
], ['value' => $normalizedValue])
;
}
}
/**
* @inheritdoc
*/
public function syncContacts(Carbon $since, ?Carbon $to = null): int
{
$syncCount = 0;
try {
$cpContacts = $this->copperClient->contacts()->paginate([
'minimum_interaction_date' => $since->timestamp,
'sort_by' => 'date_modified',
]);
foreach ($cpContacts as $cpContact) {
// Only sync if previously imported.
if ($this->hasContact($cpContact['id'])) {
$this->importContact($cpContact);
$syncCount++;
}
}
} catch (\Exception $exception) {
// Do nothing for now.
throw $exception;
}
return $syncCount;
}
/**
* @inheritdoc
*/
public function syncContact(string $crmId): ?Contact
{
$cpContact = $this->copperClient->contacts()->find($crmId);
if (empty($cpContact)) {
return null;
}
return $this->importContact($cpContact);
}
/**
* @inheritdoc
*/
private function importContact($crmData): Contact
{
$account = null;
if ($crmData['company_id']) {
$account = $this->team
->crm
->accounts()
->where('crm_provider_id', (string) $crmData['company_id'])
->first();
if ($account === null) {
$account = $this->syncAccount($crmData['company_id']);
}
}
$countryCode = null;
if (empty($crmData['address']) === false && $crmData['address']['country']) {
$countryCode = $this->convertCountryNameToCode($crmData['address']['country']);
}
$mobilePhone = $parsedNumber = null;
foreach ($crmData['phone_numbers'] as $phoneNumber) {
if ($phoneNumber['category'] === 'mobile') {
$mobilePhone = $this->buildContactMobilePhone($countryCode, $phoneNumber['number']);
} else {
$parsedNumber = $this->buildContactPhone($countryCode, $phoneNumber['number']);
}
}
$email = null;
if (empty($crmData['emails']) === false) {
$email = mb_strimwidth($crmData['emails'][0]['email'], 0, 80);
}
$profile = $this->config->profiles()->where('crm_provider_id', (string) $crmData['assignee_id'])->first();
$data = [
'team_id' => $this->team->id,
'account_id' => $account->id ?? null,
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $crmData['assignee_id'],
'name' => $crmData['name'],
'email' => $email,
'phone' => $parsedNumber['phone'] ?? null,
'mobile_phone' => $mobilePhone ?? null,
'ext' => $parsedNumber['ext'] ?? null,
'title' => $crmData['title'],
'country_code' => $countryCode,
'photo_path' => $this->prospectPhotoPathService->getOrGeneratePhotoPath(
crmConfiguration: $this->config,
crmProviderId: $crmData['id'],
modelType: Contact::class,
fileName: $crmData['id'],
avatarText: $crmData['name']
),
'remotely_created_at' => $crmData['date_created'],
];
return $this->config->contacts()->updateOrCreate(['crm_provider_id' => (string) $crmData['id']], $data);
}
private function buildContactPhone(?string $countryCode, ?string $number): ?array
{
if ($number) {
// Trim to our width and attempt to parse it.
$number = mb_strimwidth($number, 0, 25);
$parsedNumber = parsePhoneNumber($countryCode, $number);
} else {
$parsedNumber = [];
}
return $parsedNumber;
}
private function buildContactMobilePhone(?string $countryCode, ?string $number): ?string
{
return $number ? mb_strimwidth(phone_e164($countryCode, $number), 0, 25) : null;
}
/**
* @inheritdoc
*/
public function syncOrganization(): void
{
$organization = $this->copperClient->organisation()->all();
if ($this->config->crm_provider_id !== $organization['id']) {
$this->config->update(['crm_provider_id' => $organization['id']]);
}
}
private function syncCustomFields(): void
{
foreach ($this->getFieldTypes() as $fieldType) {
$currentFields = $this->getFields($fieldType);
foreach ($currentFields as $field) {
/** @var Field $field */
$field = $this->config->fields()->updateOrCreate([
'crm_provider_id' => $field['name'],
'object_type' => $fieldType,
], [
'label' => mb_strimwidth($field['label'], 0, Field::LABEL_MAX_LENGTH),
'type' => $field['type'],
]);
if ($field->getType() === Field::TYPE_PICKLIST) {
$this->importPicklistValues($field);
}
}
}
$this->config->save();
}
protected function getFieldTypes(): array
{
return [
parent::OBJECT_TASK,
parent::OBJECT_LEAD,
parent::OBJECT_ACCOUNT,
parent::OBJECT_CONTACT,
parent::OBJECT_OPPORTUNITY,
];
}
/**
* @inheritdoc
*/
public function syncProfiles(?User $userToSearch = null): ?Profile
{
$profiles = $this->copperClient->users()->all();
foreach ($profiles as $profile) {
$user = $this->userRepository->findByTeamAndEmailAddress($this->team, $profile['email'], onlyActive: true);
// Only import profiles for users we have locally.
if ($user) {
$profile = $user->crmProfile()->updateOrCreate([
'crm_configuration_id' => $this->config->id,
'crm_provider_id' => $profile['id'],
]);
if ($userToSearch && $userToSearch->id === $user->id) {
return $profile;
}
}
}
return null;
}
/**
* @inheritdoc
*/
public function syncProfileFields(): void
{
$fieldTypes = [
'task',
'lead',
'account',
'contact',
'opportunity',
];
foreach ($fieldTypes as $fieldType) {
try {
$currentFields = $this->getFields(ucfirst($fieldType));
$newFields = array_column($currentFields, 'name');
$changedFields = array_merge(
array_diff($this->profile->getFieldsAsArray($fieldType), $newFields),
array_diff($newFields, $this->profile->getFieldsAsArray($fieldType))
);
if (\count($changedFields) > 0) {
$fields = implode(',', $newFields);
$this->logger->debug(
ucfirst($fieldType)
. ' fields changed from '
. $this->profile->{$fieldType . '_fields'}
. ' to: '
. $fields
);
$this->profile->{$fieldType . '_fields'} = $fields;
}
} catch (\Exception $exception) {
$this->logger->error('No access to ' . $fieldType . ' object, skipping...');
continue;
}
}
$this->profile->save();
}
/**
* @inheritdoc
*/
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
$scopeValues = array_map(fn ($scope) => is_string($scope) ? $scope : $scope->value, $scopes);
$cacheKey = sprintf('copper-search-%d-%s-%s-%d-%d', $this->team->id, $name, implode('-', $scopeValues), $count, $offset);
return Cache::remember($cacheKey, 300, function () use ($name, $scopes, $count, $offset) {
// Try local search first
$localResults = $this->searchLocally($name, $scopes, $count, $offset);
// If no local results, fall back to remote API search
if (empty($localResults)) {
return $this->searchRemotely($name, $scopes, $count, $offset);
}
return $localResults;
});
}
/**
* @inheritdoc
*/
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
$contact = null;
$account = null;
if ($crmAccountId) {
$account = $this->config->accounts()->where('crm_provider_id', $crmAccountId)->first();
if ($account === null) {
$account = $this->syncAccount($crmAccountId);
}
}
if ($crmContactId) {
$contact = $this->config->contacts()->where('crm_provider_id', $crmContactId)->first();
if ($contact === null) {
$contact = $this->syncContact($crmContactId);
}
}
if ($contact || $account) {
if ($contact && $account === null) {
$account = $contact->account;
}
if ($account === null) {
return [];
}
$params = [
'company_ids' => [$account->crm_provider_id],
'status_ids' => [0], // The integer values are 0, 1, 2, 3, for "Open", "Won", "Lost", and "Abandoned".
'sort_by' => 'date_modified',
'sort_direction' => 'desc',
];
switch ($this->config->opportunity_assignment_rule) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$params['sort_by'] = 'date_modified';
$params['sort_direction'] = 'desc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$params['sort_by'] = 'date_created';
$params['sort_direction'] = 'desc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$params['sort_by'] = 'date_created';
$params['sort_direction'] = 'asc';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
$params['sort_by'] = 'date_modified';
$params['sort_direction'] = 'desc';
$params['status_ids'] = [0, 1, 2, 3];
}
$cpOpportunities = $this->copperClient->opportunities()->search($params);
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
foreach ($cpOpportunities as $cpOpportunity) {
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', (string) $cpOpportunity['pipeline_id'])
->first();
if ($businessProcess === null) {
// Import it.
$businessProcess = $this->importStages(
[Stage::TYPE_OPPORTUNITY],
$cpOpportunity['pipeline_stage_id']
);
}
$stage = $businessProcess
->stages()
->where('crm_provider_id', (string) $cpOpportunity['pipeline_stage_id'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $cpOpportunity['pipeline_stage_id']);
}
$recordType = $businessProcess->recordTypes()->first();
$record = [
'crmId' => $cpOpportunity['id'],
'name' => $cpOpportunity['name'],
'value' => currency_format($cpOpportunity['monetary_value'], $cpOpportunity['monetary_unit']),
'won' => $cpOpportunity['status'] === 'Won',
'stage' => [
'id' => $stage->id_string,
'name' => $stage->name,
],
'recordType' => [
'id' => $recordType->id_string,
'name' => $recordType->name,
],
];
if ($ownerId && isset($cpOpportunity['assignee_id']) && $cpOpportunity['assignee_id'] === $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
/**
* @inheritdoc
*/
public function getTasks(string $objectType, string $objectId, ?string $opportunityId): array
{
$data = $cpTasks = [];
switch ($objectType) {
case 'lead':
$cpTasks = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->relatedTasks($objectId)
);
break;
case 'account':
$cpTasks = $this->copperClient->accounts()->relatedTasks($objectId);
break;
case 'contact':
if ($opportunityId) {
$cpTasks = $this->copperClient->opportunities()->relatedTasks($opportunityId);
} elseif ($objectType === 'contact') {
$cpTasks = $this->copperClient->contacts()->relatedTasks($objectId);
}
break;
}
foreach ($cpTasks as $cpTask) {
// We only get the ID itself returned, so pull out the full object.
try {
$cpTask = $this->copperClient->tasks()->find($cpTask['id']);
} catch (Exception $exception) {
$this->logger->error('[Copper] Error fetching task', [
'resource_id' => $cpTask['id'],
'error' => $exception->getMessage(),
]);
continue;
}
// Only allow open tasks.
if ($cpTask['status'] === 'Open') {
$data[] = [
'crmId' => $cpTask['id'],
'subject' => $cpTask['name'],
'due' => $cpTask['due_date']
? Carbon::createFromTimestamp($cpTask['due_date'])->format('Y-m-d\TH:i:sO')
: null,
'type' => null,
];
}
}
return $data;
}
/**
* Try to find email address in CRM service
*
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchExactlyByEmail(string $email, ?int $userId = null): ?array
{
$cpObjectType = 'contact';
$cpObjects = $this->copperClient->contacts()->search([
'emails' => $email,
'sort_by' => 'date_modified',
'sort_direction' => 'desc',
]);
if (empty($cpObjects)) {
$cpObjectType = 'lead';
$cpObjects = $this->requestWithExceptionHandling(
fn () => $this->copperClient->leads()->search([
'emails' => ...
|
45357
|
NULL
|
NULL
|
NULL
|
|
45356
|
1626
|
8
|
2026-05-14T14:32:37.929047+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769157929_m2.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pm~ (Q SearchDate ModifiedYesterdav at 13.36Yesterday at 13:35Yesterday at 13.34Yesterday at 13:34Yesterday at 13:33resterday at 15.5sYesterdav at 13:37Yesterday at 13:32Yesterday at 13.31Yesterday at 13:30Yesterday at 13:30resterday at 15.4gYesterdav at 13:29Yesterday at 13:28Yesterday at 13:28Yesterday at 13:27Yesterday at 13:27resterday at 13.-40Yesterdav at 13:25Yesterday at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13:23Yesterday at 13.21Yesterdav at 13:21Yesterday at 13:20Yesterday at 13:20Yesterday at 13:19Yesterday at 13:19Yesterday at 13.18Vecterdav at 12:17Yesterday at 13:16Yesterdav at 13:16Yesterday at 13:15Yesterday at 13:14Yecterdav at 12:1/Yesterday at 13:13Yesterday at 13.13Yecterdav at 12:12Yesterday at 13:12Yesterday at 13:11Yesterday at 13:10Yesterday at 13:10Yesterday at 13.09Yecterdav at 12:091Yesterday at 13:08Yesterdav at 13:07MPEG-4 movie13 KBMPEG-4 movie16 KB1/ Kb29 KBMPEG-4 movieMPEG-4 movie6 KB12 KBMPE0"4 movie9 K:7 KBMPEG-4 movie8 KB37 KBMP2G-4 movie10 KBMPEG-4 movie7 KBMPEG"4 movie9K:8KBMPEG-4 movie72 KB14 K8|13 KRIMPEG-4 movieMPEG-4 movie9 KB18 KBMPEG-4 movie12 KEMPEG-4 movie10 KBMPEG-4 movie16 KB6 KB1MPEG-4 movie6 KBMPEG-4 movie12 KB23 KBMPEG-4 movie8 KEMPEG-4 movie6 KBMPEG-4 movie6 KBMPEG-4 movie11 K:MPEG-4 movie11 KBMPEG-4 movie34 KBMPEG-4 movie10 KPMPEG-4 movie7 KBMPEG-4 movie5 KBMPEG-4 movie11 KBIMPEG-4 movie26 KBMPEG-4 movie111 KB102 KBRR KRMPEG-4 movieMDEG-A movie59 KB98 KBMPEG-4 movie07 K:MPEG-A movie66 KB MPEG-4 movie44 KB93 KB79 KpMPEG-4 movieMPEG-4 movie58 KBMPEG-4 movie27 KP7 KBMPEG-4 movie12 KB32 K8MPEG-4 movieAl Notes: OffLeave• 0FavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВ148 KB122 KB111 KB94 KBZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageJPEG imageJPEG imageColdo1 of 58 selected, 8.5 GB availab!i• Inu 14 Mаy 1/.32.31Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
-4849588242053115545
|
NULL
|
click
|
ocr
|
NULL
|
ActivityFilesLaterJiminny... ~@ jiminny-x-integrat ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pm~ (Q SearchDate ModifiedYesterdav at 13.36Yesterday at 13:35Yesterday at 13.34Yesterday at 13:34Yesterday at 13:33resterday at 15.5sYesterdav at 13:37Yesterday at 13:32Yesterday at 13.31Yesterday at 13:30Yesterday at 13:30resterday at 15.4gYesterdav at 13:29Yesterday at 13:28Yesterday at 13:28Yesterday at 13:27Yesterday at 13:27resterday at 13.-40Yesterdav at 13:25Yesterday at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13:23Yesterday at 13.21Yesterdav at 13:21Yesterday at 13:20Yesterday at 13:20Yesterday at 13:19Yesterday at 13:19Yesterday at 13.18Vecterdav at 12:17Yesterday at 13:16Yesterdav at 13:16Yesterday at 13:15Yesterday at 13:14Yecterdav at 12:1/Yesterday at 13:13Yesterday at 13.13Yecterdav at 12:12Yesterday at 13:12Yesterday at 13:11Yesterday at 13:10Yesterday at 13:10Yesterday at 13.09Yecterdav at 12:091Yesterday at 13:08Yesterdav at 13:07MPEG-4 movie13 KBMPEG-4 movie16 KB1/ Kb29 KBMPEG-4 movieMPEG-4 movie6 KB12 KBMPE0"4 movie9 K:7 KBMPEG-4 movie8 KB37 KBMP2G-4 movie10 KBMPEG-4 movie7 KBMPEG"4 movie9K:8KBMPEG-4 movie72 KB14 K8|13 KRIMPEG-4 movieMPEG-4 movie9 KB18 KBMPEG-4 movie12 KEMPEG-4 movie10 KBMPEG-4 movie16 KB6 KB1MPEG-4 movie6 KBMPEG-4 movie12 KB23 KBMPEG-4 movie8 KEMPEG-4 movie6 KBMPEG-4 movie6 KBMPEG-4 movie11 K:MPEG-4 movie11 KBMPEG-4 movie34 KBMPEG-4 movie10 KPMPEG-4 movie7 KBMPEG-4 movie5 KBMPEG-4 movie11 KBIMPEG-4 movie26 KBMPEG-4 movie111 KB102 KBRR KRMPEG-4 movieMDEG-A movie59 KB98 KBMPEG-4 movie07 K:MPEG-A movie66 KB MPEG-4 movie44 KB93 KB79 KpMPEG-4 movieMPEG-4 movie58 KBMPEG-4 movie27 KP7 KBMPEG-4 movie12 KB32 K8MPEG-4 movieAl Notes: OffLeave• 0FavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВ148 KB122 KB111 KB94 KBZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageJPEG imageJPEG imageColdo1 of 58 selected, 8.5 GB availab!i• Inu 14 Mаy 1/.32.31Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
45354
|
NULL
|
NULL
|
NULL
|
|
45355
|
1625
|
14
|
2026-05-14T14:32:36.655804+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769156655_m1.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
8043719072324535154
|
-8628527368849355612
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
PhpStormFileEditViewNavig Project: faVsco.js, menu
PhpStormFileEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelp•FV faVsco.jsv* #12066 on JY-20725-handle-HS-search-rate-limit k vabl19HandleHubspotRateLimitTest100% C8• Thu 14 May 17:32:36* :QProject v= custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php© FieldDefinitions.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php=laravel.log© FieldValueConverter.php• DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.php© Service.php© DecorateActivity.phpSF [jiminny@localhost]© StandardFieldMetadata.php© Salesforce/Service.php© LogActivityTrait.phpPipedrive/Service.phpClose/Service.phpCopper/Service.php XA HS_local [jiminny@localho:Wv D Copper© PlainTextDecorateActivity.phpT ActivityPlaybookTrait.php© CrmHelperRepository.phpAccountController.php4 console [QAI PROD] X18> D Api› D ExceptionT IntegrationAppTrait.php.env.stagingE.env© DetachActivityObject.phpRematchActivityOnCrmObjectDetach.php4 console [PROD]> C OpportunitySyncStrategy© MatchActivityCrmData.php© Client.php© HubspotPaginationService.php© HandleHubspotRateLimit.phpA console (EU]> D ProspectSearchStrategy52class Service extends BaseService implementsA5 A 36DGojiminny v> CJ Traits© FieldDefinitions.php1662* Othrows CrmException084143 ×4 л© FieldValueConverter.php1663*/215|•m_layout_id =© Service.php1 usage2162,1661,66799,66> D CrmObjects1664private function buildCallPayload(Activity $activity): Activity217v DecorateActivity1665218© BaseDecorateActivity.php1666try{219id = 33;© PlainTextDecorateActivity.pl1667if (Sactivity->crm_provider_id) {=220-221> D Dummy1668// The activity should be logged under the existing Task (not Activity).v Helpers1669$newActivityType = $this->getChmType($activity->category);=222T ActivityPlaybookTrait.php1670if ($newActivityType === null) {=223© Arraylterator.php1671Smessage = sprintf( format: '[Copper] invalid CRM Custom Activity Type: %s', $activity->cat 224id THEN '(own• ConnectionStateTrait.php1672=225© CrmHelperRepository.php1673throw new CrmException(Smessage,code: 400):226© FilterJoinedParticipants.php1674— 227* OpportunitySyncableFieldsT1675$this->copperClient->tasks()->update($activity->crm_provider_id, [228v C Hubspot1676'status'= 'Completed',229• AccountSyncStrategy1677'custom_activity_type_id' => $newActivityType->value,= 230hubspat':> @ Actions|1678'details' => $this->generateActivityDescription($activity),• ContactSyncStrategy[23.16791):1232> ODTO1680j else {233 V= 11512582;› Fields1681if (Sthis-~getCrmType(SactivitX-scategocx)minulln234> • Journal1682$message = sprintf( format:'[Copper] Invalid CRM Activity Type: %s', $activity->category->-D Metadata1683v D OpportunitySyncStrategy1684throw new CrmException($message,code: 400);› D Concerns1685=A Unhonntl actlAndifiaNDur 1686Workspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)W Windsurf Teams1669:47UTF-8Ca 4 spaces...
|
45353
|
NULL
|
NULL
|
NULL
|
|
45354
|
1626
|
7
|
2026-05-14T14:32:34.096934+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769154096_m2.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
2
33...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.66456115,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.67586434,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.6871675,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.7150931,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.72639626,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"bounds":{"left":0.73769945,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Sync Changes","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide This Notification","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Code changed:","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.042220745,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.27027926,"top":1.0,"width":0.008643617,"height":0.0},"on_screen":false,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"2","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"33","depth":4,"on_screen":true,"role_description":"text"}]...
|
-9194673704168071041
|
-7555842213617218742
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
2
33
ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pm~ (Q SearchDate ModifiedYesterdav at 13.36Yesterday at 13:35Yesterday at 13.34Yesterday at 13:34Yesterday at 13:33resterday at 15.5sYesterdav at 13:37Yesterday at 13:32Yesterday ar 13.31Yesterday at 13:30Yesterday at 13:30resterday at 15.4gYesterdav at 13:29Yesterday at 13:28Yesterday at 13:28Yesterday at 13:27Yesterday at 13:27resterday at 13-40Yesterdav at 13:25Yesterday at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13:23Yesterday at 13.21Yesterdav at 13:21Yesterday at 13:20Yesterday at 13:20Yesterday at 13:19Yesterday at 13:19Yesterday at 13.18Vecterdav at 12:17Yesterday at 13:16Yesterdav at 13:16Yesterday at 13:15Yesterday at 13:14Yecterdav at 12:1/Yesterday at 13:13Yesterday at 13.13Yecterdav at 12:12Yesterday at 13:12Yesterday at 13:11Yesterday at 13:10Yesterday at 13:10Yesterday at 13.09Yecterdav at 12:091Yesterday at 13:08Yesterdav at 13:07MPEG-4 movie13 KBMPEG-4 movie16 KB1/ Kb29 KBMPEG-4 movieMPEG-4 movie6 KB12 KBMPE0"4 movie9 K:7 KBMPEG-4 movie8 KB37 KBMP2G-4 movie10 KBMPEG-4 movie7 KBMPEG"4 movie9K:8KBMPEG-4 movie72 KB14 K8|13 KRIMPEG-4 movieMPEG-4 movie9 KB18 KBMPEG-4 movie12 KEMPEG-4 movie10 KBMPEG-4 movie16 KB6 KB1MPEG-4 movie6 KBMPEG-4 movie12 KB23 KBMPEG-4 movie8 KEMPEG-4 movie6 KBMPEG-4 movie6 KBMPEG-4 movie11 K:MPEG-4 movie11 KBMPEG-4 movie34 KBMPEG-4 movie10 KPMPEG-4 movie7 KBMPEG-4 movie5 KBMPEG-4 movie11 KBIMPEG-4 movie26 KBMPEG-4 movie111 KB102 KBRR KRMPEG-4 movieMDEG-A movie59 KB98 KBMPEG-4 movie07 K:MPEG-A movie66 KB MPEG-4 movie44 KB93 KB79 KpMPEG-4 movieMPEG-4 movie58 KBMPEG-4 movie27 KP7 KBMPEG-4 movie12 KB32 K8MPEG-4 movieAl Notes: OffLeave• 0FavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВ148 KB122 KB111 KB94 KBZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.51 G8 availabld• Inu 14 Mаy 1/•32.32Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
45352
|
1626
|
6
|
2026-05-14T14:32:28.831014+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769148831_m2.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.2962101,"top":1.0,"width":0.03856383,"height":-0.019952059},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.33477393,"top":1.0,"width":0.122340426,"height":-0.019952059},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.5731383,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"HandleHubspotRateLimitTest","depth":6,"bounds":{"left":0.5884308,"top":1.0,"width":0.076130316,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.66456115,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'HandleHubspotRateLimitTest'","depth":6,"bounds":{"left":0.67586434,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"bounds":{"left":0.6871675,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"bounds":{"left":0.7150931,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"bounds":{"left":0.72639626,"top":1.0,"width":0.011303191,"height":-0.019952059},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
1160075880258684949
|
-8349599981661484599
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
Start Listening for PHP Debug Connections
HandleHubspotRateLimitTest
Run 'HandleHubspotRateLimitTest'
Debug 'HandleHubspotRateLimitTest'
More Actions
JetBrains AI
Search Everywhere
ActivityFilesLaterJiminny... ~@ jiminny-x-integrati& platform-inner-team© Channels# ai-chapter# alertsi backend# bugscontusion-cllnia# curiosity_lab# engineering# general# jiminny-bg# platform-tickets# product_launches# random# releases# sofia-office# support# thank-yous# the people of iimi..• Direct messages8. A...• A3 62P. Galya Dimitrova Mvasil VasilevA. Stefka Stoyanova%: Todor Stamatovf. Mario GeorgievP. Nikolay Ivanov2o James Graham "2. Stoyan Tanev. Steliyan Georgiev. Petko Kashinski*. Lukas Kovali...a: Apps® ToastS lira Gloud6 Huddle with Aneliya Angelova& R. Aneliya Angelova •• Messagest Add canvasur FilesAneliya Angelova 2:30 PMЛукаш, само при Сейлсфорс и Хубспот се синкваха активити типовете, когато се направи плейбук,нали?пои останалите скМі тоябва оъчно ла се въвелат.Lukas Kovalik 2:47 PMтряова да се за всички, някьде не се ли попьлвапри зохо май беше hardcoded но май и там си връщаха две категорииAneliya Angelova @ 4:00 PMЛукаш имаш ли време да се чуем за тестването на https://jiminny.atlassian.net/browse/JY-20725X Preview insackt[HubSpot] Optimise CRM rematctC OpenReady for QA- MediumAA Aneliya AngelovaAs of today at 4:00 PM RetreshOpen in Jira+ SummariseLukas Kovalik 4:02 PMzean-iurwiniareelYou joined the huddle LIVE 4:06 PMAneliva Angelova is here toolAneliya Angelova 4:44 PM11512582Lukas Kovalik O 5:16 PMcurl --location "httns:ani.hubani.com/crm/v3/obiects/contacts/search--header 'Content-Type: application/json'\--header "Authorization: BearerC|Kvma?iMx7OINOM8kOFwrAowAcAkUAhIR24?A05D?xiVrIYMILuP6SA01Kwcmhr=n.v2 hytorDniMvDalYck-CMalovolNOM9kOFwrAUAcrkcaws-ThwRARIRAOF-ATFSAOFRAO-ROIEBAQUBEggBAQEBAYICFIґ7Au8O2Nwal9YW2CbCCxYvwngmSgNldTFSAFoAYABoAHAAeAA'\--data "{ "limit", 13'Message Aneliva Angelova+ AaIđ 0Pm~ (Q SearchDate ModifiedYesterdav at 13.36Yesterday at 13:35Yesterday at 13.34Yesterday at 13:34Yesterday at 13:33resterday at 15.5sYesterdav at 13:37Yesterday at 13:32Yesterday ar 13.31Yesterday at 13:30Yesterday at 13:30resterday at 15.4gYesterdav at 13:29Yesterday at 13:28Yesterday at 13:28Yesterday at 13:27Yesterday at 13:27resterday at 13-40Yesterdav at 13:25Yesterday at 13:25Yesterday at 13:24Yesterday at 13:24Yesterday at 13:23Yesterday at 13.21Yesterdav at 13:21Yesterday at 13:20Yesterday at 13:20Yesterday at 13:19Yesterday at 13:19Yesterday at 13.18Vecterdav at 12:17Yesterday at 13:16Yesterdav at 13:16Yesterday at 13:15Yesterday at 13:14Yecterdav at 12:1/Yesterday at 13:13Yesterday at 13.13Yecterdav at 12:12Yesterday at 13:12Yesterday at 13:11Yesterday at 13:10Yesterday at 13:10Yesterday at 13.09Yecterdav at 12:091Yesterday at 13:08Yesterdav at 13:07MPEG-4 movie13 KBMPEG-4 movie16 KB1/ Kb29 KBMPEG-4 movieMPEG-4 movie6 KB12 KBMPE0"4 movie9 K:7 KBMPEG-4 movie8 KB37 KBMP2G-4 movie10 KBMPEG-4 movie7 KBMPEG"4 movie9K:8KBMPEG-4 movie72 KB14 K8|13 KRIMPEG-4 movieMPEG-4 movie9 KB18 KBMPEG-4 movie12 KEMPEG-4 movie10 KBMPEG-4 movie16 KB6 KB1MPEG-4 movie6 KBMPEG-4 movie12 KB23 KBMPEG-4 movie8 KEMPEG-4 movie6 KBMPEG-4 movie6 KBMPEG-4 movie11 K:MPEG-4 movie11 KBMPEG-4 movie34 KBMPEG-4 movie10 KPMPEG-4 movie7 KBMPEG-4 movie5 KBMPEG-4 movie11 KBIMPEG-4 movie26 KBMPEG-4 movie111 KB102 KBRR KRMPEG-4 movieMDEG-A movie59 KB98 KBMPEG-4 movie07 K:MPEG-A movie66 KB MPEG-4 movie44 KB93 KB79 KpMPEG-4 movieMPEG-4 movie58 KBMPEG-4 movie27 KP7 KBMPEG-4 movie12 KB32 K8MPEG-4 movieAl Notes: OffLeave• 0FavouritesE jiminny© Recents* ApplicationsiCloudiCloud Drive228 Sync folderQ DXP4800PLUS-B5FA@ Network|• CRMI• Orange• Red• Yellow• Green• Purple•) All lags..lohlDownloadsNameLoom.pkgAlfred copv.alfredoreterencesB KeychronAssist-1.0.2 (1).dmgA Keychron Assist-1.0.2.dmgmazanoke-images-yWJo.zioPhotos-3-001.zipD Transcript.pdf→mage U.loge1 Orioninstaller.dmaimage.jpg- image (2).1pc• ПО-22221726037035-004-001_ORGES.pdf• %D0%9F%D0%9E-22221726037035-004-001_archive.zipПO-22221726037035-004-001_archive (1).zip• repon 4).XmAltred copy2.altredoreterences05012026_0000000026574472_ SWIFT_OB70501260015890.pdf27022026_0000000026574472_SWIFT_OB72702260049200.pdf= 03042026 [CREDIT_CARD] SWIFT [CREDIT_CARD].001B reporti) xm=pdt.odipdf-1.pdfD pdf-2.pdf-pdf-5.pd1= ndf-1 ndipdf-3.pdfKoválik Family Tree.gedbitwarden export 20251031122528.isonKoválik Family Tree.zip*macOS Storage_Cleanup.mdal favicon icofirst_aid_notes_complete.docxrenortl2).esvconfig.ymlIteration run Search HS.postman_collection.jsonm licence bettertouchtoalMariusHosting Config.json1ooks-891a6503-bbb7-4b2b-9c3.csv•Alfredmazanoke-images-YWJ6ана Ковалик.jpg•искане даниел Ковалик..pa• Фактура Март Даниел Ковалик.jрс• Фактура Април Даниел Ковалик.jpg• Dhotac 2.001Q SearchKind00,4 MDinstdlle..dckage55.9 MBAlfred...ferences10,1 MBDisk Image10,1 MBDisk ImageIL MBLiP archive6,6 MBZIP archive2,5 MB PDF Document2,5 MBJreo lmage2.2 MBDisk Image2,2 MB PDF Document2 MBJPEG image1,9 MBJPEG imaqe192 KBPDF Document140 KbZIP archive148 KВ148 KB122 KB111 KB94 KBZIP archivelZIP archiveXML documentAlfred...ferencesPDF Document92 KBPDr DocumentK:91 KB91 KB30 KB29 KBPDF DocumentXML documentPDF Document28 KBPDF Document28 KR28 KB27 KB14 KB11 KB6 KB6KBPDE DocumentDocumentJSONICSV DocumentZIP archiveMarkdo…..ument5KRWindo...n image4 KB3 KBword ..cumentCSV Document2 KBYAML document1 KBcSV Document928 byteshttlicence183 bytesZero butesJSONAlfred.. ferencesZero bytesFolde1,9 MB1,8 MB17 MB1,7 MBColdorJPEG imageJPEG ImageIPEG imadeJPEG imageColdo1 of 58 selected, 8.51 G8 availabld• Inu 14 Mаy 1/•32-20Date AddedIs Mdl ZUzo dl 19:4530 Jan 2026 at 12:3617 Mar 2026 at 20:2717 Mar 2026 at 20:26Z3 Aor 2020 al 13:0229 Jan 2026 at 15:2019 Dec 2025 at 10:1619 Dec 2025 at 12:238 Aor 2026 at 20:3519 Dec 2025 at 10:2919 Dec 2025 at 12:1819 Dec 2025 at 12:4026 Mar 2026 at 11:2410 May 2026 at 13:5326 Mar 2026 at 11:2426 Mar 2026 at 11:2426 Mar 2026 at 11:2310 May 2026 at 14:3730 Jan 2026 at 12:3713 Feb 2026 at 11:54Z3 Apr 2026 at 13.0823 Aor 2026 at 13:0810 May 2026 at 13:5410 May 2026 at 14:3710 May 2026 at 13:4910 May 2026 at 13:5010 May 2026 at 13:5110 Mav 2026 at 12:51110 May 2026 at 13:5019 Dec 2025 at 11:3431 Oct 2025 at 12:2525 Nov 2025 at 17:596 Mar 2026 at 11.2224 Anr 2026 at 16:5220 Oct 2025 at 11:0218 Mar 2026 at 15:29• Mav 2026 at 11:09129 Oct 2025 at 19:329 May 2026 at 10:0418 Mar 2026 at 11:5510 May 2026 at 13:5712 Jun 2025 at 19:0430 Jan 2026 at 12:3630 Jan 2026 at 12:3616 Oct 2025 aт 16:0123 Apr 2026 at 13:0223 Apr 2026 at 13:0223 Apr 2026 at 13:0222 Anr 2026 at 12:0223 Apr 2026 at 13:0229 Jan 2026 at 15:20...
|
45347
|
NULL
|
NULL
|
NULL
|
|
45351
|
1625
|
12
|
2026-05-14T14:32:28.831004+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769148831_m1.jpg...
|
PhpStorm
|
faVsco.js – Copper/Service.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.054166667,"top":0.027777778,"width":0.08055556,"height":0.035555556},"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#12066 on JY-20725-handle-HS-search-rate-limit, menu","depth":5,"bounds":{"left":0.13472222,"top":0.027777778,"width":0.25555557,"height":0.035555556},"on_screen":true,"help_text":"Pull request #12066 exists for current branch JY-20725-handle-HS-search-rate-limit, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
7293744273990285589
|
-6961648536715800593
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12066 on JY-20725-handle Project: faVsco.js, menu
#12066 on JY-20725-handle-HS-search-rate-limit, menu
PhpStorm•FileFV faVsco.jsvEditViewNavigateCodeLaravelRefactorRunToolsGitWindowHelpabl100% C#12066 on JY-20725-handle-HS-search-rate-limit K vHandleHubspotRateLimitTestv* :8• Thu 14 May 17:32:28QProject v:=custom.logAutomatedReportGenerated.phpTrackAutomatedReportGeneratedEvent.phpPlaybackController.php© FieldDefinitions.phpUserAutomatedReportsController.phpPlanhatService.phpAutomatedReportResult.phpSendReportJob.php© FieldValueConverter.php• DeleteCrmEntityTrait.phpDeleteAccountJob.php© ImportActivityTypes.phpT WriteCrmTrait.phpDecorateActivity.php© Service.php© StandardFieldMetadata.php© Salesforce/Service.php© LogActivityTrait.phpPipedrive/Service.phpClose/Service.phpCopper/Service.php Xv D Copper© PlainTextDecorateActivity.phpT ActivityPlaybookTrait.php© CrmHelperRepository.phpAccountController.php18> D Api> D ExceptionT IntegrationAppTrait.php.env.stagingE.env© DetachActivityObject.phpRematchActivityOnCrmObjectDetach.php> C OpportunitySyncStrategy> D ProspectSearchStrategy> CJ Traits© MatchActivityCrmData.phpClient.php© HubspotPaginationService.phpclassService extendsBaseService implementsstring/nullHandleHubspotRateLimit.php© FieldDefinitions.php© FieldValueConverter.php© Service.php> D CrmObjects521517151815191520 € ›1557* }.*/public function matchByName(string $name, ?int $userId = null): ?array{...}v DecorateActivity3 usages© BaseDecorateActivity.php1558private function convertCrmData(array $object, string $objectType, ?int $userId = null): array{.© PlainTextDecorateActivity.pl1611> D Dummy1612 Cpublic function saveActivity(Activity $activity): Activityv Helpers1613T ActivityPlaybookTrait.php1614© Arraylterator.php1615• ConnectionStateTrait.php1616© CrmHelperRepository.php1617© FilterJoinedParticipants.php1618switch (Sactivity->type) {case Activity:: TYPE_CONFERENCE:case Activity:: TYPE_SOFTPHONE:case Activity: : TYPE_SOFTPHONE_INBOUND:Sactivity = $this->buildCallPayload(Sactivity):* OpportunitySyncableFieldsT1619v C Hubspot1620• AccountSyncStrategy1621> DJ Actions |1622• ContactSyncStrategy1623break;case Activity:: TYPE_SMS_INBOUND:case Activity: : TYPE_SMS_OUTBOUND:Sactivity = $this->buildTextMessagePayload($activity);> ODTO1624› Fields1625break:> • Journal1626D Metadata1627v D OpportunitySyncStrategy1628return Sactivity:> D Concerns1629A Lihonntl actlAndifiaNDurWorkspace associated with branch 'JY-20725-handle-HS-search-rate-limit' has been restored // Rollback // Configure... (today 16:17)Analyzing…=laravel.logSF [jiminny@localhost]A HS_local [jiminny@localho:W4 console [QAI PROD] X4 console [PROD]A console (EU]DGo jiminny084143 ×4 л215|•m_layout_id =2162,1661,66799,66217218219id = 33;220221222223224id THEN '(own225226227228229230hubspot':-231+ 232233V= 11512582;234W Windsurf Teams1612:21UTF-8Ca 4 spaces...
|
45350
|
NULL
|
NULL
|
NULL
|
|
45350
|
1625
|
11
|
2026-05-14T14:32:26.489014+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-14/1778 /Users/lukas/.screenpipe/data/data/2026-05-14/1778769146489_m1.jpg...
|
PhpStorm
|
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
sa
Inherited members (⌘R)
Anonymous Classes (⌘I)
L sa
Inherited members (⌘R)
Anonymous Classes (⌘I)
Lambdas (⌘L)
Service, class
NOTE_BODY_MAX_LENGTH: int = 3000000, private
OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE: string = 'Opportunity import ..., private
OPPORTUNITY_STATUS_OPEN: string = 'Open', private
RESOURCE_UPDATE_FAILED_ERROR_MESSAGE: string = 'Failed to update re..., private
STANDARD_OPPORTUNITY_FIELDS: array|array[] = [...], private
TASK_VERIFICATION_CACHE_TTL: int = 86400, private
UNSUPPORTED_OBJECT_TYPE: string = 'unsupported', private
clientFactory: ClientFactory, private
copperClient: Client|null = null ↑SearchesCrmEntities, private
crmEntityRepository: CrmEntityRepository, parameter
fieldValueConverter: FieldValueConverter, private
prospectPhotoPathService: ProspectPhotoPathService, parameter
userRepository: UserRepository, parameter
__construct(clientFactory: ClientFactory, fieldValueConverter: FieldValueConverter, userRepository: UserRepository, prospectPhotoPathService: ProspectPhotoPathService, crmEntityRepository: CrmEntityRepository) ↑BaseService, method
buildCallPayload(activity: Activity): Activity, method
buildContactMobilePhone(countryCode: null|string, number: null|string): null|string, method
buildContactPhone(countryCode: null|string, number: null|string): array|null, method
buildTextMessagePayload(activity: Activity): Activity, method
convertActivityAssociations(activity: Activity): array, method
convertActivityType(activityType: PlaybookCategory): array, method
convertCrmData(object: array, objectType: string, [userId: int|null = null]): array, method
convertFieldType(fieldType: string): string, method
createTranscriptNotes(activity: Activity): void ↑RemoteEntityManipulationInterface, method
extractFieldValue(opportunityData: mixed[], fieldName: string): bool|float|int|mixed[]|null|string, method
fetchCustomFieldData(activity: Activity, objectType: string): array, method
find(name: string, scopes: array): array ↑RemoteEntityLookupInterface, method
findOpportunities(crmAccountId: null|string, crmContactId: null|string, [userId: int|null = null]): array ↑RemoteEntityLookupInterface, method
generateActivityDescription(activity: Activity): string, method
generateProviderUrl(providerId: string, objectType: string): null|string ↑SettingsInterface, method
generateTranscription(activity: Activity): string, method
getCrmEntityRepository(): CrmEntityRepository ↑SearchesCrmEntities, method
getDealInsightsFields(): array|string[][] ↑LayoutManagementInterface, method
getDefaultActivityField(activityType: string): Field ↑LayoutManagementInterface, method
getDefaultFields(activityType: string): array ↑LayoutManagementInterface, method
getDefaultFollowupLayoutFields(activityType: string): array ↑BaseService, method
getDisplayName(): string ↑SettingsInterface, method
getFields(crmObject: string): array ↑BaseService, method
getFieldTypes(): array ↑BaseService, method
getMinimumApiVersion(): string ↑ServiceInterface, method
getOAuthAccount(user: User): SocialAccount|null ↑BaseService, protected method
getRecord(objectType: string, objectId: string, [fields: array = [...]]): array ↑RemoteEntityLookupInterface, method
getSupportedPlaybookTypes(): array ↑SettingsInterface, method
getTasks(objectType: string, objectId: string, opportunityId: null|string): array ↑RemoteEntityLookupInterface, method
importAccount(crmData): Account, method
importContact(crmData): Contact, method
importFieldValuesForDealInsights(field: Field): FieldValue[], method
importLead(crmData): Lead|null, method
importOpportunity(crmData): Opportunity|null, method
importOpportunityCrmFieldData(opportunityData: array|mixed[], dealInsightsFields: string[], opportunityId: int): void ↑BaseService, method
importPicklistValues(field: Field): array|FieldValue[] ↑SyncCrmEntitiesInterface, method
importStages([types: array|null = null], [missingStageName: null|string = null]): Stage|null ↑SyncCrmEntitiesInterface, method
isStandardField(fieldName: string): bool, method
isSupportedObjectType(objectType: string): bool, method
mapObjectType(objectType: string): string, method
matchByName(name: string, [userId: int|null = null]): array|null ↑MatchCrmEntitiesInterface, method
matchByPhone(phone: string, [rawPhoneNumber: null|string = null], [userId: int|null = null]): array|null ↑MatchCrmEntitiesInterface, public method
matchExactlyByEmail(email: string, [userId: int|null = null]): array|null ↑MatchCrmEntitiesInterface, public method
normalizeValue(fieldType: string, fieldValue: string, [internal: bool = false]): string ↑SettingsInterface, public method
prepareOpportunityFieldsForUpdate(fieldData: string[]): bool[]|bool[][][]|float[]|float[][][]|int[]|int[][][]|null[]|null[][][]|string[]|string[][][], private method
prepareValueForUpdate(params: array): array ↑BaseService, public method
requestWithExceptionHandling(apiRequest: Closure): iterable, private method
resolveCustomFieldFromOpportunityData(opportunityData: mixed[], fieldName: string): bool|float|int|mixed[]|null|string, private method
saveActivity(activity: Activity): Activity ↑RemoteEntityManipulationInterface, public method
saveFollowupActivity(activity: Activity, fields: array): null|string ↑RemoteEntityManipulationInterface, public method
setConfiguration(configuration: Configuration): void ↑SettingsInterface, public method
setUser(user: User): void ↑SettingsInterface, public method
syncAccount(crmId: string): Account|null ↑SyncCrmEntitiesInterface, public method
syncAccounts(since: \Carbon\Carbon, [to: \Carbon\Carbon|null = null]): int ↑SyncCrmEntitiesInterface, public method
syncContact(crmId: string): Contact|null ↑SyncCrmEntitiesInterface, public method
syncContacts(since: \Carbon\Carbon, [to: \Carbon\Carbon|null = null]): int ↑SyncCrmEntitiesInterface, public method
syncCustomFields(): void, method
syncField(field: Field): void ↑SyncCrmEntitiesInterface, method
syncFields(): void ↑SyncCrmEntitiesInterface, method
syncLead(crmId: string): Lead|null ↑SyncCrmEntitiesInterface, method
syncLeads(since: \Carbon\Carbon, [to: \Carbon\Carbon|null = null], [crmProfileId: null|string = null]): int ↑SyncCrmEntitiesInterface, method
syncOpportunities(parameters: array, [strategy: null|string = null]): int ↑SyncCrmEntitiesInterface, method
syncOpportunity(crmId: string): Opportunity|null ↑SyncCrmEntitiesInterface, method
syncOrganization(): void ↑SyncCrmMetadataInterface, method
syncProfileFields(): void ↑SyncCrmMetadataInterface, method
syncProfiles([userToSearch: User|null = null]): Profile|null ↑SyncCrmMetadataInterface, method...
|
[{"role":"AXTextField","text [{"role":"AXTextField","text":"sa","depth":1,"bounds":{"left":0.52152777,"top":0.32,"width":0.06458333,"height":0.031111112},"on_screen":true,"value":"sa","role_description":"text field","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Inherited members (⌘R)","depth":1,"bounds":{"left":0.5277778,"top":0.35555556,"width":0.10972222,"height":0.031111112},"on_screen":true,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Anonymous Classes (⌘I)","depth":1,"bounds":{"left":0.64444447,"top":0.35555556,"width":0.10972222,"height":0.031111112},"on_screen":true,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Lambdas (⌘L)","depth":1,"bounds":{"left":0.76111114,"top":0.35555556,"width":0.10972222,"height":0.031111112},"on_screen":true,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Service, class","depth":4,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"NOTE_BODY_MAX_LENGTH: int = 3000000, private","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE: string = 'Opportunity import ..., private","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"OPPORTUNITY_STATUS_OPEN: string = 'Open', private","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"RESOURCE_UPDATE_FAILED_ERROR_MESSAGE: string = 'Failed to update re..., private","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"STANDARD_OPPORTUNITY_FIELDS: array|array[] = [...], private","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"TASK_VERIFICATION_CACHE_TTL: int = 86400, private","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"UNSUPPORTED_OBJECT_TYPE: string = 'unsupported', private","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"clientFactory: ClientFactory, private","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"copperClient: Client|null = null ↑SearchesCrmEntities, private","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"crmEntityRepository: CrmEntityRepository, parameter","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"fieldValueConverter: FieldValueConverter, private","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"prospectPhotoPathService: ProspectPhotoPathService, parameter","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"userRepository: UserRepository, parameter","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"__construct(clientFactory: ClientFactory, fieldValueConverter: FieldValueConverter, userRepository: UserRepository, prospectPhotoPathService: ProspectPhotoPathService, crmEntityRepository: CrmEntityRepository) ↑BaseService, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"buildCallPayload(activity: Activity): Activity, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"buildContactMobilePhone(countryCode: null|string, number: null|string): null|string, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"buildContactPhone(countryCode: null|string, number: null|string): array|null, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"buildTextMessagePayload(activity: Activity): Activity, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"convertActivityAssociations(activity: Activity): array, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"convertActivityType(activityType: PlaybookCategory): array, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"convertCrmData(object: array, objectType: string, [userId: int|null = null]): array, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"convertFieldType(fieldType: string): string, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"createTranscriptNotes(activity: Activity): void ↑RemoteEntityManipulationInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"extractFieldValue(opportunityData: mixed[], fieldName: string): bool|float|int|mixed[]|null|string, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"fetchCustomFieldData(activity: Activity, objectType: string): array, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"find(name: string, scopes: array): array ↑RemoteEntityLookupInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"findOpportunities(crmAccountId: null|string, crmContactId: null|string, [userId: int|null = null]): array ↑RemoteEntityLookupInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"generateActivityDescription(activity: Activity): string, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"generateProviderUrl(providerId: string, objectType: string): null|string ↑SettingsInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"generateTranscription(activity: Activity): string, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getCrmEntityRepository(): CrmEntityRepository ↑SearchesCrmEntities, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getDealInsightsFields(): array|string[][] ↑LayoutManagementInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getDefaultActivityField(activityType: string): Field ↑LayoutManagementInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getDefaultFields(activityType: string): array ↑LayoutManagementInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getDefaultFollowupLayoutFields(activityType: string): array ↑BaseService, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getDisplayName(): string ↑SettingsInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getFields(crmObject: string): array ↑BaseService, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getFieldTypes(): array ↑BaseService, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getMinimumApiVersion(): string ↑ServiceInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getOAuthAccount(user: User): SocialAccount|null ↑BaseService, protected method","depth":5,"bounds":{"left":0.55277777,"top":0.48777777,"width":0.30416667,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"getRecord(objectType: string, objectId: string, [fields: array = [...]]): array ↑RemoteEntityLookupInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getSupportedPlaybookTypes(): array ↑SettingsInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"getTasks(objectType: string, objectId: string, opportunityId: null|string): array ↑RemoteEntityLookupInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"importAccount(crmData): Account, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"importContact(crmData): Contact, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"importFieldValuesForDealInsights(field: Field): FieldValue[], method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"importLead(crmData): Lead|null, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"importOpportunity(crmData): Opportunity|null, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"importOpportunityCrmFieldData(opportunityData: array|mixed[], dealInsightsFields: string[], opportunityId: int): void ↑BaseService, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"importPicklistValues(field: Field): array|FieldValue[] ↑SyncCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"importStages([types: array|null = null], [missingStageName: null|string = null]): Stage|null ↑SyncCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"isStandardField(fieldName: string): bool, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"isSupportedObjectType(objectType: string): bool, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"mapObjectType(objectType: string): string, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"matchByName(name: string, [userId: int|null = null]): array|null ↑MatchCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"matchByPhone(phone: string, [rawPhoneNumber: null|string = null], [userId: int|null = null]): array|null ↑MatchCrmEntitiesInterface, public method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"matchExactlyByEmail(email: string, [userId: int|null = null]): array|null ↑MatchCrmEntitiesInterface, public method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"normalizeValue(fieldType: string, fieldValue: string, [internal: bool = false]): string ↑SettingsInterface, public method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"prepareOpportunityFieldsForUpdate(fieldData: string[]): bool[]|bool[][][]|float[]|float[][][]|int[]|int[][][]|null[]|null[][][]|string[]|string[][][], private method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"prepareValueForUpdate(params: array): array ↑BaseService, public method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"requestWithExceptionHandling(apiRequest: Closure): iterable, private method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"resolveCustomFieldFromOpportunityData(opportunityData: mixed[], fieldName: string): bool|float|int|mixed[]|null|string, private method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"saveActivity(activity: Activity): Activity ↑RemoteEntityManipulationInterface, public method","depth":5,"bounds":{"left":0.55277777,"top":0.51222223,"width":0.3548611,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"saveFollowupActivity(activity: Activity, fields: array): null|string ↑RemoteEntityManipulationInterface, public method","depth":5,"bounds":{"left":0.55277777,"top":0.5366667,"width":0.44722223,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"setConfiguration(configuration: Configuration): void ↑SettingsInterface, public method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"setUser(user: User): void ↑SettingsInterface, public method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncAccount(crmId: string): Account|null ↑SyncCrmEntitiesInterface, public method","depth":5,"bounds":{"left":0.55277777,"top":0.5611111,"width":0.32291666,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"syncAccounts(since: \\Carbon\\Carbon, [to: \\Carbon\\Carbon|null = null]): int ↑SyncCrmEntitiesInterface, public method","depth":5,"bounds":{"left":0.55277777,"top":0.58555555,"width":0.44722223,"height":0.024444444},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"syncContact(crmId: string): Contact|null ↑SyncCrmEntitiesInterface, public method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncContacts(since: \\Carbon\\Carbon, [to: \\Carbon\\Carbon|null = null]): int ↑SyncCrmEntitiesInterface, public method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncCustomFields(): void, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncField(field: Field): void ↑SyncCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncFields(): void ↑SyncCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncLead(crmId: string): Lead|null ↑SyncCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncLeads(since: \\Carbon\\Carbon, [to: \\Carbon\\Carbon|null = null], [crmProfileId: null|string = null]): int ↑SyncCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncOpportunities(parameters: array, [strategy: null|string = null]): int ↑SyncCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncOpportunity(crmId: string): Opportunity|null ↑SyncCrmEntitiesInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncOrganization(): void ↑SyncCrmMetadataInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncProfileFields(): void ↑SyncCrmMetadataInterface, method","depth":5,"on_screen":false,"role_description":"text"},{"role":"AXStaticText","text":"syncProfiles([userToSearch: User|null = null]): Profile|null ↑SyncCrmMetadataInterface, method","depth":5,"on_screen":false,"role_description":"text"}]...
|
1253387167212463152
|
-1070430673578670609
|
visual_change
|
accessibility
|
NULL
|
sa
Inherited members (⌘R)
Anonymous Classes (⌘I)
L sa
Inherited members (⌘R)
Anonymous Classes (⌘I)
Lambdas (⌘L)
Service, class
NOTE_BODY_MAX_LENGTH: int = 3000000, private
OPPORTUNITY_IMPORT_FAILED_ERROR_MESSAGE: string = 'Opportunity import ..., private
OPPORTUNITY_STATUS_OPEN: string = 'Open', private
RESOURCE_UPDATE_FAILED_ERROR_MESSAGE: string = 'Failed to update re..., private
STANDARD_OPPORTUNITY_FIELDS: array|array[] = [...], private
TASK_VERIFICATION_CACHE_TTL: int = 86400, private
UNSUPPORTED_OBJECT_TYPE: string = 'unsupported', private
clientFactory: ClientFactory, private
copperClient: Client|null = null ↑SearchesCrmEntities, private
crmEntityRepository: CrmEntityRepository, parameter
fieldValueConverter: FieldValueConverter, private
prospectPhotoPathService: ProspectPhotoPathService, parameter
userRepository: UserRepository, parameter
__construct(clientFactory: ClientFactory, fieldValueConverter: FieldValueConverter, userRepository: UserRepository, prospectPhotoPathService: ProspectPhotoPathService, crmEntityRepository: CrmEntityRepository) ↑BaseService, method
buildCallPayload(activity: Activity): Activity, method
buildContactMobilePhone(countryCode: null|string, number: null|string): null|string, method
buildContactPhone(countryCode: null|string, number: null|string): array|null, method
buildTextMessagePayload(activity: Activity): Activity, method
convertActivityAssociations(activity: Activity): array, method
convertActivityType(activityType: PlaybookCategory): array, method
convertCrmData(object: array, objectType: string, [userId: int|null = null]): array, method
convertFieldType(fieldType: string): string, method
createTranscriptNotes(activity: Activity): void ↑RemoteEntityManipulationInterface, method
extractFieldValue(opportunityData: mixed[], fieldName: string): bool|float|int|mixed[]|null|string, method
fetchCustomFieldData(activity: Activity, objectType: string): array, method
find(name: string, scopes: array): array ↑RemoteEntityLookupInterface, method
findOpportunities(crmAccountId: null|string, crmContactId: null|string, [userId: int|null = null]): array ↑RemoteEntityLookupInterface, method
generateActivityDescription(activity: Activity): string, method
generateProviderUrl(providerId: string, objectType: string): null|string ↑SettingsInterface, method
generateTranscription(activity: Activity): string, method
getCrmEntityRepository(): CrmEntityRepository ↑SearchesCrmEntities, method
getDealInsightsFields(): array|string[][] ↑LayoutManagementInterface, method
getDefaultActivityField(activityType: string): Field ↑LayoutManagementInterface, method
getDefaultFields(activityType: string): array ↑LayoutManagementInterface, method
getDefaultFollowupLayoutFields(activityType: string): array ↑BaseService, method
getDisplayName(): string ↑SettingsInterface, method
getFields(crmObject: string): array ↑BaseService, method
getFieldTypes(): array ↑BaseService, method
getMinimumApiVersion(): string ↑ServiceInterface, method
getOAuthAccount(user: User): SocialAccount|null ↑BaseService, protected method
getRecord(objectType: string, objectId: string, [fields: array = [...]]): array ↑RemoteEntityLookupInterface, method
getSupportedPlaybookTypes(): array ↑SettingsInterface, method
getTasks(objectType: string, objectId: string, opportunityId: null|string): array ↑RemoteEntityLookupInterface, method
importAccount(crmData): Account, method
importContact(crmData): Contact, method
importFieldValuesForDealInsights(field: Field): FieldValue[], method
importLead(crmData): Lead|null, method
importOpportunity(crmData): Opportunity|null, method
importOpportunityCrmFieldData(opportunityData: array|mixed[], dealInsightsFields: string[], opportunityId: int): void ↑BaseService, method
importPicklistValues(field: Field): array|FieldValue[] ↑SyncCrmEntitiesInterface, method
importStages([types: array|null = null], [missingStageName: null|string = null]): Stage|null ↑SyncCrmEntitiesInterface, method
isStandardField(fieldName: string): bool, method
isSupportedObjectType(objectType: string): bool, method
mapObjectType(objectType: string): string, method
matchByName(name: string, [userId: int|null = null]): array|null ↑MatchCrmEntitiesInterface, method
matchByPhone(phone: string, [rawPhoneNumber: null|string = null], [userId: int|null = null]): array|null ↑MatchCrmEntitiesInterface, public method
matchExactlyByEmail(email: string, [userId: int|null = null]): array|null ↑MatchCrmEntitiesInterface, public method
normalizeValue(fieldType: string, fieldValue: string, [internal: bool = false]): string ↑SettingsInterface, public method
prepareOpportunityFieldsForUpdate(fieldData: string[]): bool[]|bool[][][]|float[]|float[][][]|int[]|int[][][]|null[]|null[][][]|string[]|string[][][], private method
prepareValueForUpdate(params: array): array ↑BaseService, public method
requestWithExceptionHandling(apiRequest: Closure): iterable, private method
resolveCustomFieldFromOpportunityData(opportunityData: mixed[], fieldName: string): bool|float|int|mixed[]|null|string, private method
saveActivity(activity: Activity): Activity ↑RemoteEntityManipulationInterface, public method
saveFollowupActivity(activity: Activity, fields: array): null|string ↑RemoteEntityManipulationInterface, public method
setConfiguration(configuration: Configuration): void ↑SettingsInterface, public method
setUser(user: User): void ↑SettingsInterface, public method
syncAccount(crmId: string): Account|null ↑SyncCrmEntitiesInterface, public method
syncAccounts(since: \Carbon\Carbon, [to: \Carbon\Carbon|null = null]): int ↑SyncCrmEntitiesInterface, public method
syncContact(crmId: string): Contact|null ↑SyncCrmEntitiesInterface, public method
syncContacts(since: \Carbon\Carbon, [to: \Carbon\Carbon|null = null]): int ↑SyncCrmEntitiesInterface, public method
syncCustomFields(): void, method
syncField(field: Field): void ↑SyncCrmEntitiesInterface, method
syncFields(): void ↑SyncCrmEntitiesInterface, method
syncLead(crmId: string): Lead|null ↑SyncCrmEntitiesInterface, method
syncLeads(since: \Carbon\Carbon, [to: \Carbon\Carbon|null = null], [crmProfileId: null|string = null]): int ↑SyncCrmEntitiesInterface, method
syncOpportunities(parameters: array, [strategy: null|string = null]): int ↑SyncCrmEntitiesInterface, method
syncOpportunity(crmId: string): Opportunity|null ↑SyncCrmEntitiesInterface, method
syncOrganization(): void ↑SyncCrmMetadataInterface, method
syncProfileFields(): void ↑SyncCrmMetadataInterface, method
syncProfiles([userToSearch: User|null = null]): Profile|null ↑SyncCrmMetadataInterface, method...
|
NULL
|
NULL
|
NULL
|
NULL
|