|
87900
|
3001
|
29
|
2026-05-28T16:29:05.260408+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985745260_m2.jpg...
|
Alfred
|
Alfred
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Alfred Search Field
|
[{"role":"AXTextField","text [{"role":"AXTextField","text":"Alfred Search Field","depth":1,"on_screen":true,"help_text":"Alfred Search","role_description":"text field","is_enabled":true,"is_focused":true}]...
|
7926243118367575
|
7570943109877468232
|
typing_pause
|
hybrid
|
NULL
|
Alfred Search Field
wuniconX HubspotwYour team is Alfred Search Field
wuniconX HubspotwYour team is now on the Free plan with 1 admin. You retain editing access and other members are read-only. View team permissicas to see who can edit, or ungrade to restore collaborationUseful › get history of property - deal stage((baseUri))/deats/V1/deal/494058190045?includePropertyVersions=trucE Docs Params • Authorization • Headers 12 Body • Scriots SettingsQuery Paramsv includePropertyVersionsobiectTyeo0sLXThu 28 May 19:29:06© Scarchlollietmnr sayeeoehtorooeCEr RendCr det meetinoct eonthet with ihR SaveV COLLECYIONS> HubsootKeration tun Hoteration run Searchts› Journal & webhocoks v4• Poperiesv a crm/vs xoverties ob ect tvoe> (t batchacouos> (a(property Name)y ut Resd all propertiesca successful operationAn ertor occurredrooneresle a properRESSAREH• СЕAРCH> Tckev Useful> rost tilter per comoanyonly ooen deal staoes.cEt engagements old associated by deawenanacmmnts dd nscocintnd oy comasnv сEt get history of property - deal stagenosuccasstul operation55. An error occurred.at get usersCET SF osuthuumeating cutcomes cer mectinoaPondi all nranortioe nou.> ct Resd all properties oldCT old call dispositionset list with associationscEt list engagements okeuirecendencsaementCET get dealcEt Get Engagement (v1)PATCH https://api.hubapi.com/engagements/V1/engagements/2492739S231Parckhttos:/api.hubaoi.com/crm/vs/co.ects/meet.nos/2497k5x3%wrchttosdllanihubani. com/ancacamanteMlaoonoamaatc/240273052811CiuodstedesioodCMMIDANIENTCSPECS> FLOWSOConndettCoasde em aniooDetcrictionSondCookiesp.YKEOKEJSONvPreview Visualizestad.700 ok. 270ms. 41.76 KRAs ab.* 70122ken Save Resnons?ддаг8юдд6осаевовeprobabal1tyHandler_deal_stage_pF|Cannot edit in read-only editorsouxcoid*: *DealStageProbabil{tyHandlor*"CALCULATED"requestid*: *019e46a9-51b8-7e60-9db6-153e5c1b1529,uket restaroAsPerssistencet mestamo"etmue."sourceUpstreamDeployable*: "ForecastingKafka-deal-stage-probability-workezapromotrwhhndilor"-78be-bc7b-ccf524c62eb6*uselznescaspnspersistencelamestanp: crue•souxceUpstreanDeployable*: *ForccastingKafka-deal•stage-probability-worker"Mea"e thecaciase oromahity•A7201Giobnts Montt Tookemed...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87897
|
3001
|
28
|
2026-05-28T16:29:00.797481+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985740797_m2.jpg...
|
iTerm2
|
NULL
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
VieWwunicowX HubspotYour team is now on the Free p VieWwunicowX HubspotYour team is now on the Free plan with 1 admin. You retain editing access and other members are read-only. View team permissicas to see who can edit, or ungrade to restore collaborationUseful › get history of property - deal stage((baseUri))/deats/V1/deal/494058190045?includePropertyVersionstrucE Docs Params • Authorization • Headers 12 Body • Scriots SettingsQuery Paramsv includePropertyVersionsobiectTyeThu 28 May 19:29:00© Scarchollietmnn sayeCoe hitoroore eOET ReadCr det meetinoet eonther with mhR SaveV COLLECYIONS> HubsootKeration tun Hoteration run Search HS› Journal & webhocoks v4• Poperiesv a crm/vsxovertes ob ect tvoe> (t batchacouos> (a(property Name)y ut Resd all propertiesca successful operationAn ertor occurredroneresle a properRESSAREH• СЕAРCH> Tckev Useful> rost tilter per comoany oniy ooen deal staoes.cEt engagements old associated by deawenanacments dld nscocntedloy comasn.v t get history of property - deal stagenosuccasstul operation55. An error occurred.at getusersCET SF osuthuuMeeting cutcomes cer mectinowpond all aranortios nou.> ct Resd all properties oldсT old call dispositionset list with associationscEt list engagements okuuirecentencsaementCET get dealcEt Get Engagement (v1)PATCH https://api.hubapi.com/engagements/V1/engagements/24927395231Parckhttos:/api.hubaoi.com/crm/vs/co.ects/meet.nos/2497k5x3%wTchttosdllanihubani. com/ancacamantslaoonoamaatc/240273052811Ciodstedessa00CMMIDANIENTCSPECS> FLOWSEConnnettPoasolewwsotoodDetcrictionSondCookiesp.YKEOSJSON vPreview Visualizestad.700 ok. 270ms. 41.76 KRAs ab.* 70122wn Save Resnons,JE Xддаг8юдд6асаевевeprobab{lityHandlerdeal stase probability',ainestaro: 1719301965775souxcoid": *DealStageProbabil{tyHandlor""CALCULATED"requestid*: *019e46a9-51b8-7e60-9db6-153e5c1b1529*.uket restaroAsPerssistencet mestamo"etmue."sourceUpstreamDeployable*: "ForecastingKafka-deal-stage-probability-workezẬV++. -aprombrwhandilor"-78be-bc7b-ccf524c62eb6*uselznescasonspersistencelamestamp: crue•souxceUpstreanDeployable*: *ForccastingKafka-deal•stage-probability-worker"name": "hs_deal_stage_probability"•A7201HIGiobnts Montt Tookenem...
|
NULL
|
3454370956757743985
|
NULL
|
click
|
ocr
|
NULL
|
VieWwunicowX HubspotYour team is now on the Free p VieWwunicowX HubspotYour team is now on the Free plan with 1 admin. You retain editing access and other members are read-only. View team permissicas to see who can edit, or ungrade to restore collaborationUseful › get history of property - deal stage((baseUri))/deats/V1/deal/494058190045?includePropertyVersionstrucE Docs Params • Authorization • Headers 12 Body • Scriots SettingsQuery Paramsv includePropertyVersionsobiectTyeThu 28 May 19:29:00© Scarchollietmnn sayeCoe hitoroore eOET ReadCr det meetinoet eonther with mhR SaveV COLLECYIONS> HubsootKeration tun Hoteration run Search HS› Journal & webhocoks v4• Poperiesv a crm/vsxovertes ob ect tvoe> (t batchacouos> (a(property Name)y ut Resd all propertiesca successful operationAn ertor occurredroneresle a properRESSAREH• СЕAРCH> Tckev Useful> rost tilter per comoany oniy ooen deal staoes.cEt engagements old associated by deawenanacments dld nscocntedloy comasn.v t get history of property - deal stagenosuccasstul operation55. An error occurred.at getusersCET SF osuthuuMeeting cutcomes cer mectinowpond all aranortios nou.> ct Resd all properties oldсT old call dispositionset list with associationscEt list engagements okuuirecentencsaementCET get dealcEt Get Engagement (v1)PATCH https://api.hubapi.com/engagements/V1/engagements/24927395231Parckhttos:/api.hubaoi.com/crm/vs/co.ects/meet.nos/2497k5x3%wTchttosdllanihubani. com/ancacamantslaoonoamaatc/240273052811Ciodstedessa00CMMIDANIENTCSPECS> FLOWSEConnnettPoasolewwsotoodDetcrictionSondCookiesp.YKEOSJSON vPreview Visualizestad.700 ok. 270ms. 41.76 KRAs ab.* 70122wn Save Resnons,JE Xддаг8юдд6асаевевeprobab{lityHandlerdeal stase probability',ainestaro: 1719301965775souxcoid": *DealStageProbabil{tyHandlor""CALCULATED"requestid*: *019e46a9-51b8-7e60-9db6-153e5c1b1529*.uket restaroAsPerssistencet mestamo"etmue."sourceUpstreamDeployable*: "ForecastingKafka-deal-stage-probability-workezẬV++. -aprombrwhandilor"-78be-bc7b-ccf524c62eb6*uselznescasonspersistencelamestamp: crue•souxceUpstreanDeployable*: *ForccastingKafka-deal•stage-probability-worker"name": "hs_deal_stage_probability"•A7201HIGiobnts Montt Tookenem...
|
87896
|
NULL
|
NULL
|
NULL
|
|
87896
|
3001
|
27
|
2026-05-28T16:28:45.324755+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985725324_m2.jpg...
|
iTerm2
|
NULL
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
VieWwunicowX HubspotYour team is now on the Free p VieWwunicowX HubspotYour team is now on the Free plan with 1 admin. You retain editing access and other members are read-only. View team permissicas to see who can edit, or ungrade to restore collaborationUseful › get history of property - deal stage((baseUri))/deats/V1/deal/494058190045?includePropertyVersionstrucE Docs Params • Authorization • Headers 12 Body • Scriots SettingsQuery Paramsv includePropertyVersionsobiectTye@ Searchollietmnn sayeCoe hitoroore eCEr RendCr det meetino4oct eonthet with ihThu 28 May 19:28:46R SaveV COLLECYIONS> HubsootKeration tun Hoteration run Searchts› Journal & webhocoks v4• Poperiesv a crmvs/xoverteskob ect lvoe> (t batchacouos> (a(property Name)y ut Resd all propertiesca successful operationAn ertor occurredroneresle a properRESSAREH• СЕAРCH> Tckev Useful> rost tilter per comoanyonly ooen deal staoes.cEt engagements old associated by deawenanacments dld nscocntedloy comasn.v сEt get history of property - deal stagenosuccasstul operation55. An error occurred.at getusersCET SF osuthuuMeeting cutcomes cer mectinoaPond all nranortioe nou.> ct Resd all properties oldсT old call dispositionset list with associationscEt list engagements okuuirecentencsaementCET get dealcEt Get Engagement (v1)PATCH https://api.hubapi.com/engagements/V1/engagements/2492739S231Parckhttos:/api.hubaoi.com/crm/vs/co.ects/meet.nos/2497k5x3%wTchttosdllanihubani. com/ancacamantslaoonoamaatc/240273052811Ciodstedessa00CMMIDANIENTCSPECS> FLOWSOConnnettCoasdleem antooDetcrictionSondCookiesp.YKEOKEJSONvP% Visualize"uselsirestaroAcPerssistencetmestamo"etaue.*sourceUpstreamDeployable*: *ForecastingKafka-deal-stage-probability-workezame*: "hs deal stase_probability"Ртовbtв сунand er".useTinestaspAsPersistenceTimestamp*: true"souxceUpstreanDeployable*: *ForccastingKafka-deal-stage-probability-worker""nane": "hs_deal_stage_probability"."ylu". *0,5""Xoastaro": 1776674845838"sourceld": "DealStageProbabilityHandler".*019daa12-640e-7560-884c-3dccd/300910*.stad.200ok:270ms. 41.76 KRAs ab.* 70122wn Save Resnons,HIGiobnts Montt Tookemem...
|
NULL
|
-3150212978057685637
|
NULL
|
visual_change
|
ocr
|
NULL
|
VieWwunicowX HubspotYour team is now on the Free p VieWwunicowX HubspotYour team is now on the Free plan with 1 admin. You retain editing access and other members are read-only. View team permissicas to see who can edit, or ungrade to restore collaborationUseful › get history of property - deal stage((baseUri))/deats/V1/deal/494058190045?includePropertyVersionstrucE Docs Params • Authorization • Headers 12 Body • Scriots SettingsQuery Paramsv includePropertyVersionsobiectTye@ Searchollietmnn sayeCoe hitoroore eCEr RendCr det meetino4oct eonthet with ihThu 28 May 19:28:46R SaveV COLLECYIONS> HubsootKeration tun Hoteration run Searchts› Journal & webhocoks v4• Poperiesv a crmvs/xoverteskob ect lvoe> (t batchacouos> (a(property Name)y ut Resd all propertiesca successful operationAn ertor occurredroneresle a properRESSAREH• СЕAРCH> Tckev Useful> rost tilter per comoanyonly ooen deal staoes.cEt engagements old associated by deawenanacments dld nscocntedloy comasn.v сEt get history of property - deal stagenosuccasstul operation55. An error occurred.at getusersCET SF osuthuuMeeting cutcomes cer mectinoaPond all nranortioe nou.> ct Resd all properties oldсT old call dispositionset list with associationscEt list engagements okuuirecentencsaementCET get dealcEt Get Engagement (v1)PATCH https://api.hubapi.com/engagements/V1/engagements/2492739S231Parckhttos:/api.hubaoi.com/crm/vs/co.ects/meet.nos/2497k5x3%wTchttosdllanihubani. com/ancacamantslaoonoamaatc/240273052811Ciodstedessa00CMMIDANIENTCSPECS> FLOWSOConnnettCoasdleem antooDetcrictionSondCookiesp.YKEOKEJSONvP% Visualize"uselsirestaroAcPerssistencetmestamo"etaue.*sourceUpstreamDeployable*: *ForecastingKafka-deal-stage-probability-workezame*: "hs deal stase_probability"Ртовbtв сунand er".useTinestaspAsPersistenceTimestamp*: true"souxceUpstreanDeployable*: *ForccastingKafka-deal-stage-probability-worker""nane": "hs_deal_stage_probability"."ylu". *0,5""Xoastaro": 1776674845838"sourceld": "DealStageProbabilityHandler".*019daa12-640e-7560-884c-3dccd/300910*.stad.200ok:270ms. 41.76 KRAs ab.* 70122wn Save Resnons,HIGiobnts Montt Tookemem...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87895
|
3001
|
26
|
2026-05-28T16:28:43.046521+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985723046_m2.jpg...
|
iTerm2
|
NULL
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
winoowX HubspotYour team is now on the Free plan w winoowX HubspotYour team is now on the Free plan with 1 admin. You retain editing access and other members are read-only. View team permissicas to see who can edit, or ungrade to restore collaborationerpendoneUseful › get history of property - deal stage((baseUri))/deats/V1/deal/494058190045?includePropertyVersionstrucE Docs Params • Authorization • Headers 12)SettinasQuery ParamsinciuderropertyverstonsobiectTyeV COLLECYIONS> HubsootKeration tun hsteration run Searchts› Journal & webhocoks v4• Poperiesv a crm/vs xoverties ob ect tvoe> (t batchacouos> (a(property Name)y ut Resd all propertiesca successful operationAn ertor occurredroneresle a properRESSAREH• СЕAРCH> Tckev Useful> rost tilter per comoanyonly ooen deal staoes.cEt engagements old associated by deawenanacmmnts dd nscocintnd oy comasnv сEt get history of property - deal stagenosuccasstul operation55. An error occurred.at get usersCET SF osuthauweeting cutcomes cer mectinowpond all aranortios nou.> ct Resd all properties okeсT old call dispositionset list with associationscEt list engagements okuuirecentencsaementCET get dealcEt Get Engagement (v1)PATCH https://api.hubapi.com/engagements/V1/engagements/2492739S231Parckhttos:/api.hubaoi.com/crm/vs/co.ects/meet.nos/2497k5x3%wTchttosdllanihubani. com/ancacamantslaoonoamaatc/240273052811Ciodstedessa00CMMIDANIENTCSPECS> FLOWSOConndettCoasde em aniooRoduKEJSONvPreview Visualize"hs deal stage probability".useTinestaspAsPersistenceTimestamp": true,"sourceUpstreanDeployable*:-"ForecastingKafka-deal-stage-probability-workezdenu stare oroodosbstty"DealStageProbabilityHandler",Huserrswrsi@ Searcha menim m sordCoe hitoroore eCEr RendCedet meetino4o7o0sLXThu 28 May 19:28:47et eonther with mhR SaveDetcrictionSondCookiesp.YKEOValuttruestad.700 ok. 270ms. 41.76 KRen Save Resnons?=019As ab.* 70122kHIGiobnts Montt Tookenem...
|
NULL
|
-1374538177591003150
|
NULL
|
click
|
ocr
|
NULL
|
winoowX HubspotYour team is now on the Free plan w winoowX HubspotYour team is now on the Free plan with 1 admin. You retain editing access and other members are read-only. View team permissicas to see who can edit, or ungrade to restore collaborationerpendoneUseful › get history of property - deal stage((baseUri))/deats/V1/deal/494058190045?includePropertyVersionstrucE Docs Params • Authorization • Headers 12)SettinasQuery ParamsinciuderropertyverstonsobiectTyeV COLLECYIONS> HubsootKeration tun hsteration run Searchts› Journal & webhocoks v4• Poperiesv a crm/vs xoverties ob ect tvoe> (t batchacouos> (a(property Name)y ut Resd all propertiesca successful operationAn ertor occurredroneresle a properRESSAREH• СЕAРCH> Tckev Useful> rost tilter per comoanyonly ooen deal staoes.cEt engagements old associated by deawenanacmmnts dd nscocintnd oy comasnv сEt get history of property - deal stagenosuccasstul operation55. An error occurred.at get usersCET SF osuthauweeting cutcomes cer mectinowpond all aranortios nou.> ct Resd all properties okeсT old call dispositionset list with associationscEt list engagements okuuirecentencsaementCET get dealcEt Get Engagement (v1)PATCH https://api.hubapi.com/engagements/V1/engagements/2492739S231Parckhttos:/api.hubaoi.com/crm/vs/co.ects/meet.nos/2497k5x3%wTchttosdllanihubani. com/ancacamantslaoonoamaatc/240273052811Ciodstedessa00CMMIDANIENTCSPECS> FLOWSOConndettCoasde em aniooRoduKEJSONvPreview Visualize"hs deal stage probability".useTinestaspAsPersistenceTimestamp": true,"sourceUpstreanDeployable*:-"ForecastingKafka-deal-stage-probability-workezdenu stare oroodosbstty"DealStageProbabilityHandler",Huserrswrsi@ Searcha menim m sordCoe hitoroore eCEr RendCedet meetino4o7o0sLXThu 28 May 19:28:47et eonther with mhR SaveDetcrictionSondCookiesp.YKEOValuttruestad.700 ok. 270ms. 41.76 KRen Save Resnons?=019As ab.* 70122kHIGiobnts Montt Tookenem...
|
87892
|
NULL
|
NULL
|
NULL
|
|
87892
|
3001
|
25
|
2026-05-28T16:28:30.609426+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985710609_m2.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"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,"bounds":{"left":0.36635637,"top":0.17478053,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","depth":4,"bounds":{"left":0.37632978,"top":0.17478053,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.3879654,"top":0.17318435,"width":0.00731383,"height":0.018355945},"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.39527926,"top":0.17318435,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","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":"22","depth":4,"bounds":{"left":0.6363032,"top":0.10055866,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.64827126,"top":0.10055866,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.65791225,"top":0.09896249,"width":0.00731383,"height":0.018355945},"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.66522604,"top":0.09896249,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","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.011968086,"top":0.047885075,"width":0.024268618,"height":0.024740623},"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}]...
|
3808456254828495905
|
5959254332685757060
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87889
|
3001
|
24
|
2026-05-28T16:28:24.493381+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985704493_m2.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
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.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"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}]...
|
-1036505436057061937
|
-8706354890773656634
|
typing_pause
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
rapstomEV favscojs ~ProjectvViewNeweNNC#12121 on JY-20963-fix-InCoocWindow› E Merge© HubspotWebhooiMetriPropertyChangeManaguvalohtwohooktoG WebhookAssociationGlwalennedwityCimbdlo.orgy uimaeumyociwiceon€ ServiceTest.php@ CachedCrmServiceDecorator.phpo Prossceruochid.pnoooonurwowncaion© HubspotLastModifiedCreatedRecentiyOpenSyncStrateay.ohg© PayloadBulider.php x© WebhookDeletionHandwewokvents© WebhookMergeHandleclass PayloadbuzldenA8X25 Av© WebhookPropertyChan 689C WeohookSionatureVa© BatchSynceollector.phpc) Batchsuncred sservice o© Client.phpC) Cosed Dea [EMAIL]) Decorate chmm cho©FieldDefinitions.phpCrAcTvaAeoousreoodHubspotClientinterface.ph© [EMAIL]© RemoteCrmObjectManipulResponseNormaize.php© Service.php© SyncFieldAction.php© SyncRelatedActivity Mana, 697© WebhookSyncBatchProce> E IntegrationApp>Elisteners> @ Metadata› E Migration› 0 PipedriveE Salesforce> D Fields› E OpportunityMatcher› OpportunitySyncStrategye SemicetiraitsCeentond©DecorateActivity.phpbele eocectetie tonocseldoe inittons cnoc Paviosd Bulldes.ono© [EMAIL] Ouorvitorstoe nha©QueryResuits.phpci Connno nhr71089* Generate a payload to search for contacts by name.*The searchois a token search sin dinstnane on uostnend3 893public function generateSearchContactsByNanePayLoad(string Snane, array $fiolds): array{....95Susagespublic function buildAddAssociationPayload(string Scraid, array Sids, int SassociationType): arrayl »7public function addClosedStageFilters(array &Spayload, array SclosedStages): void"propertyNane' => "dealstage'."oneator'values' => SclosedStages[ 'lost'].117118public function addGreatedDateFilters(array &Spayload, Carbon ScreatedAfter): voidf...10 usagespublic function getDealsInBulkPayLoad(array SdealIds): array(...}BUMMEMEMME85d-entity // View pull request (today 16:12)A SF jiminny@localhost]HS.Jocal [iminny@localhost)A consoie (EU]© PropertyChangeManager.phpxusers (EU)readonly class PropertyChangeManagenA console [PROD)A console (STAGING)TNY.AVself::0BJECT_TYPE_CONTACT →> [// Add contact properties that support direct updateself::OBJECT_TYPE_COMPANY »>[// Add company properties that support direct update* Napping from HubSpot property names to Jiminny model property names.* Used when updating the main model (Opportunity, Contact, Account) directly.* OnZy needed when Hubspot property nane differs fron jiminny property name.*/private const array OBJECT_PROPERTY_MAPPINGS = LCascade & VICommand'dealgang' »> 'nane', // HubSpot "dealnane' naps to Opportunity 'name)=private BatchSyncCollector SbatchCollector,private OpportunityRepository SopportunityRepository.orsvate FleldhataRenos.tony SsieidhataRenost tomy.private HubspotWebhookMetricsService SnetricsService,* Get contact fields that webhooks are subscribed to in HubSpot.— Thie conuse de dosnontatton hd tho cuanont cohhanh Conficunntion$0 l100% KSa- 8• Thu 28 May 19:28:24ServiceTestvCascadeles Orcnnworeebeeionhnves ohtine oDon+0.Unless the May 20 sync used a cachedClosedDea lStages that was populated earlier in the same batch lob — before a importStages () call updated thestage probability from 0 to 100. But that would require stage 20616 to have been at probability 0 at the start of that batch run, then changed to 100 mid-runby tecortStases(.And ieportstanesontyrunsThe true, detinitive answenAfer all this ansves, the most"kely exolonstion is this is a data snaoshot from an eanter time,t ihe opoortunty was sunoed when closedlost harprobability 0 (before May 4, 2026). Then someone manually changed the stage probability to 100 on May 4 in Jiminry. But the opportunity hasn't been re-synced since then - it shows opdated_at: 2826-65-20 but that could be from a different field being updated (like dealname, value, etc.) via the Propertychanackanager's dircct uodate path, which does Not recalculate is. wonLook at PropertyChangekschinono looea luareciupdatea PropertychUoontc boock procchisy trwootne cxstsCoronerMnoosros& CeTeiEeT PROPERN MAPDNSRANORFMNMPE DEAETe1t (isset(SpropertyMappings (SpropertyNase))) <Sthis-sopportunityRepository->update0rCreate(.):odste weld darSthis->inportObjectFieldData(...):return true;D8_OBJECT_UPOATE_PROPERTIES for deals = ['dealnane', "description']. if a dealnase or description webhook event came in on May 20, it would:1. Update nase on the opportunity (via updateOrCreate) → touches updated_at2. Return true (bypassing the full hand leübiectSync / batch queue path3. NOT recalculate 15,vocThis is the answer. On May 20, a dralnase or description change webhook arrived. PropertyChangeManaoer: :handleDralDirectUpdate ran, undatecthe opportunity's nane field (touching updated_at to 2026-05-28 18:36:59 ), and returned true - skipping the full batch sync that would haverecalulated 1s von. The dears 1s,von was already & from a previous syne (when elosedlost had probability 0, before May 4), and the May 20 direct-update webhook dionthxkSummaryTine ooocturynsywna1. Before May 4: Stage 20616 (closmdlost) had probability = 8 in Jiminny's DB (consistent with HubSpot's default behavior for a stage named"closedlost"). Any sync at that time would put "closedlost* in lost() → 15_closedel, i5,vonne.2. May 4: Someone manually updated the stage probability to 100 in Jiminny DB (and/or HubSpot updated their stage label/settings). Stage undateal.ate2826-85-043. May 20: A HubSpot webhook for dealnase or description property change arrived for this deal. Prcndleocaldi rectUpdatfired - it updated the opportunity's nane field directly (touching updated_at ) but returned true without queuing a full sync. 15 von was neverrecalculated4. Result: updated_at: 2826-85-28 looks recent, but the is_von value is stale from a sync that happened before May 4 when the stage probability wasstilllotthe tixis to troac a troch sune df thie sond ic anoortunity: sync0noortun ty(404958190945*) wotld tetch ttrom Hub Soot soo denlstran - "closedlos", find it in wontl (probablity 100 now), and set 15,Mon + 1.ok i still don't get it. Atter I run manual command to php artisan crmi-sync-opportunity - teamid 55 --opportunityld 494058190045 the opportunity is_wonekorchurelrne kaskeliah2 4 spa...
|
87886
|
NULL
|
NULL
|
NULL
|
|
87886
|
3001
|
23
|
2026-05-28T16:28:19.222137+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985699222_m2.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
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.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"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}]...
|
-1365964065509732424
|
-8708606759306818624
|
typing_pause
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
rapstomEV faVsco,ls ~ProjectvViewNeweNNC#12121 on JY-20963-fix-InCoocWindow› E Merge© HubspotWebhooiMetriPropertyChangeManaguvalohtwohooktoG WebhookAssociationGlwalennedwityCimbdlo.orgy uimaeumyociwiceon© ServiceTest.php@ CachedCrmServiceDecorator.phpo Prossceruochid.pnoooonurwowncaion© HubspotLastModifiedCreatedRecentiyOpenSyncStrateay.ohg© PayloadBulider.phpx© WebhookDeletionHandwewokvents© WebhookMergeHandleclass PayloadbuzldenA8X25 Av© WebhookPropertyChan 689C WeohookSionatureVa© BatchSynceollector.phpc) Batchsuncred sservice o© Client.phpC) Cosed Dea [EMAIL]) Decorate chmm cho©FieldDefinitions.phpCrAcTvaAeoousreoodHubspotClientinterface.ph© [EMAIL]© RemoteCrmObjectManipulResponseNormaize.php© Service.php© SyncFieldAction.php© SyncRelatedActivity Mana, 697© WebhookSyncBatchProce> E IntegrationApp>Elisteners> @ Metadata› E Migration› 0 PipedriveE Salesforce> D Fields› E OpportunityMatcher› OpportunitySyncStrategye SemicetiraitsCeentond©DecorateActivity.phpbele eocectetie tonocseldoe inittons cnoc Paviosd Bulldes.ono© [EMAIL] Ouorvitorstoe nha©QueryResuits.phpci Connno nhr71089* Generate a payload to search for contacts by name.*The searchois a token search sin dinstnane on uostnend3 893public function generateSearchContactsByNanePayLoad(string Snane, array $fiolds): array{....955usagespublic function buildAddAssociationPayload(string Scraid, array Sids, int SassociationType): arrayl »7public function addClosedStageFilters(array &Spayload, array SclosedStages): void"propertyNane' => "dealstage'."oneator'values' => SclosedStages[ 'lost'].117118public function addGreatedDateFilters(array &Spayload, Carbon ScreatedAfter): voidf...10 usagespublic function getDealsInBulkPayLoad(array SdealIds): array(...}BUMMEMEMME85d-entity // View pull request (today 16:12)A SF jiminny@localhost]HS.Jocal [iminny@localhost)A console (EU]© PropertyChangeManager.phpxB users (EU)readonly class PropertyChangeManagerA console [PROD)A console (STAGING)TNw.AYself::0BJECT_TYPE_CONTACT →> [// Add contact properties that support direct updateself::OBJECT_TYPE_COMPANY »>[// Add company properties that support direct update* Napping from HubSpot property names to Jiminny model property names.* Used when updating the main model (Opportunity, Contact, Account) directly.* OnZy needed when Hubspot property nane differs fron jiminny property name.*/private const array OBJECT_PROPERTY_MAPPINGS = LCascade & VICommand'dealgang' »> 'nane', // HubSpot "dealnane' naps to Opportunity 'name)=private BatchSyncCollector SbatchCollector,private OpportunityRepository SopportunityRepository.orsvate FleldhataRenos.tony SsieidhataRenost tomy.private HubspotWebhookMetricsService SnetricsService,* Get contact fields that webhooks are subscribed to in HubSpot.— Thie conuse de dosnontatton hd tho cuanont cohhanh Conficunntion$0 l100% KSa- 8• Thu 28 May 19:28:18ServiceTestvCascadeles Orcnnworeebeeionhnves ohtine oDon+0.Unless the May 20 sync used a cachedClosedDea lStages that was populated earlier in the same batch lob — before a importStages () call updated thestage probability from 0 to 100. But that would require stage 20616 to have been at probability 0 at the start of that batch run, then changed to 100 mid-runby tecortStases(.And ieportstanesontyrunsThe true, detinitive answenAfer all this ansves, the most"kely exolonstion is this is a data snaoshot from an eanter time,t ihe opoortunty was sunoed when closedlost harprobability 0 (before May 4, 2026). Then someone manually changed the stage probability to 100 on May 4 in Jiminry. But the opportunity hasn't been re-synced since then - it shows opdated_at: 2826-65-20 but that could be from a different field being updated (like dealname, value, etc.) via the Propertychanackanager's dircct uodate path, which does Not recalculate is. wonLook at PropertyChangekschinono looea luareciupdatea PropertychUoontc boock procchisy trwootne cxstsCoronerMnoosros& CeTeiEeT PROPERN MAPDNSRANORFMNMPE DEAETe1t (isset(SpropertyMappings (SpropertyNase))) <Sthis-sopportunityRepository->update0rCreate(.):odste weld darSthis->inportObjectFieldData(...):return true;D8_OBJECT_UPOATE_PROPERTIES for deals = ['dealnane', "description']. if a dealnase or description webhook event came in on May 20, it would:1. Update nase on the opportunity (via updateOrCreate) → touches updated_at2. Return true (bypassing the full hand leübiectSync / batch queue path3. NOT recalculate 15,vocThis is the answer. On May 20, a dralnase or description change webhook arrived. PropertyChangeManaoer: :handleDralDirectUpdate ran, undatecthe opportunity's nane field (touching updated_at to 2026-05-28 18:36:59 ), and returned true - skipping the full batch sync that would haverecalulated 1s von. The dears 1s,von was already & from a previous syne (when elosedlost had probability 0, before May 4), and the May 20 direct-update webhook dionthxkSummaryTine ooocurynsywns1. Before May 4: Stage 20616 (closmdlost) had probability = 8 in Jiminny's DB (consistent with HubSpot's default behavior for a stage named"closedlost"). Any sync at that time would put "closedlost* in lost() → 15_closedel, i5,vonne.2. May 4: Someone manually updated the stage probability to 100 in Jiminny DB (and/or HubSpot updated their stage label/settings). Stage undateal.ate2826-85-043. May 20: A HubSpot webhook for dealnase or description property change arrived for this deal. Prcndleocaldi rectUpdatfired - it updated the opportunity's nane field directly (touching updated_at ) but returned true without queuing a full sync. 15 von was neverrecalculated4. Result: updated_at: 2826-85-28 looks recent, but the is_von value is stale from a sync that happened before May 4 when the stage probability wasstilllotthe tixis to troac a troch sune df thie sond ic anoortunity: sync0noortun ty(404958190945*) wotld tetch ttrom Hub Soot soo denlstran - "closedlos", find it in wontl (probablity 100 now), and set 15,Mon + 1.ok i still don't get it. Atter I run manual command to php artisan crmi-sync-opportunity - teamid 55 --opportunityld 494058190045 the opportunity is_wonто вегорат усковеск озат. ро в-10. aoste вnол yл ti hoe coa n ou.Konchurelins "arkeliah2 4 spao...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87884
|
3001
|
22
|
2026-05-28T16:28:15.337098+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985695337_m2.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"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,"bounds":{"left":0.36635637,"top":0.17478053,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","depth":4,"bounds":{"left":0.37632978,"top":0.17478053,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"}]...
|
682789680577023509
|
-8708624335957161150
|
typing_pause
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
rapstomEV faVsco,ls ~ProjectvViewNeweNNC#12121 on JY-20963-fix-InCoocWindow› E Merge© HubspotWebhooiMetriPropertyChangeManaguvalohtwohooktoG WebhookAssociationGlwalennedwityCimbdlo.orgy uimaeumyociwiceon© ServiceTest.php@ CachedCrmServiceDecorator.phpo Frosserosehid.onpooonurwowncaion© HubspotLastModifiedCreatedRecentiyOpenSyncStrateay.ohg© PayloadBulider.php x© WebhookDeletionHandwewokvents© WebhookMergeHandleclass PayloadbuzldenA8X25 Av© WebhookPropertyChan 689C WeohookSionatureVa© BatchSynceollector.phpc) Batchsuncred sservice o© Client.phpC) Cosed Dea [EMAIL]) Decorate chmm cho©FieldDefinitions.phpCrAcTvaAeoousreoodHubspotClientinterface.ph© [EMAIL]© RemoteCrmObjectManipulResponseNormaize.php© Service.php© SyncFieldAction.php© SyncRelatedActivity Mana, 697© WebhookSyncBatchProce> E IntegrationApp>Elisteners> @ Metadata› E Migration› 0 PipedriveE Salesforce> D Fields› E OpportunityMatcher› OpportunitySyncStrategyeSemicetiraitsCeentond©DecorateActivity.phpbele eocectetie tonocseldae initons choc Paviosd Bulldes.ono© [EMAIL] Ouorvitorstoe nha©QueryResuits.phpci Connno nhr71089* Generate a payload to search for contacts by name.*The searchois a token search sin dinstnane on uostnend3 893public function generateSearchContactsByNanePayLoad(string Snane, array $fiolds): arrayl....955usagespublic function buildAddAssociationPayload(string Scraid, array Sids, int SassociationType): arrayl »7public function addClosedStageFilters(array &Spayload, array SclosedStages): void"propertyName' = "dealstase","oneator'values' => SclosedStages[ 'lost'].117118Usdouspublic function addGreatedDateFilters(array &Spayload, Carbon ScreatedAfter): voidf...10 usagespublic function getDealsInBulkPayLoad(array SdealIds): array(...}BUMMEMEMME85id-entity // View pull request (today 16:12)A SF jiminny@localhost]HS.Jocal [iminny@localhost)A consoie (EU]© PropertyChangeManager.phpxusers (EU)readonly class PropertyChangeManagenA console [PROD)A console (STAGING)TNw.AYself::0BJECT_TYPE_CONTACT →> [// Add contact properties that support direct updateself::OBJECT_TYPE_COMPANY »>[// Add company properties that support direct update* Napping from HubSpot property names to Jiminny model property names.* Used when updating the main model (Opportunity, Contact, Account) directly.* OnZy needed when Hubspot property nane differs fron jiminny property name.*/private const array OBJECT_PROPERTY_MAPPINGS = LCascade & VICommand'dealgang' »> 'nane', // HubSpot "dealnane' naps to Opportunity 'name)=private BatchSyncCollector SbatchCollector,private OpportunityRepository SopportunityRepository,orsvate FleldhataRenos.tony SsieidhataRenost tomy.private HubspotWebhookMetricsService SnetricsService,* Get contact fields that webhooks are subscribed to in HubSpot.— Thie conuse de dosnontatton hd tho cuanont cohhanh Conficunntion$0 l100% KSa- 8• Thu 28 May 19:28:15ServiceTestvCascadeles Orcnnworeebeeionhnves ohtine oDon+0.Unless the May 20 sync used a cachedClosedDea lStages that was populated earlier in the same batch lob — before a importStages () call updated thestage probability from 0 to 100. But that would require stage 20616 to have been at probability 0 at the start of that batch run, then changed to 100 mid-runby tecortStases(.And ieportstanesontyrunsThe true, detinitive answenAfer all this ansves, the most"kely exolonstion is this is a data snaoshot from an eanter time,t ihe opoortunty was sunoed when closedlost harprobability 0 (before May 4, 2026). Then someone manually changed the stage probability to 100 on May 4 in Jiminry. But the opportunity hasn't been re-synced since then - it shows opdated_at: 2826-65-28 but that could be from a different field being updated (like dealnane, value, etc.) via the Propertychanackanager's dircct uodate path, which does Not recalculate is wonLook at PropertyChangeksnehinond looea luarectupdatea PropertychUoontc boock procchisy trwootne cxstsCRooerMRoosCos& CeTTeOEeI PROPERN MAPPISRANAHORFMNNPE OEATNEh1t (isset(SpropertyMappings (SpropertyNase))) <Sthis-sopportunityRepository->update0rCreate(..);odste weld darSthis->inportObjectFieldData(...):return true;D8_OBJECT_UPOATE_PROPERTIES for deals = ['dealnane', "description']. if a dealnase or description webhook event came in on May 20, it would:1. Update nase on the opportunity (via updateOrCreate) → touches updated_at2. Return true (bypassing the full hand leöbiectSync / batch queue path3. NOT recalculate 15,vocThis is the answer. On May 20, a dealnane or description change webhook arrived. PropertyChangeManager::handLeDealDirectUpdate ran, updatedthe opportunity's nane field (touching updated_at to 2026-05-28 18:36:59 ), and returned true - skipping the full batch sync that would haverecalulated 1s von. The dear's 1s,von was already 8 from a previous syne (when Closedlost had probability 0, before May 4), and the May 20 direct-update weohook oiontfixkSummaryTine ooocurynsywns1. Before May 4: Stage 20616 (closmdlost) had probability = 8 in Jiminny's DB (consistent with HubSpot's default behavior for a stage named"closedlost"). Any sync at that time would put "closedlost* in tostl) → 15_closedel, i5,vonne.2. May 4: Someone manually updated the stage probability to 100 in Jiminny DB (and/or HubSpot updated their stage label/settings). Stage undateal.ate2826-85-043. May 20: A HubSpot webhook for dealnase or description property change arrived for this deal. Prcndleocaldi rectUpdatfired - it updated the opportunity's nane field directly (touching updated_at ) but returned true without queuing a full sync. 15 von was neverrecalculated4. Result: updated_at: 2826-85-28 looks recent, but the is_von value is stale from a sync that happened before May 4 when the stage probability wasstilllotthe tixis to troac a troch sune df thie sond ic anoortunity: sync0noortun ty(404958190945*) wotld tetch ttrom Hub Soot soo denlstran - "closedlos", find it in wontl (probablity 100 now), and set 15,Mon + 1.Eyceed otare cherce ia ine ip oaryoa (oiteo.)Korchurellne kaskelhiroh2 4 spao...
|
87882
|
NULL
|
NULL
|
NULL
|
|
87882
|
3001
|
21
|
2026-05-28T16:28:12.040331+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985692040_m2.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"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,"bounds":{"left":0.36635637,"top":0.17478053,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","depth":4,"bounds":{"left":0.37632978,"top":0.17478053,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.3879654,"top":0.17318435,"width":0.00731383,"height":0.018355945},"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.39527926,"top":0.17318435,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-7963540551006488554
|
-8669200539060040766
|
typing_pause
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
rapstomEV faVsco,ls ~ProjectvViewNeweNNC#12121 on JY-20963-fix-InCoocWindow› E Merge© HubspotWebhooiMetriPropertyChangeManaguvalohtwohooktoG WebhookAssociationGlwalennedwityCimbdlo.orgy uimaeumyociwiceon€ ServiceTest.php@ CachedCrmServiceDecorator.phpo Frosserosehid.onpooonurwowncaion© HubspotLastModifiedCreatedRecentiyOpenSyncStrateay.ohg© PayloadBulider.phpx© WebhookDeletionHandwewokvents© WebhookMergeHandleclass PayloadbuzldenA8X25 Av© WebhookPropertyChan 689C WeohookSionatureVa© BatchSynceollector.phpc) Batchsuncred sservice o© Client.phpC) Cosed Dea [EMAIL]) Decorate chmm cho©FieldDefinitions.phpCrAcTvaAeoousreoodHubspotClientinterface.ph© [EMAIL]© RemoteCrmObjectManipulResponseNormaize.php© Service.php© SyncFieldAction.php© SyncRelatedActivity Mana, 697© WebhookSyncBatchProce> E IntegrationApp>Elisteners> @ Metadata› E Migration› 0 PipedriveE Salesforce> D Fields› E OpportunityMatcher› OpportunitySyncStrategyeSemicetiraitsCeentond©DecorateActivity.phpbele eocectetie tonocseldae initons choc Paviosd Bulldes.ono© [EMAIL] Ouorvitorstoe nha©QueryResuits.phpci Connno nhr71089* Generate a payload to search for contacts by name.*The searchois a token search sin dinstnane on uostnend3 893public function generateSearchContactsByNanePayLoad(string Snane, array $fiolds): arrayl....95Susagespublic function buildAddAssociationPayload(string Scraid, array Sids, int SassociationType): arrayl »7public function addClosedStageFilters(array &Spayload, array SclosedStages): void"propertyNane' => "dealstage'."oneator'values' => SclosedStages[ 'lost'].117118public function addGreatedDateFilters(array &Spayload, Carbon ScreatedAfter): voidf...10 usagespublic function getDealsInBulkPayLoad(array SdealIds): array(...}BUMMEMEMME85id-entity // View pull request (today 16:12)A SF jiminny@localhost]HS.Jocal [iminny@localhost)A consoie (EU]© PropertyChangeManager.phpxusers (EU)readonly class PropertyChangeManagenA console [PROD)A console (STAGING)TNw.AYself::0BJECT_TYPE_CONTACT →> [// Add contact properties that support direct updateself::OBJECT_TYPE_COMPANY »> [// Add company properties that support direct update* Napping from HubSpot property names to Jiminny model property names.* Used when updating the main model (Opportunity, Contact, Account) directly.* OnZy needed when Hubspot property nane differs fron jiminny property name.*/private const array OBJECT_PROPERTY_MAPPINGS = LCascade & VICommand'dealgang' »> 'nane', // HubSpot "dealnane' naps to Opportunity 'name)=$0 l100% KSa- 8• Thu 28 May 19:28:11ServiceTestvCascadeles Orcnnworeebeeionhnves ohtine oDon+0.Unless the May 20 sync used a cachedClosedDea lStages that was populated earlier in the same batch lob — before a importStages () call updated thestage probability from 0 to 100. But that would require stage 20616 to have been at probability 0 at the start of that batch run, then changed to 100 mid-runby tecortStases(.And ieportstanesontyrunsThe true, detinitive answenAfer all this ansves, the most"kely exolonstion is this is a data snaoshot from an eanter time,t ihe opoortunty was sunoed when closedlost harprobability 0 (before May 4, 2026). Then someone manually changed the stage probability to 100 on May 4 in Jiminry. But the opportunity hasn't been re-synced since then - it shows opdated_at: 2826-65-20 but that could be from a different field being updated (like dealname, value, etc.) via the Propertychanackanager's dircct uodate path, which does Not recalculate is. wonLook at PropertyChangekschinono looea luareciupdatea PropertychUoontc boock procchisy trwootne cxstsCoronerMnoosros& CeTeiEeT PROPERN MAPDNSRANORFMNMPE DEAETe1t (isset(SpropertyMappings (SpropertyNase))) <Sthis-sopportunityRepository->update0rCreate(..);odste weld darSthis->inportObjectFieldData(...):return true;D8_OBJECT_UPOATE_PROPERTIES for deals = ['dealnane', "description']. if a dealnase or description webhook event came in on May 20, it would:1. Update nase on the opportunity (via updateOrCreate) → touches updated_at2. Return true (bypassing the full hand leöbiectSync / batch queue path3. NOT recalculate 15,vocThis is the answer. On May 20, a dralnase or description change webhook arrived. PropertyChangeManaoer: :handleDralDirectUpdate ran, undatecthe opportunity's nane field (touching updated_at to 2026-05-28 18:36:59 ), and returned true - skipping the full batch sync that would haverecalulated 1s von. The dear's 1s,von was already 8 from a previous syne (when Closedlost had probability 0, before May 4), and the May 20 direct-update weohook oiontfixkSummaryTine ooocurynsywns1. Before May 4: Stage 20616 (closmdlost) had probability = 8 in Jiminny's DB (consistent with HubSpot's default behavior for a stage named"closedlost"). Any sync at that time would put "closedlost* in tostl) → 15_closedel, i5,vonne.2. May 4: Someone manually updated the stage probability to 100 in Jiminny DB (and/or HubSpot updated their stage label/settings). Stage undateal.ate2826-85-043. May 20: A HubSpot webhook for dealnase or description property change arrived for this deal. Prcndleocaldi rectUpdatfired - it updated the opportunity's nane field directly (touching updated_at ) but returned true without queuing a full sync. 15 von was neverrecalculated4. Result: updated_at: 2826-85-28 looks recent, but the is_von value is stale from a sync that happened before May 4 when the stage probability wasstilllotthe tixis to troac a troch sune df thie sond ic anoortunity: sync0noortun ty(404958190945*) wotld tetch ttrom Hub Soot soo denlstran - "closedlos", find it in wontl (probablity 100 now), and set 15,won + 1private BatchSyncCollector SbatchCollector,private OpportunityRepository SopportunityRepository,orsvate FleldhataRenos.tony SsieidhataRenost tomy.private HubspotWebhookMetricsService SnetricsService,* Get contact fields that webhooks are subscribed to in HubSpot.— Thie conuse de dosnontatton hd tho cuanont cohhanh Conficunntionekorchurelrne kaskeliah2 4 spao...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87878
|
3001
|
20
|
2026-05-28T16:28:10.970372+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985690970_m2.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"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,"bounds":{"left":0.36635637,"top":0.17478053,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","depth":4,"bounds":{"left":0.37632978,"top":0.17478053,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.3879654,"top":0.17318435,"width":0.00731383,"height":0.018355945},"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.39527926,"top":0.17318435,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","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":"22","depth":4,"bounds":{"left":0.6363032,"top":0.10055866,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.64827126,"top":0.10055866,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.65791225,"top":0.09896249,"width":0.00731383,"height":0.018355945},"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.66522604,"top":0.09896249,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","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.011968086,"top":0.047885075,"width":0.024268618,"height":0.024740623},"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}]...
|
3808456254828495905
|
5959254332685757060
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
87877
|
NULL
|
NULL
|
NULL
|
|
87877
|
3001
|
19
|
2026-05-28T16:28:09.795083+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985689795_m2.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"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,"bounds":{"left":0.36635637,"top":0.17478053,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","depth":4,"bounds":{"left":0.37632978,"top":0.17478053,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.3879654,"top":0.17318435,"width":0.00731383,"height":0.018355945},"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.39527926,"top":0.17318435,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","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":"22","depth":4,"bounds":{"left":0.6363032,"top":0.10055866,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.64827126,"top":0.10055866,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.65791225,"top":0.09896249,"width":0.00731383,"height":0.018355945},"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.66522604,"top":0.09896249,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","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.011968086,"top":0.047885075,"width":0.024268618,"height":0.024740623},"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}]...
|
-4934908395381711432
|
5959254332685757060
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87875
|
3001
|
18
|
2026-05-28T16:28:08.011325+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985688011_m2.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"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,"bounds":{"left":0.36635637,"top":0.17478053,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","depth":4,"bounds":{"left":0.37632978,"top":0.17478053,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.3879654,"top":0.17318435,"width":0.00731383,"height":0.018355945},"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.39527926,"top":0.17318435,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","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":"22","depth":4,"bounds":{"left":0.6363032,"top":0.10055866,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.64827126,"top":0.10055866,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.65791225,"top":0.09896249,"width":0.00731383,"height":0.018355945},"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.66522604,"top":0.09896249,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","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.011968086,"top":0.047885075,"width":0.024268618,"height":0.024740623},"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}]...
|
3808456254828495905
|
5959254332685757060
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
87873
|
NULL
|
NULL
|
NULL
|
|
87873
|
3001
|
17
|
2026-05-28T16:27:57.595551+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985677595_m2.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-824022620702545522
|
-9103533727753729596
|
typing_pause
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
rapstomEV faVsco,ls ~ProjectvViewNeweNNC#12121 on JY-20963-fix-InCoocWindow› E Merge© HubspotWebhooiMetriPropertyChangeManaguvalohtwohooktoG WebhookAssociationGlwalennedwityCimbdlo.orgy uimaeumyociwiceon© ServiceTest.php@ CachedCrmServiceDecorator.phpo Frosserosehid.onpooonurwowncaion© HubspotLastModifiedCreatedRecentiyOpenSyncStrateay.ohg© PayloadBulider.phpx© WebhookDeletionHandwewokvents© WebhookMergeHandleclass PayloadbuzldenA8X25 Av© WebhookPropertyChan 689C WeohookSionatureVa© BatchSynceollector.phpc) Batchsuncred sservice o© Client.phpC) Cosed Dea [EMAIL]) Decorate chmm cho©FieldDefinitions.phpCrAcTvaAeoousreoodHubspotClientinterface.ph© [EMAIL]© RemoteCrmObjectManipulResponseNormaize.php© Service.php© SyncFieldAction.php© SyncRelatedActivity Mana, 697© WebhookSyncBatchProce> E IntegrationApp>Elisteners> @ Metadata› E Migration› 0 PipedriveE Salesforce> D Fields› E OpportunityMatcher› OpportunitySyncStrategyeSemicetiraitsC e entond©DecorateActivity.phpbele eocectetie tonocseldae initons choc Paviosd Bulldes.ono© [EMAIL] Ouorvitorstoe nha©QueryResuits.phpci Connno nhr71089* Generate a payload to search for contacts by name.*The searchois a token search sin dinstnane on uostnend3 893public function generateSearchContactsByNanePayLoad(string Snane, array $fiolds): arrayl....95Susagespublic function buildAddAssociationPayload(string Scraid, array Sids, int SassociationType): arrayl »7public function addClosedStageFilters(array &Spayload, array SclosedStages): void"propertyName' = "dealstase","oneator'values' => SclosedStages[ 'lost'].117118public function addGreatedDateFilters(array &Spayload, Carbon ScreatedAfter): voidf...10 usagespublic function getDealsInBulkPayLoad(array SdealIds): array{...}BUMMEMEMME85id-entity // View pull request (today 16:12)A SF jiminny@localhost]HS.Jocal [iminny@localhost)A consoie (EU]© PropertyChangeManager.phpxusers (EU)readonly class PropertyChangeManagenA console [PROD)A console (STAGING)TNw.AYself::0BJECT_TYPE_CONTACT →> [// Add contact properties that support direct updateself::OBJECT_TYPE_COMPANY »>[// Add company properties that support direct update* Napping from HubSpot property names to Jiminny model property names.* Used when updating the main model (Opportunity, Contact, Account) directly.* OnZy needed when Hubspot property nane differs fron jiminny property name.*/private const array OBJECT_PROPERTY_MAPPINGS = LCascade & VICommand'dealgang' »> 'nane', // HubSpot "dealnane' naps to Opportunity 'name)=$0 l100% KSa- • Thu 28 May 19:27:57ServiceTestvCascadeles Orcnnworeebeeionhnves ohtine oDon+0.Unless the May 20 sync used a cachedClosedDea lStages that was populated earlier in the same batch lob — before a importStages () call updated thestage probability from 0 to 100. But that would require stage 20616 to have been at probability 0 at the start of that batch run, then changed to 100 mid-runby tecortStases(.And ieportstanesontyrunsThe true, detinitive answenAfer all this ansves, the most"kely exolonstion is this is a data snaoshot from an eanter time,t ihe opoortunty was sunoed when closedlost harprobability 0 (before May 4, 2026). Then someone manually changed the stage probability to 100 on May 4 in Jiminry. But the opportunity hasn't been re-synced since then - it shows opdated_at: 2826-65-20 but that could be from a different field being updated (like dealname, value, etc.) via the Propertychanackanager's dircct uodate path, which does Not recalculate is. wonLook at PropertyCharhinonio Looea luareciupdatea PropertyChUoonte bocck procchirttne CxistCoronerMnoosros& CeTeiEeT PROPERN MAPDNSRANORFMNMPE DEAETe1t (isset(SpropertyMappings (SpropertyNase))) <Sthis-sopportunityRepository->update0rCreate(..);odste weld darSthis->inportObjectFieldData(...):return true;D8_OBJECT_UPOATE_PROPERTIES for deals = ['dealnane', "description']. if a dealnase or description webhook event came in on May 20, it would:1. Update nase on the opportunity (via updateOrCreate) → touches updated_at2. Return true (bypassing the full hand leöbiectSync / batch queue path3. NOT recalculate 15,vocThis is the answer. On May 20, a dralnase or description change webhook arrived. PropertyChangeManaoer: :handleDralDirectUpdate ran, undatecthe opportunity's nane field (touching updated_at to 2026-05-28 18:36:59 ), and returned true - skipping the full batch sync that would haverecalulated 1s von. The dear's 1s,von was already 8 from a previous syne (when Closedlost had probability 0, before May 4), and the May 20 direct-update weohook oiontfixkSummaryTine ooocturynsywna1. Before May 4: Stage 20616 (closmdlost) had probability = 8 in Jiminny's DB (consistent with HubSpot's default behavior for a stage named"closedlost"). Any sync at that time would put "closedlost* in tostl) → 15_closedel, i5,vonne.2. May 4: Someone manually updated the stage probability to 100 in Jiminny DB (and/or HubSpot updated their stage label/settings). Stage undateal.ate2826-85-043. May 20: A HubSpot webhook for dealnase or description property change arrived for this deal. Prndleocaldi rectUpdatfired - it updated the opportunity's nane field directly (touching updated_at ) but returned true without queuing a full sync. 15 von was neverrecalculated4. Result: updated_at: 2826-85-28 looks recent, but the is_von value is stale from a sync that happened before May 4 when the stage probability wasstilllotthe tixis to troac a troch sune df thie sond ic anoortunity: sync0noortun ty(404958190945*) wotld tetch ttrom Hub Soot soo denlstran - "closedlos", find it in wontl (probablity 100 now), and set 15,won + 1private BatchSyncCollector SbatchCollector,private OpportunityRepository SopportunityRepository,orsvate FleldhataRenos.tony SsieidhataRenost tomy.private HubspotWebhookMetricsService SnetricsService,* Get contact fields that webhooks are subscribed to in HubSpot.— Thie conuse de dosnontatton hd tho cuanont cohhanh Conficunntiondirect upaate chaon 2028-05-06 | modttes the dhange in staroser Hubanot (ft saeer ie ott 1ee-18 00 () probe inou. d syne the teroie d how could100-5 (395 chars, 10 line breaks) UTF-82 4 spa...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87871
|
3001
|
16
|
2026-05-28T16:27:51.927800+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985671927_m2.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-7617337236921633572
|
-8635159314967324256
|
typing_pause
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
rapstomEV faVsco,ls ~ProjectvViewNeweNNC#12121 on JY-20963-fix-InCoocWindow› E Merge© HubspotWebhooiMetriPropertyChangeManaguvalohtwohooktoG WebhookAssociationGlwalennedwityCimbdlo.orgy uimaeumyociwiceon© ServiceTest.php@ CachedCrmServiceDecorator.phpo Frosserosehid.onpooonurwowncaion©) HubspotLastModifiedCreatedRecentiyOpenSyncStrateay.ohg© PayloadBulider.phpx© WebhookDeletionHandwewokvents© WebhookMergeHandleclass PayloadbuzldenA8X25 Av© WebhookPropertyChan 689C WeohookSionatureVa© BatchSynceollector.phpc) Batchsuncred sservice o© Client.phpC) Cosed Dea [EMAIL]) Decorate chmm cho©FieldDefinitions.phpCrAcTvaAeoousreoodHubspotClientinterface.ph© [EMAIL]© RemoteCrmObjectManipulResponseNormaize.php© Service.php© SyncFieldAction.php© SyncRelatedActivity Mana, 697© WebhookSyncBatchProce> E IntegrationApp>Elisteners> @ Metadata› E Migration› 0 PipedriveE Salesforce> D Fields› E OpportunityMatcher› OpportunitySyncStrategyeSemicetiraitsC e entond©DecorateActivity.phpbele eocectetie tonocseldae initons choc Paviosd Bulldes.ono© [EMAIL] Ouorvitorstoe nha©QueryResuits.phpci Connno nhr71089* Generate a payload to search for contacts by name.*The searchois a token search sin dinstnane on uostnend3 893public function generateSearchContactsByNanePayLoad(string Snane, array $fiolds): arrayl....95Susagespublic function buildAddAssociationPayload(string Scraid, array Sids, int SassociationType): arrayl »7public function addClosedStageFilters(array &Spayload, array SclosedStages): void"propertyName' = "dealstase","oneator'values' => SclosedStages[ 'lost'].117118Usdouspublic function addGreatedDateFilters(array &Spayload, Carbon ScreatedAfter): voidf...10 usagespublic function getDealsInBulkPayLoad(array SdealIds): array{...}BUMMEMEMME85id-entity // View pull request (today 16:12)A SF jiminny@localhost]HS.Jocal [iminny@localhost)A consoie (EU]© PropertyChangeManager.phpxusers (EU)readonly class PropertyChangeManagenA console [PROD)A console (STAGING)TNw.AYself::0BJECT_TYPE_CONTACT →> [// Add contact properties that support direct updateself::OBJECT_TYPE_COMPANY »>[// Add company properties that support direct update* Napping from HubSpot property names to Jiminny model property names.* Used when updating the main model (Opportunity, Contact, Account) directly.* OnZy needed when Hubspot property nane differs fron jiminny property name.*/private const array OBJECT_PROPERTY_MAPPINGS = LCascade & VICommand'dealgang' »> 'nane', // HubSpot "dealnane' naps to Opportunity 'name)=private BatchSyncCollector SbatchCollector,private OpportunityRepository SopportunityRepository,orsvate FleldhataRenos.tony SsieidhataRenost tomy.private HubspotWebhookMetricsService SnetricsService,* Get contact fields that webhooks are subscribed to in HubSpot.— Thie conuse de dosnontatton hd tho cuanont cohhanh Conficunntion$0 l100% KSa- 8• Thu 28 May 19:27:51ServiceTestvCascadeles Orcnnworeebeeionhnves ohtine oDon+0.Unless the May 20 sync used a cachedClosedDea lStages that was populated earlier in the same batch lob — before a importStages () call updated thestage probability from 0 to 100. But that would require stage 20616 to have been at probability 0 at the start of that batch run, then changed to 100 mid-runby tecortStases(.And ieportstanesontyrunsThe true, detinitive answenAfer all this ansves, the most"kely exolonstion is this is a data snaoshot from an eanter time,t ihe opoortunty was sunoed when closedlost harprobability 0 (before May 4, 2026). Then someone manually changed the stage probability to 100 on May 4 in Jiminry. But the opportunity hasn't been re-synced since then - it shows opdated_at: 2826-65-20 but that could be from a different field being updated (like dealname, value, etc.) via the Propertychanackanager's dircct uodate path, which does Not recalculate is. wonLook at PropertyChanhinonio Looea luareciupdatea PropertyChUoontc boock procchisy trwootne cxstsCoronerMnoosros& CeTeiEeT PROPERN MAPDNSRANORFMNMPE DEAETe1t (isset(SpropertyMappings (SpropertyNase))) <Sthis-sopportunityRepository->update0rCreate(..);odste weld darSthis->inportObjectFieldData(...):return true;D8_OBJECT_UPOATE_PROPERTIES for deals = ['dealnane', "description']. if a dealnase or description webhook event came in on May 20, it would:1. Update nase on the opportunity (via updateOrCreate) → touches updated_at2. Return true (bypassing the full hand leöbiectSync / batch queue path3. NOT recalculate 15,vocThis is the answer. On May 20, a dralnase or description change webhook arrived. PropertyChangeManaoer: :handleDralDirectUpdate ran, undatecthe opportunity's nane field (touching updated_at to 2026-05-28 18:36:59 ), and returned true - skipping the full batch sync that would haverecalulated 1s von. The dear's 1s,von was already 8 from a previous syne (when Closedlost had probability 0, before May 4), and the May 20 direct-update weohook oiontfixkSummaryTine ooocurynsywns1. Before May 4: Stage 20616 (closmdlost) had probability = 8 in Jiminny's DB (consistent with HubSpot's default behavior for a stage named"closedlost"). Any sync at that time would put "closedlost* in tostl) → 15_closedel, i5,vonne.2. May 4: Someone manually updated the stage probability to 100 in Jiminny DB (and/or HubSpot updated their stage label/settings). Stage undateal.ate2826-85-043. May 20: A HubSpot webhook for dealnase or description property change arrived for this deal. Prndleocaldi rectUpdatfired - it updated the opportunity's nane field directly (touching updated_at ) but returned true without queuing a full sync. 15 von was neverrecalculated4. Result: updated_at: 2826-85-28 looks recent, but the is_von value is stale from a sync that happened before May 4 when the stage probability wasstilllotthe tixis to troac a troch sune df thie sond ic anoortunity: sync0noortun ty(404958190945*) wotld tetch ttrom Hub Soot soo denlstran - "closedlos", find it in wontl (probablity 100 now), and set 15,won + 1direct upaate chaon 2028-05-061| modttes the dhannae in staroser Hcbenot (a saeer. ieptt 10-118 00 () booba100-5 (395 chars, 10 fine breaks) UTF-82 4 spad...
|
87867
|
NULL
|
NULL
|
NULL
|
|
87867
|
3001
|
15
|
2026-05-28T16:27:45.825848+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985665825_m2.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"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,"bounds":{"left":0.36635637,"top":0.17478053,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","depth":4,"bounds":{"left":0.37632978,"top":0.17478053,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.3879654,"top":0.17318435,"width":0.00731383,"height":0.018355945},"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.39527926,"top":0.17318435,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","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":"22","depth":4,"bounds":{"left":0.6363032,"top":0.10055866,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.64827126,"top":0.10055866,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.65791225,"top":0.09896249,"width":0.00731383,"height":0.018355945},"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.66522604,"top":0.09896249,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","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.011968086,"top":0.047885075,"width":0.024268618,"height":0.024740623},"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}]...
|
3808456254828495905
|
5959254332685757060
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87865
|
3001
|
14
|
2026-05-28T16:27:37.900660+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985657900_m2.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
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.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
5582423643801155883
|
-8994321436789994556
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
rapstomEV faVsco,ls ~ProjectvViewNeweNNC#12121 on JY-20963-fix-inCoocWindow© ServiceTest.php› E MergewawenacdvityCimDalo.ongy uimaeumyociwiceon@ CachedCrmServiceDecorator.php© HubspotWebhooiMetriPropertyChangeManaguvalohtwohooktoooonurwowncaion©) HubspotLastModifiedCreatedRecentiyOpenSyncStrateay.ohgG WebhookAssociationGlFroseeeuscnid.pint© PayloadBulider.php x© WebhookDeletionHandwewokvents© WebhookMergeHandleclass Payloadbuzlden* Generate a payload to search for contacts by name.*The searchois a token search sin dinstnane on uostnend© WebhookPropertyChan 689C WeohookSionatureVa© BatchSynceollector.phpc) Batchsuncred sservice o© Client.phpC) Cosed Dea [EMAIL]) Decorate chmm cho©FieldDefinitions.phporAdTaAeooueaeoo.HubspotClientinterface.ph© [EMAIL]© RemoteCrmObjectManipulResponseNormaize.php© Service.php© SyncFieldAction.php© SyncRelatedActivity Mana, 697© WebhookSyncBatchProce> E IntegrationApp>Elisteners> @ Metadata› E Migration› 0 PipedriveE Salesforce> D Fields› E OpportunityMatcher› OpportunitySyncStrategyRRER8eSemicetiraitsC e entond©DecorateActivity.phpbele eocectetie tonocseldoe inittons cnoc Paviosd Bulldes.ono© [EMAIL] Ouorvitorstoe nha©QueryResuits.phpci Connno nhr710publio function addCreatedDateFilters(array &Spayload, Carbon ScreatedAfter): voidf..₴210 usagespublic function getDealsInBulkPayLoad(array SdealIds): array(...}d-entity // View pull request (today 16:12)A SF jiminny@localhost]# consolkeuPropertyChangeManager.phpxB users (EU)readonly class PropertyChangeManagenself::0BJECT_TYPE_CONTACT →> [1.// Add contact properties that support direct updateself::OBJECT_TYPE_COMPANY »>[I/ Add company properties that support direct updateA console (STAGING)TNY.AV9192931:=$0 l100% KSa- 8• Thu 28 May 19:27:37ServiceTestvCascadeles Orcnnworeeoeionhnves ohtine oDon+0.Unless the May 20 sync used a cachedClosedDea lStages that was populated earlier in the same batch lob — before a importStages () call updated thestage probability from 0 to 100. But that would require stage 20616 to have been at probability 0 at the start of that batch run, then changed to 100 mid-runby ecortstases(.And ieportstanes only runsThe true, detinitive answenAfer all this ansves, the most"kely exolonstion is this is a data snaoshot from an eanter time,t ihe opoortunty was sunoed when closedlost harprobability 0 (before May 4, 2026). Then someone manually changed the stage probability to 100 on May 4 in Jiminry. But the opportunity hasn't been re-synced since then - it shows opdated_at: 2826-65-20 but that could be from a different field being updated (like dealname, value, etc.) via the Propertychanackanager's dircct uodate path, which does Not recalculate is. wonLook at PropertyChangeMchethanio looea warceiupdatea PropertyChUooatc bouck procchty rbsootne cxistCoronerMnoosros& CeTeiEeT PROPERN MAPDNSRANORFMNMPE DEAETe1t (isset(SpropertyMappings (SpropertyNase))) <Sthis-sopportunityRepository->update0rCreate(.):odste weld darSthis->inportObjectFieldData(...):return true;D8_OBJECT_UPOATE_PROPERTIES for deals = ['dealnane', "description']. if a dealnase or description webhook event came in on May 20, it would:1. Update nase on the opportunity (via updateOrCreate) → touches updated_at2. Return true (bypassing the full hand leübiectSync / batch queue path3. NOT recalculate 15,vocThis is the answer. On May 20, a dralnase or description change webhook arrived. PropertyChangeManaoer: :handleDralDirectUpdate ran, undatecthe opportunity's nane field (touching updated_at to 2026-05-28 18:36:59 ), and returned true - skipping the full batch sync that would haverecalulated 1s von. The dear's 1s,von was already 8 from a previous syne (when elosedlost had probability 0, before May 4), and the May 20 direct-update webhook dionthxkSummaryTine ooocurynsywns1. Before May 4: Stage 20616 (closmdlost) had probability = 8 in Jiminny's DB (consistent with HubSpot's default behavior for a stage named"closedlost"). Any sync at that time would put "closedlost* in tostl) → 15_closedel, i5,vonne.2. May 4: Someone manually updated the stage probability to 100 in Jiminny DB (and/or HubSpot updated their stage label/settings). Stage undateal.ate2826-85-043. May 20: A HubSpot webhook for dealnase or description property change arrived for this deal. Prcndleocaldi rectUpdatfired - it updated the opportunity's nane field directly (touching updated_at ) but returned true without queuing a full sync. 15 von was neverrecalculated4. Result: updated_at: 2826-85-28 looks recent, but the is_von value is stale from a sync that happened before May 4 when the stage probability wasstilllotthe tixis to troac a troch sune df thie sond ic anoortunity: sync0noortun ty(404958190945*) wotld tetch ttrom Hub Soot soo denlstran - "closedlos", find it in wontl (probablity 100 now), and set 15,won + 1ВАЕДДАДАВаЦЕGet contact flolds that webhooks are subsertoes to in tuspor.* This serves as documentation of the current webhook configuration.WindewasetTrnchre Xlline wankelhires2 4 spad...
|
87858
|
NULL
|
NULL
|
NULL
|
|
87858
|
3001
|
13
|
2026-05-28T16:27:15.899195+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985635899_m2.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"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,"bounds":{"left":0.36635637,"top":0.17478053,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","depth":4,"bounds":{"left":0.37632978,"top":0.17478053,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.3879654,"top":0.17318435,"width":0.00731383,"height":0.018355945},"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.39527926,"top":0.17318435,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","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":"22","depth":4,"bounds":{"left":0.6363032,"top":0.10055866,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.64827126,"top":0.10055866,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.65791225,"top":0.09896249,"width":0.00731383,"height":0.018355945},"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.66522604,"top":0.09896249,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","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.011968086,"top":0.047885075,"width":0.024268618,"height":0.024740623},"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}]...
|
3808456254828495905
|
5959254332685757060
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87855
|
3001
|
12
|
2026-05-28T16:27:11.129165+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985631129_m2.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
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.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
5582423643801155883
|
-8994321436789994556
|
typing_pause
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
rapstomEV faVsco,ls ~ProjectvViewNeweNNC#12121 on JY-20963-fix-InCoocWindow© ServiceTest.php› E MergewawenacdvityCimDalo.ongy uimaeumyociwiceon@ CachedCrmServiceDecorator.php© HubspotWebhooiMetriPropertyChangeManaguvalohtwohooktoooonurwowncaion©) HubspotLastModifiedCreatedRecentiyOpenSyncStrateay.ohgG WebhookAssociationGlFroseeeuscnid.pint© PayloadBulider.php x© WebhookDeletionHandwewokvents© WebhookMergeHandleclass Payloadbuzlden* Generate a payload to search for contacts by name.*The searchois a token search sin dinstnane on uostnend© WebhookPropertyChan 689C WeohookSionatureVa© BatchSynceollector.phpc) Batchsuncred sservice o© Client.phpC) Cosed Dea [EMAIL]) Decorate chmm cho©FieldDefinitions.phporAdTaAeooueaeoo.HubspotClientinterface.ph© [EMAIL]© RemoteCrmObjectManipulResponseNormaize.php© Service.php© SyncFieldAction.php© SyncRelatedActivity Mana, 697© WebhookSyncBatchProce> E IntegrationApp>Elisteners> @ Metadata› E Migration› 0 PipedriveE Salesforce> D Fields› E OpportunityMatcher› OpportunitySyncStrategyRRER8eSemicetiraitsCeentond©DecorateActivity.phpbele eocectetie tonocseldoe inittons cnoc Paviosd Bulldes.ono© [EMAIL] Ouorvitorstoe nha©QueryResuits.phpci Connno nhr710publio function addCreatedDateFilters(array &Spayload, Carbon ScreatedAfter): voidf..₴210 usagespublic function getDealsInBulkPayLoad(array SdealIds): array{...}id-entity // View pull request (today 16:12)A SF jiminny@localhost]# consokkeuPropertyChangeManager.phpxB users (EU)readonly class PropertyChangeManagenself::0BJECT_TYPE_CONTACT →> [1.// Add contact properties that support direct updateself::OBJECT_TYPE_COMPANY »>[I/ Add company properties that support direct updateA console (STAGING)TNY.AV92931:=ВАЕДДАДАВаЦЕGet contact flolds that webhooks are subsertoes to in tuspor.* This serves as documentation of the current webhook configuration.50 lN100% KSa- 8• Thu 28 May 19:27:10ServiceTestvCascadeles Orcnnworeeoeionhnves ohtine oDon+0.Unless the May 20 sync used a cachedClosedDea lStages that was populated earlier in the same batch lob — before a importStages () call updated thestage probability from 0 to 100. But that would require stage 20616 to have been at probability 0 at the start of that batch run, then changed to 100 mid-runby ecortstases(.And ieportstanes only runsThe true, detinitive answenAfer all this ansves, the most"kely exolonstion is this is a data snaoshot from an eanter time,t ihe opoortunty was sunoed when closedlost harprobability 0 (before May 4, 2026). Then someone manually changed the stage probability to 100 on May 4 in Jiminry. But the opportunity hasn't been re-synced since then - it shows opdated_at: 2826-65-20 but that could be from a different field being updated (like dealname, value, etc.) via the Propertychanackanager's dircct uodate path, which does Not recalculate is. wonLook at PropertyCharhinonio Looea luareciupdatea PropertychUoonte bouck procchisyuttne CxistCoronerMnoosros& CeTeiEeT PROPERN MAPDNSRANORFMNMPE DEAETe1t (isset(SpropertyMappings (SpropertyNase))) <Sthis-sopportunityRepository->update0rCreate(.):odste weld darSthis->inportObjectFieldData(...):return true;D8_OBJECT_UPOATE_PROPERTIES for deals = ['dealnane', "description']. if a dealnase or description webhook event came in on May 20, it would:1. Update nase on the opportunity (via updateOrCreate) → touches updated_at2. Return true (bypassing the full hand leübiectSync / batch queue path3. NOT recalculate 15,vocThis is the answer. On May 20, a dralnase or description change webhook arrived. PropertyChangeManaoer: :handleDralDirectUpdate ran, undatecthe opportunity's nane field (touching updated_at to 2026-05-28 18:36:59 ), and returned true - skipping the full batch sync that would haverecalulated 1s von. The dear's 1s,von was already 8 from a previous syne (when elosedlost had probability 0, before May 4), and the May 20 direct-update webhook dionthxkSummaryTine ooocurynsywns1. Before May 4: Stage 20616 (closmdlost) had probability = 8 in Jiminny's DB (consistent with HubSpot's default behavior for a stage named"closedlost"). Any sync at that time would put "Closedlost* in tost(] → 15_closedel, is,vonna.2. May 4: Someone manually updated the stage probability to 100 in Jiminny DB (and/or HubSpot updated their stage label/settings). Stage undateal.ate2826-85-043. May 20: A HubSpot webhook for dealnase or description property change arrived for this deal. Prndleocaldi rectUpdatfired - it updated the opportunity's nane field directly (touching updated_at ) but returned true without queuing a full sync. 15 von was neverrecalculated4. Result: updated_at: 2826-85-28 looks recent, but the is_von value is stale from a sync that happened before May 4 when the stage probability wasstilllotthe tixis to troac a troch sune df thie sond ic anoortunity: sync0noortun ty(404958190945*) wotld tetch ttrom Hub Soot soo denlstran - "closedlos", find it in wontl (probablity 100 now), and set 15,won + 1O al -ok I still don't get it. After I run manual comrnityid 494058190045 the opportunity is_won"eoohWindewatetTrnchure Xlline wankelires2 4 spa...
|
87853
|
NULL
|
NULL
|
NULL
|
|
87853
|
3001
|
11
|
2026-05-28T16:27:04.960297+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985624960_m2.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
rapstomViewNeweNNCCoocWindowFV faVsco.|s ~#12121 o rapstomViewNeweNNCCoocWindowFV faVsco.|s ~#12121 on JY-20963-fx-lProinet v© Service Test.php› @ MergewawenacdvityCimDalo.ongy uimaeumyociwiceonaewemwwocorotor.orFroseeeuscnid.pint© HubspotWebhookMetriLo Propenycnangemons:uvalohtwohooktoWebhookAssociationCooonurwowncaion© HubspotLastModifiedCreatedRecentiyOpenSyncStrateay.ohg© PayloadBulder.pho xg© WebhookDeletionHandwewokventsC WebhookMergeHandleclass Payloadbuzlden- 48×25 ^ V 88WebhookProoertvChan 9°C WeohookSionatureVa© BatchSynceollector.phpc) Batchsuncred sservice og clent.phpC) Cosed Dea StadessemicelC Desl zieldsservice onoC) Decorate chmm chocFeld detinitons cnoCrAcTvaAeoousreoodKtnend'esotiottesnhC HubspotTokenManager.pho pawiasatthoneooecPAmotdermersaiisomnd ResnonseNormalize.phpel Sarnice ono© SyncFieldAction.php© SyncRelatedActivityManac 69e Mohhaal-CunaRatchormd> @ IntegrationApoMlictonord> @ Metadata> [ Migration>D Pipedrivev C Salesforce> D Fields> B OpportunitvMatchen> D OpportunitvSvncStrateoeSemicetiraitsC e entondC. DecorateActivity.cho710bele eocectetie tonocseldae initons choc Paviosd Bulldes.onoc Pronie.onocOuwyetder.onocOuerylandier.ohoc Ouorvitorstoe nhae Ouoneoarte nhnci Connno nhr89* Generate a payload to search for contacts by name.*The searchois a token search sin dinstnane on uostnendpublic function generateSearchContactsByNamePayLoad(string Snane, array Sfields): arrayt...:5 usagespublic function buildAddAssociationPayload(string Scrnid, array Sids, int Sassociationlype): arrayi 973 apublic function buildRemoveAssociationPayload(string Scrnid, array $ids): array{...;/usagespublic function addClosedStageFilters(array &Spayload, array SclosedStages): voidif ( enpty(SclosedStagesf 'won'1)) 5oavrosolnwense"propercynane" s> "dealstage"-185vallues 8>SclSeoSROrSROnif (4 enoty(SclosedStagesf'lost'1)) !SoayLondn'Sittens"meBEES'propertyName' => "dealstage",onemator,113114"vallues' E> SclosedStaoest" lost"118public function addCreatedDateFilters(array &Spayload, Carbon ScreatedAfter): voidt...}10 usagespublic function getDealsinBulkPayload(array Sdealids): array ...;005Б65ВВВ5wtw:twwiews.outreonaettodaw RayA SF fiminny@loca host)HS Jocal jminny@blocalhostde console [PRODA console (EUle Froterundrewons"ohuneuis users (EUTA console [STAGING)Icaconl closs Prodercycnane chandoerTNY.AVself::0BJECTTYPE CONTACT => [I/ Add contact properties that support direct updateSelf::ORJECT TYPE COMPANY =>acooany oroderatesSuppornOReoping fren Hubspot prepenty nones to Mieieny roter prepenty nones* Used when updating the main model (Opportunity, Contact, Account) directly,* Onty needed when HubSpot property name differs fron Jininny property name*/private const array OBJECT_PROPERTY MAPPINGS =Commandsell.-ORJEeTYPE DEAL E)'dealnane' a> 'name'. / HubSpot 'dealname' maps to Opportunity 'nameExtract SurroundTT Ado contact property nappings if neededself::OBJECT_TYPE_COMPANY =>Add company property nappings if needed1:I/ Field object types mappingprivate const array FIELD_OBJECT_TYPES = [self::0BJECT_TYPE_DEAL => Field::0BJECT_OPPORTUNITYself::0BJECT_TYPE_CONTACT => Field::0BJECT_CONTACT,self::0BJECT_TYPE_COMPANY => Ficld::OBJECT_ACCOUNT1:onsuare tarchsuncioitleccon Sharchtoe ecton.private OpportunityRepository SopportunityRepository.orsivate CrnEntatvRenos.tory ScrnEnt: tyRenost tory.private FieldDataRepository SfieldDataRepository.private HubspotWebhookMetricsService SmetricsService,* Get contact fields that webhooks are subscribed to in HubSpot.* This serves as documentation of the current webhook confiquration.=100% 142-• Thu 28 May 19:27:04ServiceTestvmeesdales Orcnnworeebeeionhnves ohtine oDon+0.Unless the May 20 sync used a cachedClosedDea lStages that was populated earlier in the same batch lob — before a importStages () call updated thestage probability from 0 to 100. But that would require stage 20616 to have been at probabiity o at the start of that batch run, then changed to 100 midrunby ecortstases(.And ieportstanes only runsThe true, detinitive answenAfer all this ansves, the most"kely exolonstion is this is a data snaoshot from an eanter time,t ihe opoortunty was sunoed when closedlost hadprobability 0 (before May 4, 2026). Then someone manually changed the stage probability to 100 on May 4 in Jiminny. But the opportunity hasn't been re-synced since then - it shows updated at: 2026-45-20 but that could be from a different field being updated (like dealnase, value, etc.) via the Propertychanackanager's dircct uodate path, which does Not recalculate is. wonLook at PropertyCharhinonio Looea luareciupdatea PropertyChUoontc boock procchisy trwootne cxstsCoronerManoinos- CeTATO:EeT PROPERN MAPDNMSIRANANOROFMNMPE DEAEITETNif (isset(SpropertyMappings(SpropertyNase) )) 4Sthis-sopportunityRepository-update0rCreate(...):odste weld darsthis->import0bjectFieldData(...):return trues0B OBJECT UPOATE PROPERTIES for deals = ["ótalnane', "description']. If a dealnane or description webhook event came in on May 20, it would1. Update nane on the opportunity (via update0rCreate) → touches updated.at2. Return true (bypassing the full hand leübiectSync / batch queue path3. NOT recalculate 15. voThis is the answer. On May 20, a dralnase or description change webhook arrived. PropertyChangeManaoer: :handleDralDirectUpdate ran, undatecthe opportunity's nane field (touching updated_at to 2026-05-28 18:36:59 ), and returned true - skipping the full batch sync that would haverecalculated is_von. The deal's is_von was already e from a previous sync (when closedlost had probability 0, before May 4), and the May 20 directupdate webhook dionthxkSummatyTine ooocturynsywna1. Before May 4: Stage 20616 (closmdlost) had probability = 8 in Jiminny's DB (consistent with HubSpot's default behavior for a stage named"closedlost"). Any sync at that time would put "closedlost" in tost() → 1s_closedel, is-wonne2. May 4: Someone manually updated the stage probability to 100 in Jiminny DB (and/or HubSpot updated their stage label/settings). Stage undatedl.ate2026-06-043. May 20: A HubSpot webhook for dealnase or description property change arrived for this deal. Prndleocaldi rectUpdatfired - it updated the opportunity's nane field directly (touching updated_at ) but returned true without queuing a fulll sync. is_von was neverrecalculated4. Result: updated.at: 2826-85-20 looks recent, but the is-von value is stale from a sync that happened before May 4 when the stage probability wastilllotthe tixis to troac a troch sune df thie sond ic anoortunity: sync0noortun ty(404958190945*) wotld tetch ttrom Hub Soot soo denlstran - "closedlosf*, find it in wonill (probabillity 100 now), and set 1s.won = 1Cal =ok I still don't get it. After I run manual conand to php artisan crm:sync-opportunity --teamid 555 --opportyras set to 1. However I stil can't understand what happened before. The opportunity stage was changed on 2026-9"eoohWindewetetTrnchure xlline wasket4 spa...
|
NULL
|
-6415391823891610473
|
NULL
|
click
|
ocr
|
NULL
|
rapstomViewNeweNNCCoocWindowFV faVsco.|s ~#12121 o rapstomViewNeweNNCCoocWindowFV faVsco.|s ~#12121 on JY-20963-fx-lProinet v© Service Test.php› @ MergewawenacdvityCimDalo.ongy uimaeumyociwiceonaewemwwocorotor.orFroseeeuscnid.pint© HubspotWebhookMetriLo Propenycnangemons:uvalohtwohooktoWebhookAssociationCooonurwowncaion© HubspotLastModifiedCreatedRecentiyOpenSyncStrateay.ohg© PayloadBulder.pho xg© WebhookDeletionHandwewokventsC WebhookMergeHandleclass Payloadbuzlden- 48×25 ^ V 88WebhookProoertvChan 9°C WeohookSionatureVa© BatchSynceollector.phpc) Batchsuncred sservice og clent.phpC) Cosed Dea StadessemicelC Desl zieldsservice onoC) Decorate chmm chocFeld detinitons cnoCrAcTvaAeoousreoodKtnend'esotiottesnhC HubspotTokenManager.pho pawiasatthoneooecPAmotdermersaiisomnd ResnonseNormalize.phpel Sarnice ono© SyncFieldAction.php© SyncRelatedActivityManac 69e Mohhaal-CunaRatchormd> @ IntegrationApoMlictonord> @ Metadata> [ Migration>D Pipedrivev C Salesforce> D Fields> B OpportunitvMatchen> D OpportunitvSvncStrateoeSemicetiraitsC e entondC. DecorateActivity.cho710bele eocectetie tonocseldae initons choc Paviosd Bulldes.onoc Pronie.onocOuwyetder.onocOuerylandier.ohoc Ouorvitorstoe nhae Ouoneoarte nhnci Connno nhr89* Generate a payload to search for contacts by name.*The searchois a token search sin dinstnane on uostnendpublic function generateSearchContactsByNamePayLoad(string Snane, array Sfields): arrayt...:5 usagespublic function buildAddAssociationPayload(string Scrnid, array Sids, int Sassociationlype): arrayi 973 apublic function buildRemoveAssociationPayload(string Scrnid, array $ids): array{...;/usagespublic function addClosedStageFilters(array &Spayload, array SclosedStages): voidif ( enpty(SclosedStagesf 'won'1)) 5oavrosolnwense"propercynane" s> "dealstage"-185vallues 8>SclSeoSROrSROnif (4 enoty(SclosedStagesf'lost'1)) !SoayLondn'Sittens"meBEES'propertyName' => "dealstage",onemator,113114"vallues' E> SclosedStaoest" lost"118public function addCreatedDateFilters(array &Spayload, Carbon ScreatedAfter): voidt...}10 usagespublic function getDealsinBulkPayload(array Sdealids): array ...;005Б65ВВВ5wtw:twwiews.outreonaettodaw RayA SF fiminny@loca host)HS Jocal jminny@blocalhostde console [PRODA console (EUle Froterundrewons"ohuneuis users (EUTA console [STAGING)Icaconl closs Prodercycnane chandoerTNY.AVself::0BJECTTYPE CONTACT => [I/ Add contact properties that support direct updateSelf::ORJECT TYPE COMPANY =>acooany oroderatesSuppornOReoping fren Hubspot prepenty nones to Mieieny roter prepenty nones* Used when updating the main model (Opportunity, Contact, Account) directly,* Onty needed when HubSpot property name differs fron Jininny property name*/private const array OBJECT_PROPERTY MAPPINGS =Commandsell.-ORJEeTYPE DEAL E)'dealnane' a> 'name'. / HubSpot 'dealname' maps to Opportunity 'nameExtract SurroundTT Ado contact property nappings if neededself::OBJECT_TYPE_COMPANY =>Add company property nappings if needed1:I/ Field object types mappingprivate const array FIELD_OBJECT_TYPES = [self::0BJECT_TYPE_DEAL => Field::0BJECT_OPPORTUNITYself::0BJECT_TYPE_CONTACT => Field::0BJECT_CONTACT,self::0BJECT_TYPE_COMPANY => Ficld::OBJECT_ACCOUNT1:onsuare tarchsuncioitleccon Sharchtoe ecton.private OpportunityRepository SopportunityRepository.orsivate CrnEntatvRenos.tory ScrnEnt: tyRenost tory.private FieldDataRepository SfieldDataRepository.private HubspotWebhookMetricsService SmetricsService,* Get contact fields that webhooks are subscribed to in HubSpot.* This serves as documentation of the current webhook confiquration.=100% 142-• Thu 28 May 19:27:04ServiceTestvmeesdales Orcnnworeebeeionhnves ohtine oDon+0.Unless the May 20 sync used a cachedClosedDea lStages that was populated earlier in the same batch lob — before a importStages () call updated thestage probability from 0 to 100. But that would require stage 20616 to have been at probabiity o at the start of that batch run, then changed to 100 midrunby ecortstases(.And ieportstanes only runsThe true, detinitive answenAfer all this ansves, the most"kely exolonstion is this is a data snaoshot from an eanter time,t ihe opoortunty was sunoed when closedlost hadprobability 0 (before May 4, 2026). Then someone manually changed the stage probability to 100 on May 4 in Jiminny. But the opportunity hasn't been re-synced since then - it shows updated at: 2026-45-20 but that could be from a different field being updated (like dealnase, value, etc.) via the Propertychanackanager's dircct uodate path, which does Not recalculate is. wonLook at PropertyCharhinonio Looea luareciupdatea PropertyChUoontc boock procchisy trwootne cxstsCoronerManoinos- CeTATO:EeT PROPERN MAPDNMSIRANANOROFMNMPE DEAEITETNif (isset(SpropertyMappings(SpropertyNase) )) 4Sthis-sopportunityRepository-update0rCreate(...):odste weld darsthis->import0bjectFieldData(...):return trues0B OBJECT UPOATE PROPERTIES for deals = ["ótalnane', "description']. If a dealnane or description webhook event came in on May 20, it would1. Update nane on the opportunity (via update0rCreate) → touches updated.at2. Return true (bypassing the full hand leübiectSync / batch queue path3. NOT recalculate 15. voThis is the answer. On May 20, a dralnase or description change webhook arrived. PropertyChangeManaoer: :handleDralDirectUpdate ran, undatecthe opportunity's nane field (touching updated_at to 2026-05-28 18:36:59 ), and returned true - skipping the full batch sync that would haverecalculated is_von. The deal's is_von was already e from a previous sync (when closedlost had probability 0, before May 4), and the May 20 directupdate webhook dionthxkSummatyTine ooocturynsywna1. Before May 4: Stage 20616 (closmdlost) had probability = 8 in Jiminny's DB (consistent with HubSpot's default behavior for a stage named"closedlost"). Any sync at that time would put "closedlost" in tost() → 1s_closedel, is-wonne2. May 4: Someone manually updated the stage probability to 100 in Jiminny DB (and/or HubSpot updated their stage label/settings). Stage undatedl.ate2026-06-043. May 20: A HubSpot webhook for dealnase or description property change arrived for this deal. Prndleocaldi rectUpdatfired - it updated the opportunity's nane field directly (touching updated_at ) but returned true without queuing a fulll sync. is_von was neverrecalculated4. Result: updated.at: 2826-85-20 looks recent, but the is-von value is stale from a sync that happened before May 4 when the stage probability wastilllotthe tixis to troac a troch sune df thie sond ic anoortunity: sync0noortun ty(404958190945*) wotld tetch ttrom Hub Soot soo denlstran - "closedlosf*, find it in wonill (probabillity 100 now), and set 1s.won = 1Cal =ok I still don't get it. After I run manual conand to php artisan crm:sync-opportunity --teamid 555 --opportyras set to 1. However I stil can't understand what happened before. The opportunity stage was changed on 2026-9"eoohWindewetetTrnchure xlline wasket4 spa...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87850
|
3001
|
10
|
2026-05-28T16:26:53.791011+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985613791_m2.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
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.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
5582423643801155883
|
-8994321436789994556
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
rapstomViewNeweNNCCoocWindowFV faVsco.|s ~#12121 on JY-20963-fx-lProinet v© Service Test.php› @ Mergewalennedwilycmbdlo.orgy uimaeumyociwiceonaewemwwocorotor.orFroseeeuscnid.pint© HubspotWebhookMetriLo Propenycnangemons:uvalohtwohooktoWebhookAssociationCooonurwowncaion© HubspotLastModifiedCreatedRecentiyOpenSyncStrateay.ohg© PayloadBulder.pho x© WebhookDeletionHandwewokventsC WebhookMergeHandleclass Payloadbuzlden= | A8 225 A 33WebhookProoertvChan 9°c WeohookSionatureVal© BatchSynceollector.phpc) Batchsuncred sservice og clent.phpC) Cosed Dea StadessemicelC Desl zieldsservice onoC) Decorate chmm chocFeld detinitons cnoCrAcTvaAeoousreoodKtnend'esotiotsrnesnhC) HubspotTokenManager.phe pawiasatthieaeahdcPAmotdermersaiisomnd ResnonseNormalize.phpel Sarnice ono© SyncFieldAction.php© SyncRelatedActivityManac 69e Mohhaal-CunaRatchormd> @ IntegrationApoMlictonord> @ Metadata> [ Migration>D Pipedrivev C Salesforce> D Fields> B OpportunitvMatchen> D OpportunitvSvncStrateoRRER8eSemicetiraitsC e entondC. DecorateActivity.cho710bele eocectetie tonocseldoe inittons cnoc Paviosd Bulldes.onoc Pronie.ono₴2cOuwyetder.onocOuerylandier.ohoc Ouorvitorstoe nhae Ouoneoarte nhnci Connno nhr* Generate a payload to search for contacts by name.*The searchois a token search sin dinstnane on uostnendpublic function generateSearchContactsByNamePayLoad(string Snane, array Sfields): arrayt...:935 usages95public function buildAddAssociationPayload(string Scrnid, array Sids, int Sassociationlype): arrayi 97public function buildRemoveAssociationPayload(string Scrnid, array Sids): array{...}/usagespublic function addClosedStageFilters(array &Spayload, array SclosedStages): voidif ( enpty(SclosedStagesf 'won'1)) 5oavrosolnwense"propercynane" s> "dealstage"vallues 8>SclSeoSROrSROnif (4 enoty(SclosedStagesf'lost'1)) !SoayLondn'Sittens"me'propertyName' => "dealstage","oneator"vallues' E> SclosedStaoest" lost"19988Usdouspublic function addCreatedDateFilters(array &Spayload, Carbon ScreatedAfter): voidt...}10 usagespublic function getDealsinBulkPayload(array Sdealids): array ...;8 8 0,11,44,08431hw:tw/wiew oureoueettodayRayA SF fiminny@loca host)HS Jocal jminny@blocalhostde console [PROD# consolkeule Froterundrewons"ohuneuis users (EUTA console [STAGING)Icaconl closs Prodercycnane chandoerTNY.AVself::0BJECTTYPE CONTACT => [I/ Add contact properties that support direct updateSelf::ORJECT TYPE COMPANY =>acooany oroderatesSuppornONapping fron Hubspot propenty nanes to Jistiany rodel preperty none* Used when updating the main model (Opportunity, Contact, Account) directly,* Onty needed when HubSpot property name differs fron Jininny property name.'dealnane' a> 'name', // HubSpot 'dealname' maps to Opportunity 'nameprávate const array FIELD_OBJECT_TYPES =1self::0BJECT_TYPE_DEAL => Ejeld::OBJECT_OPPORTUNETY,SUTIKENENPEWINPANNE TCLOOKENANNEpublic function __constructCprivate Batchsynctollector Sbatchcollector,private OpportunityRepository SopportunityRepository.private CrmEntityRepository ScrnEntityRepository.private FieldRepository SfieldRepository,private FieldDataRepository SfieldDataRepository.private HubspotWebhookMetricsService SnetricsService* Get contact fields that webhooks are subscribed to in HubSpot.* This serves as documentation of the current webhook confiquration.=100% 142-• Thu 28 May 19:26:53ServiceTestvmeesdales Orcnnworeeoeionhnves ohtine oDon+0 .Unless the May 20 sync used a cachedClosedDea lStages that was populated earlier in the same batch lob — before a importStages () call updated thestage probability from 0 to 100. But that would require stage 20616 to have been at probabiity o at the start of that batch run, then changed to 100 midrun by ecortstases(.And ieportstanes only runsThe true, detinitive answenAfer all this ansves, the most"kely exolonstion is this is a data snaoshot from an eanter time,t ihe opoortunty was sunoed when closedlost hadprobability 0 (before May 4, 2026). Then someone manually changed the stage probability to 100 on May 4 in Jiminny. But the opportunity hasn't been re-synced since then - it shows updated at: 2026-45-20 but that could be from a different field being updated (like dealnase, value, etc.) via the Propertychanackanager's dircct uodate path, which does Not recalculate is. wonLook at PropertyChahinonio Looea luareciupdatea PropertyChuoontc bouck procchsytrtstne CxistCRooerMRoosCos& CeTTeOEeI PROPERN MAPPISRANAHORFMNNPE OEATNEhif (isset(SpropertyMappings (SpropertyNase) )) 4Sthis-sopportunityRepository-update0rCreate(...):odste weld darsthis->import0bjectFieldData(...):0B OBJECT UPOATE PROPERTIES for deals = ["ótalnane', "description']. If a dealnane or description webhook event came in on May 20, it would1. Update nane on the opportunity (via update0rCreate) → touches updated.at2. Return true (bypassing the full hand leöbiectSync / batch queue path3. NOT recalculate 15, volThis is the answer. On May 20, a dralnase or description change webhook arrived. PropertyChangeManaoer: :handleDralDirectUpdate ran, undatecthe opportunity's nane field (touching updated_at to 2026-05-28 18:36:59 ), and returned true - skipping the full batch sync that would haverecalculated is_von. The deal's is_von was already e from a previous sync (when closedlost had probability 0, before May 4), and the May 20 direct-update webhook dionthxkSummatyTine ooocturynsywna1. Before May 4: Stage 20616 (closmdlost) had probability = 8 in Jiminny's DB (consistent with HubSpot's default behavior for a stage named"closedlost"). Any sync at that time would put "closedlost" in tost() → 1s_closedel, is-wonne2. May 4: Someone mansally updated the stage probability to 100 in Jiminny DB (and/or HubSpot updated their stage label/settings). Stage undatedl.ate2826-06-0413. May 20: A HubSpot webhook for dealnase or description property change arrived for this deal. Prcndleocaldi rectUpdatfired - it updated the opportunity's nane field directly (touching updated_at ) but returned true without queuing a fulll sync. is_von was neverrecalculated4. Result: updated.at: 2826-85-20 looks recent, but the is-von value is stale from a sync that happened before May 4 when the stage probability wastilllotthe tixis to troac a troch sune df thie sond ic anoortunity: sync0noortun ty(404958190945*) wotld tetch ttrom Hub Soot soo denlstran - "closedlosf*, find it in wonfll (probabllity 100 now), and set 1swon = 1Gal =ok I still don't get it. After I run manual conand to php artisan crm:sync-opportunity --teamid 555 --opportras set to 1. However I stll can't understand what happened before. The opportunity stage was changed on 2026-05-20t4 spag...
|
87849
|
NULL
|
NULL
|
NULL
|
|
87849
|
3001
|
9
|
2026-05-28T16:26:47.556335+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985607556_m2.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
rapstomViewNeweNNCCoocWindowFV faVsco.|s ~#12121 o rapstomViewNeweNNCCoocWindowFV faVsco.|s ~#12121 on JY-20963-fx-l© Service Test.phppeleteooiccistrai.png› @ MergewawenacdvityCimDalo.ongy uimaeumyociwiceonaewemwwocorotor.oro Prossceruochid.pno© HubspotWebhookMetriLo Propenycnangemons:uvalohtwohooktoWebhookAssociationCooonurwowncaion© HubspotLastModifiedCreatedRecentiyOpenSyncStrateay.ohg© PayloadBulder.php x© WebhookDeletionHandwewokventsC WebhookMergeHandleclass Payloadbuzlden- 48×25 ^ V 219WebhookProoertvChan 9°c WeohookSionatureVal© BatchSynceollector.phpc) Batchsuncred sservice og clent.phpC) Cosed Dea StadessemicelC Desl zieldsservice onoC) Decorate chmm chocFeld detinttons onoCrAcTvaAeoousreoodKtnend'esotiotsrnesnhC HubspotTokenManager.pho pawiasatthoneooecPAmotdermersaiisomnd ResnonseNormalize.phpel Sarnice ono© SyncFieldAction.php© SyncRelatedActivityManac 69e Mohhaal-CunaRatchormd> @ IntegrationApoMlictonord> @ Metadata> [ Migration>D Pipedrivev C Salesforce> D Fields> B OpportunitvMatchen> D OpportunitvSvncStrateoeSemicetiraitsC e entondC. DecorateActivity.cho710bele eocectetie tonocseldae initons choc Paviosd Bulldes.onoc Pronie.onocOuwyetder.onocOuerylandier.ohoc Ouorvitorstoe nhae Ouoneoarte nhnci Connno nhr* Generate a payload to search for contacts by name.*The searchois a token search sin dinstnane on uostnendpublic function generateSearchContactsByNamePayLoad(string Snane, array Sfields): arrayt...:Z245 usagespublic function buildAddAssociationPayload(string Scrnid, array Sids, int Sassociationlype): arrayi 22€227228public function buildRemoveAssociationPayload(string Scrnid, array $ids): array{...;/usagespublic function addClosedStageFilters(array &Spayload, array SclosedStages): voidif ( enpty(SclosedStagesf 'won'1)) 5oavrosolnwense251252"propercynane" s> "dealstage"vallues 8>SclSeoSROrSROn254259254257if (4 enoty(SclosedStagesf'lost•1)) !SoayLondn'Sittens"me'propertyName' => "dealstage",onemator,262262"vallues' E> SclosedStaoest" lost"public function addCreatedDateFilters(array &Spayload, Carbon ScreatedAfter): void ....10 usagespublic function getDealsinBulkPayload(array Sdealids): array ...;wtw:twwiews.outreonaettodaw RayA SF fiminny@loca host)de console [PROD# consolkeule Froterundrewons"ohunguis users (EUTA console [STAGING)TNY.AVprivate function isDirectUpdateSupported(string SobjectType, string SpropertyName): bool(...* Henole oroperaesha suodon onec denooseWeCino oo1eee Votoino So01e0edConfigurat ion Sconfigurationstriina Soropertylancstring SpropertyValug: booL 1..H* Handle direct updates for deal objectsprivate function handleDealDirectUpdatestring SobnectId.lConfiquration Sconfiqurationstring SpropertyNameStrano Spropercyvalue: bool 4Sopportunity = Sthis->opportun_tyRepos{tory->findByConf_gAndCraProviderIddif ( Sopportunity instanceof Opportunity) 4reurntei/ Uodate nodel pronenty if naoping existeSpropertynappings = SeLT::UBJECT_PROPERTY_HAPPINGSLSELT::OBJECT_TYPE_DEAL) PP LJEi€ Gisset (Soronent.vManninasfSoropentyNanel))?Sthis-sonnortunitvRenositony->update0rCceate/Sohrectd.SoronertyMannsinasiiSaronertylanel SoronentyVailuelUpdate field dateSthssosononthhsectf.eldhatalobecttwoe. self..OR.FAT TYPE NSAICAnnAntIn turSaOtTAO>0bAl100% 142-• Thu 28 May 19:26:47ServiceTestvmeesdales Orcnnworeebeeionhnves ohtine oDon+0 .Unless the May 20 sync used a cachedClosedDea lStages that was populated earlier in the same batch lob — before a importStages () call updated thestage probability from 0 to 100. But that would require stage 20616 to have been at probabiity o at the start of that batch run, then changed to 100 midrunby tcortStases(.And ieportstanes onty runswThe true, detinitive answenAfer all this ansves, the most"kely exolonstion is this is a data snaoshot from an eanter time,t ihe opoortunty was sunoed when closedlost hadprobability 0 (before May 4, 2026). Then someone manually changed the stage probability to 100 on May 4 in Jiminny. But the opportunity hasn't been re-synced since then - it shows updated at: 2026-45-20 but that could be from a different field being updated (like dealnase, value, etc.) via the Propertychangckansger's dircct uodate path, which does Not recalculate is wonLook at PropertyCharchinono looea luareciupdatea PropertyChUoonte bouck procchisyuttne CxistCRooerMRoosCos& CeTTeOEeI PROPERN MAPPISRANAHORFMNNPE OEATNEhif (isset(SpropertyMappings(SpropertyNase) )) 4Sthis-sopportunityRepository-update0rCreate(...):odste weld darsthis->import0bjectFieldData(...):return tries0B OBJECT UPOATE PROPERTIES for deals = ["ótalnane', "description']. If a dealnane or description webhook event came in on May 20, it would1. Update nane on the opportunity (via update0rCreate ) → touches updated.at2. Return true (bypassing the full hand leübiectSync / batch queue path3. NOT recalculate 15, volThis is the answer. On May 20, a dralnase or description change webhook arrived. PropertyChangeManaoer: :handleDralDirectUpdate ran, undatecthe opportunity's nane field (touching updated_at to 2026-05-28 18:36:59 ), and returned true - skipping the full batch sync that would haverecalculated is_von. The deal's is_von was already e from a previous sync (when closedlost had probability 0, before May 4), and the May 20 directupdate webhook dionthxkSummalyTine ooocturynsywna1. Before May 4: Stage 20616 (closmdlost) had probability = 8 in Jiminny's DB (consistent with HubSpot's default behavior for a stage named"closedlost"). Any sync at that time would put "closedlost" in tost() → 1s_closedel, is-wonne2. May 4: Someone nsally updated the stage probability to 100 in Jiminny DB (and/or HubSpot updated their stage label/settings). Stage undatedl.ate2026-06-043. May 20: A HubSpot webhook for dealnase or description property change arrived for this deal. Procertychndleocaldi rectUpdatfired - it updated the opportunity's nane field directly (touching updated_at ) but returned true without queuing a fulll sync. is_von was neverrecalculated4. Result: updated.at: 2826-85-20 looks recent, but the is-von value is stale from a sync that happened before May 4 when the stage probability wastilllotthe tixis to troac a troch sune df thie sond ic anoortunity: sync0noortun ty(404958190945*) wotld tetch ttrom Hub Soot soo denlstran - "closedlosf*, find it in wonill (probabillity 100 now), and set 1s.won = 1Coal +ok I still don't get it. After I run manual conand to php artisan crm:sync-opportunity --teamid 555 --opportwas set to 1. However I stil can't understand what happened before. The opportunity stage was changed on 2026-"eooht4 spag...
|
NULL
|
-283997725300794889
|
NULL
|
visual_change
|
ocr
|
NULL
|
rapstomViewNeweNNCCoocWindowFV faVsco.|s ~#12121 o rapstomViewNeweNNCCoocWindowFV faVsco.|s ~#12121 on JY-20963-fx-l© Service Test.phppeleteooiccistrai.png› @ MergewawenacdvityCimDalo.ongy uimaeumyociwiceonaewemwwocorotor.oro Prossceruochid.pno© HubspotWebhookMetriLo Propenycnangemons:uvalohtwohooktoWebhookAssociationCooonurwowncaion© HubspotLastModifiedCreatedRecentiyOpenSyncStrateay.ohg© PayloadBulder.php x© WebhookDeletionHandwewokventsC WebhookMergeHandleclass Payloadbuzlden- 48×25 ^ V 219WebhookProoertvChan 9°c WeohookSionatureVal© BatchSynceollector.phpc) Batchsuncred sservice og clent.phpC) Cosed Dea StadessemicelC Desl zieldsservice onoC) Decorate chmm chocFeld detinttons onoCrAcTvaAeoousreoodKtnend'esotiotsrnesnhC HubspotTokenManager.pho pawiasatthoneooecPAmotdermersaiisomnd ResnonseNormalize.phpel Sarnice ono© SyncFieldAction.php© SyncRelatedActivityManac 69e Mohhaal-CunaRatchormd> @ IntegrationApoMlictonord> @ Metadata> [ Migration>D Pipedrivev C Salesforce> D Fields> B OpportunitvMatchen> D OpportunitvSvncStrateoeSemicetiraitsC e entondC. DecorateActivity.cho710bele eocectetie tonocseldae initons choc Paviosd Bulldes.onoc Pronie.onocOuwyetder.onocOuerylandier.ohoc Ouorvitorstoe nhae Ouoneoarte nhnci Connno nhr* Generate a payload to search for contacts by name.*The searchois a token search sin dinstnane on uostnendpublic function generateSearchContactsByNamePayLoad(string Snane, array Sfields): arrayt...:Z245 usagespublic function buildAddAssociationPayload(string Scrnid, array Sids, int Sassociationlype): arrayi 22€227228public function buildRemoveAssociationPayload(string Scrnid, array $ids): array{...;/usagespublic function addClosedStageFilters(array &Spayload, array SclosedStages): voidif ( enpty(SclosedStagesf 'won'1)) 5oavrosolnwense251252"propercynane" s> "dealstage"vallues 8>SclSeoSROrSROn254259254257if (4 enoty(SclosedStagesf'lost•1)) !SoayLondn'Sittens"me'propertyName' => "dealstage",onemator,262262"vallues' E> SclosedStaoest" lost"public function addCreatedDateFilters(array &Spayload, Carbon ScreatedAfter): void ....10 usagespublic function getDealsinBulkPayload(array Sdealids): array ...;wtw:twwiews.outreonaettodaw RayA SF fiminny@loca host)de console [PROD# consolkeule Froterundrewons"ohunguis users (EUTA console [STAGING)TNY.AVprivate function isDirectUpdateSupported(string SobjectType, string SpropertyName): bool(...* Henole oroperaesha suodon onec denooseWeCino oo1eee Votoino So01e0edConfigurat ion Sconfigurationstriina Soropertylancstring SpropertyValug: booL 1..H* Handle direct updates for deal objectsprivate function handleDealDirectUpdatestring SobnectId.lConfiquration Sconfiqurationstring SpropertyNameStrano Spropercyvalue: bool 4Sopportunity = Sthis->opportun_tyRepos{tory->findByConf_gAndCraProviderIddif ( Sopportunity instanceof Opportunity) 4reurntei/ Uodate nodel pronenty if naoping existeSpropertynappings = SeLT::UBJECT_PROPERTY_HAPPINGSLSELT::OBJECT_TYPE_DEAL) PP LJEi€ Gisset (Soronent.vManninasfSoropentyNanel))?Sthis-sonnortunitvRenositony->update0rCceate/Sohrectd.SoronertyMannsinasiiSaronertylanel SoronentyVailuelUpdate field dateSthssosononthhsectf.eldhatalobecttwoe. self..OR.FAT TYPE NSAICAnnAntIn turSaOtTAO>0bAl100% 142-• Thu 28 May 19:26:47ServiceTestvmeesdales Orcnnworeebeeionhnves ohtine oDon+0 .Unless the May 20 sync used a cachedClosedDea lStages that was populated earlier in the same batch lob — before a importStages () call updated thestage probability from 0 to 100. But that would require stage 20616 to have been at probabiity o at the start of that batch run, then changed to 100 midrunby tcortStases(.And ieportstanes onty runswThe true, detinitive answenAfer all this ansves, the most"kely exolonstion is this is a data snaoshot from an eanter time,t ihe opoortunty was sunoed when closedlost hadprobability 0 (before May 4, 2026). Then someone manually changed the stage probability to 100 on May 4 in Jiminny. But the opportunity hasn't been re-synced since then - it shows updated at: 2026-45-20 but that could be from a different field being updated (like dealnase, value, etc.) via the Propertychangckansger's dircct uodate path, which does Not recalculate is wonLook at PropertyCharchinono looea luareciupdatea PropertyChUoonte bouck procchisyuttne CxistCRooerMRoosCos& CeTTeOEeI PROPERN MAPPISRANAHORFMNNPE OEATNEhif (isset(SpropertyMappings(SpropertyNase) )) 4Sthis-sopportunityRepository-update0rCreate(...):odste weld darsthis->import0bjectFieldData(...):return tries0B OBJECT UPOATE PROPERTIES for deals = ["ótalnane', "description']. If a dealnane or description webhook event came in on May 20, it would1. Update nane on the opportunity (via update0rCreate ) → touches updated.at2. Return true (bypassing the full hand leübiectSync / batch queue path3. NOT recalculate 15, volThis is the answer. On May 20, a dralnase or description change webhook arrived. PropertyChangeManaoer: :handleDralDirectUpdate ran, undatecthe opportunity's nane field (touching updated_at to 2026-05-28 18:36:59 ), and returned true - skipping the full batch sync that would haverecalculated is_von. The deal's is_von was already e from a previous sync (when closedlost had probability 0, before May 4), and the May 20 directupdate webhook dionthxkSummalyTine ooocturynsywna1. Before May 4: Stage 20616 (closmdlost) had probability = 8 in Jiminny's DB (consistent with HubSpot's default behavior for a stage named"closedlost"). Any sync at that time would put "closedlost" in tost() → 1s_closedel, is-wonne2. May 4: Someone nsally updated the stage probability to 100 in Jiminny DB (and/or HubSpot updated their stage label/settings). Stage undatedl.ate2026-06-043. May 20: A HubSpot webhook for dealnase or description property change arrived for this deal. Procertychndleocaldi rectUpdatfired - it updated the opportunity's nane field directly (touching updated_at ) but returned true without queuing a fulll sync. is_von was neverrecalculated4. Result: updated.at: 2826-85-20 looks recent, but the is-von value is stale from a sync that happened before May 4 when the stage probability wastilllotthe tixis to troac a troch sune df thie sond ic anoortunity: sync0noortun ty(404958190945*) wotld tetch ttrom Hub Soot soo denlstran - "closedlosf*, find it in wonill (probabillity 100 now), and set 1s.won = 1Coal +ok I still don't get it. After I run manual conand to php artisan crm:sync-opportunity --teamid 555 --opportwas set to 1. However I stil can't understand what happened before. The opportunity stage was changed on 2026-"eooht4 spag...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87847
|
3001
|
8
|
2026-05-28T16:26:43.295934+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985603295_m2.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
6423983795013307969
|
-3852565242246887264
|
visual_change
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
rapstomViewCoocWindowFV faVsco.s ~#12121 on JY-20963-fx-in© Service Test.phppeleteooiccistrai.pngM.CLAUDE mowolcnnedvityCimbald.ongy uimaeumyociwiceonaewemwwocorotor.orFroseeeuscnid.pintcomooser isonACUViy.oncomooserlockdeoendency-checkercoroowonoryoyne taion© HubspotLastModifiedCreatedRecentiyOpenSyncStrateay.ohgePawwnobu ooirone x211dev.sonids.txtintection.son.declass Payloadbuzlden- 48×25 ^ V 219MAINCTAImMAINSeNAws.wowcstem687* Generate a payload to search for contacts by name.*The searchois a token search sin dinstnane on uostnendliminny_storageMallicaneae maM Makefile# package-lock.jsonphpstan.neon.distEphpstan-baseline.neo< phpunit.xmltraw-Sclquely.scMEREADME.md& sonar-prolect.propertiesEtestiov<> Untitied Diagram.xmls vetur.confialeM.WEBHOOK_FILTERING.IMPLEMENTAT OYhexenalMortesv Scratches and ConsolesVteeostConotconsole iaulADEAL RISKS (EUToNTEUA EU (EU)ylliminnusochinostconsole tliminnweioch moshof tiiminny@localhostHS ocallitliminnw@loca nosh#SF (iminny@localhost)zoho-dev (iminny@localhost)V A PRODA console PRODnancalo logeniDI PROD]› AOA> A QAI> QAI PRODV ASTAGINGA console (STAGINGconsole SlaGiNgA uranus (STAGING)>M ExtensionsMScratchas-220public function generateSearchContactsByNamePayLoad(string Snane, array Sfields): arrayt...:5 usages224public function buildAddAssociationPayload(string Scrnid, array Sids, int Sassociationlype): arrayi 22€227228public function buildRemoveAssociationPayload(string Scrnid, array $ids): array{...;/usagespublic function addClosedStageFilters(array &Spayload, array SclosedStages): void248- 249250if ( enpty(SclosedStagesf 'won'1)) 5oavrosolnwense"propercynane" s> "dealstage"values S>clOSeOSdOrSROn251252253254255if (4 enoty(SclosedStagesf'lost•1)) !SoayLondn'Sittens"me'propertyName' => "dealstage","onematon""NODN"26%262"vallues' E> SclosedStaoest" lost"public function addCreatedDateFilters(array &Spayload, Carbon ScreatedAfter): void ....10 usagespublic function getDealsinBulkPayload(array Sdealids): array ...;8885ЗаЗдаВаВВAottylwiew outrenuaet todayRayA SF fiminny@loca host)HS Jocal jminny@blocalhostde console [PROD# consolkeule Froterundrewons"ohunguis users (EUTA console [STAGING)TNY.AVprivate function isDirectUpdateSupported(string SobjectType, string SpropertyName): booli...* Henole oroperaesha suodon onec denooseWeCrinoooieedvotoino So01e0edConfigurat ion Sconfigurationstriina Soropertylancstring SpropertyValug): bool 4...3objectsnnusto tunatson hantilono.Insnostlindatoetasinn Cahslonttaiconrauracon comerurderorstring SpropertyNameScrano Soroper cyvalue): bool 4Sopportunity = Sthis->oppontun_tyRepos{tory->findByConf_gAndCraProviderIdscont zouracionSobeccloif ( Sopportunity instanceof Opportunity) 41/ Uodate sodel oronenty if maoping existelSpropertynappings = seLT::UBJECT_PROPERTY_HAPPINGSLSELT:ROBJECT_TYPE_DEAL) PP LJGi€ Gisset (Soronent.vManninasfSoropentyNanel))?hisosonnor unttvrenosttory-sunchretrereare[SoronentvManninasfSoronentvNanel SoronentvValue]Update field dataSthssosnnonthhsectF.eldhatalobjectType: self::OBJECT_TYPE_DEAL,CAnnAntund tursaottaO100% 142-• Thu 28 May 19:26:42ServiceTestvmeesdales Orcnnworeeoeionhnves ohtine oDon+0.Unless the May 20 sync used a cachedClosedDea lStages that was populated earlier in the same batch lob — before a importStages () call updated thestage probability from 0 to 100. But that would require stage 20616 to have been at probabiity o at the start of that batch run, then changed to 100 midrunby tecortStases(.And ieportstanesonty runswThe true, detinitive answenAfer all this ansves, the most"kely exolonstion is this is a data snaoshot from an eanter time,t ihe opoortunty was sunoed when closedlost hadprobability 0 (before May 4, 2026). Then someone manually changed the stage probability to 100 on May 4 in Jiminny. But the opportunity hasn't been re-synced since then - it shows updated at: 2026-45-20 but that could be from a different field being updated (like dealnase, value, etc.) via the Propertychangckansger's dircct uodate path, which does Not recalculate is wonLook at PropertyChangelchinono looea luareciupdatea PropertychUoontc boock procchisy trwootne cxstsCoronerManoinos- CeTATO:EeT PROPERN MAPDNMSIRANANOROFMNMPE DEAEITETNif (isset(SpropertyMappings(SpropertyNase) )) 4Sthis-sopportunityRepository-update0rCreate(...):odste weld darsthis->import0bjectFieldData(...):return tries0B OBJECT UPOATE PROPERTIES for deals = ["ótalnane', "description']. If a dealnane or description webhook event came in on May 20, it would1. Update nane on the opportunity (via updateOrCreate ) → touches updated.at2. Return true (bypassing the full hand leöbiectSync / batch queue path3. NOT recalculate 15. voThis is the answer. On May 20, a dralnase or description change webhook arrived. PropertyChangeManaocra:handicOcalDArectUpdate ran, undatecthe opportunity's nane field (touching updated_at to 2026-05-28 18:36:59 ), and returned true - skipping the full batch sync that would haverecalculated is_von. The deal's is_von was already e from a previous sync (when closedlost had probability 0, before May 4), and the May 20 directupdate weohook oiontfixkSummalyTine ooocurynsywns1. Before May 4: Stage 20616 (closmdlost) had probability = 8 in Jiminny's DB (consistent with HubSpot's default behavior for a stage named"closedlost"). Any sync at that time would put "closedlost" in tost() → 1s_closedel, is-wonne2. May 4: Someone manually updated the stage probability to 100 in Jiminny DB (and/or HubSpot updated their stage label/settings). Stage undatedl.ate2826-06-0413. May 20: A HubSpot webhook for dealnase or description property change arrived for this deal. Procertychndleocaldi rectUpdatfired - it updated the opportunity's nane field directly (touching updated_at ) but returned true without queuing a fulll sync. is_von was neverrecalculated4. Result: updated.at: 2826-85-20 looks recent, but the is-von value is stale from a sync that happened before May 4 when the stage probability wastilllotthe tixis to troac a troch sune df thie sond ic anoortunity: sync0noortun ty(404958190945*) wotld tetch ttrom Hub Soot soo denlstran - "closedlosf*, find it in wonfll (probabillity 100 now), and set is.won = 1okl still don't oet it. Atter" mn manual conc-opportunity --teamio 555 --0was set to 1. Howener 136-5n4u Nderstand whst happened before. The opportunity stage was changed on 2026-CCGndalMtikchueine wankelt4 spl...
|
87845
|
NULL
|
NULL
|
NULL
|
|
87845
|
3001
|
7
|
2026-05-28T16:26:42.156553+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985602156_m2.jpg...
|
PhpStorm
|
faVsco.js – console [EU]
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Execute
Explain Plan
Browse Query History...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"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,"bounds":{"left":0.36635637,"top":0.17478053,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","depth":4,"bounds":{"left":0.37632978,"top":0.17478053,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.3879654,"top":0.17318435,"width":0.00731383,"height":0.018355945},"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.39527926,"top":0.17318435,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.4039229,"top":0.09896249,"width":0.008643617,"height":0.01915403},"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.41256648,"top":0.09896249,"width":0.008643617,"height":0.01915403},"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,"bounds":{"left":0.42353722,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
3388717660813814812
|
1347656185060473476
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Execute
Explain Plan
Browse Query History...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87843
|
3001
|
6
|
2026-05-28T16:26:30.442150+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985590442_m2.jpg...
|
PhpStorm
|
faVsco.js – console [EU]
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Code changed:
Hide
Sync Changes...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"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,"bounds":{"left":0.36635637,"top":0.17478053,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","depth":4,"bounds":{"left":0.37632978,"top":0.17478053,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.3879654,"top":0.17318435,"width":0.00731383,"height":0.018355945},"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.39527926,"top":0.17318435,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.4039229,"top":0.09896249,"width":0.008643617,"height":0.01915403},"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.41256648,"top":0.09896249,"width":0.008643617,"height":0.01915403},"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,"bounds":{"left":0.42353722,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"bounds":{"left":0.43218085,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"bounds":{"left":0.44082448,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"bounds":{"left":0.45179522,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"bounds":{"left":0.46276596,"top":0.09896249,"width":0.024268618,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"bounds":{"left":0.4893617,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"bounds":{"left":0.5003325,"top":0.09896249,"width":0.029587766,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.64261967,"top":0.09896249,"width":0.02825798,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"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":"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}]...
|
4694320471963729785
|
1349767247385803396
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Code changed:
Hide
Sync Changes...
|
87840
|
NULL
|
NULL
|
NULL
|
|
87840
|
3001
|
5
|
2026-05-28T16:26:01.279144+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985561279_m2.jpg...
|
PhpStorm
|
faVsco.js – console [EU]
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Code changed:
Hide
Sync Changes
Hide This Notification
31
9
29
3
109
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM team_features where team_id = 1;
SELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922
SELECT * FROM users WHERE team_id = 340; # 12015
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 340
and sa.provider = 'salesforce';
# and sa.provider = 'salesloft';
select * from crm_fields where crm_configuration_id = 270 and object_type = 'event';
# 125558 - Event Type - Event_Type__c
# 125552 - Event Status - Event_Status__c
SELECT * FROM sidekick_settings WHERE team_id = 340;
SELECT * FROM crm_field_values WHERE crm_field_id in (125552);
select * from activities where crm_configuration_id = 270
and type = 'conference' and crm_provider_id IS NOT NULL
and actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;
SELECT * FROM activities WHERE id = 20871677;
SELECT * FROM crm_field_data WHERE activity_id = 20871677;
select * from crm_layouts where crm_configuration_id = 270;
select * from crm_layout_entities where crm_layout_id in (886,887);
SELECT * FROM crm_configurations WHERE id = 270;
select * from playbooks where team_id = 340; # 1514
select * from groups where team_id = 340;
SELECT * FROM crm_fields WHERE id IN (125393, 125401);
select g.name as 'team name', p.name as 'playbook name', f.label as 'activity type field' from groups g
join playbooks p on g.playbook_id = p.id
join crm_fields f on p.activity_field_id = f.id
where g.team_id = 340;
SELECT * FROM activities WHERE uuid_to_bin('0c180357-67d2-419e-a8c3-b832a3490770') = uuid; # 20448716
select * from crm_field_data where object_id = 20448716;
select * from activities where crm_configuration_id = 270 and provider = 'salesloft' order by id desc;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%CybSafe%'; # 343,273,12008
select * from opportunities where team_id = 343;
select * from opportunities where team_id = 343 and crm_provider_id = '18099102526';
select * from opportunities where team_id = 343 and account_id = 945217482;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
select * from accounts where team_id = 343 order by name asc;
select * from stages where crm_configuration_id = 273 and type = 'opportunity';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Voyado%'; # 353,283,12143
SELECT * FROM activities WHERE crm_configuration_id = 283 and account_id = 3777844 order by id desc;
SELECT * FROM accounts WHERE team_id = 353 AND name LIKE '%Salesloft%';
SELECT * FROM activities WHERE id = 20717903;
select * from participants where activity_id IN (20929172,20928605,20928468,20926272,20926271,20926270,20926269,20916499,20916454,20916436,20916435,20900015,20900014,20900013,20897312,20897243,20897241,20897237,20897232,20897229,20893648,20893231,20893230,20893229,20893228,20889784,20885039,20885038,20885037,20885036,20885035,20882728,20882708,20882703,20882702,20869828,20869811,20869806,20869801,20869799,20869798,20869796,20869795,20869794,20869761,20869760,20869759,20868688,20868687,20850340,20847195,20841710,20833967,20827021,20825307,20825305,20825297,20824615,20824400,20823927,20821760,20795588,20794233,20794057,20793710,20785811,20781789,20781394,20781307,20762651,20758453,20758282,20757323,20756643,20756636,20756629,20756627,20756606,20756605,20756604,20756603,20756602,20756600,20756599,20756598,20756595,20756594,20756589,20756587,20756577,20756573,20748918,20748386,20748385,20748384,20748383,20748382,20748381,20748380,20748379,20748377,20748375,20748373,20743301,20717905,20717904,20717903,20717901,20717899);
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 353
and sa.provider = 'salesforce';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%modern world business solutions%'; # 345,275,12016, [EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('3921d399-3fef-4609-a291-b0097a166d43') = uuid;
# id: 20940638, user: 12022, contact: 5305871
SELECT * FROM activity_summary_logs WHERE activity_id = 20940638;
select * from contacts where team_id = 345 and crm_provider_id = '30891432415' order by name asc; # 5305871
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 345
and sa.provider = 'hubspot';
select * from users where team_id = 345 and id = 12022;
SELECT * FROM crm_profiles WHERE user_id = 12022;
SELECT * FROM participants WHERE activity_id = 20940638;
SELECT * FROM users u
JOIN crm_profiles cp ON u.id = cp.user_id
WHERE u.team_id = 345;
select * from contacts where team_id = 345 and crm_provider_id = '30880813535' order by name desc; # 5305871
select * from team_features where team_id = 345;
SELECT * FROM activities WHERE uuid_to_bin('11701e2d-2f82-4dab-a616-1db4fad238df') = uuid; # 21115197
SELECT * FROM participants WHERE activity_id = 20897406;
SELECT * FROM activities WHERE uuid_to_bin('63ba55cd-1abc-447d-83da-0137000005b7') = uuid; # 20953912
SELECT * FROM activities WHERE crm_configuration_id = 275 and provider = 'ringcentral' and title like '%1252629100%';
SELECT * FROM activities WHERE id = 20946641;
SELECT * FROM crm_profiles WHERE user_id = 10211;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120,97,10984, [EMAIL]
SELECT * FROM opportunities WHERE crm_configuration_id = 97 and crm_provider_id = '006N1000006c5PpIAI';
select * from stages where crm_configuration_id = 97 and type = 'opportunity';
select * from opportunities where team_id = 120;
select * from crm_configurations crm join teams t on crm.id = t.crm_id
where 1=1
AND t.current_billing_plan IS NOT NULL
AND crm.auto_sync_activity = 0
and crm.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Exclaimer%'; # 270,205,10053,[EMAIL]
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 270
and sa.provider = 'salesforce';
SELECT * FROM activities WHERE uuid_to_bin('b54df794-2a9a-4957-8d80-09a600ead5f8') = uuid; # 21637956
SELECT * FROM crm_profiles WHERE user_id = 11446;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Cygnetise%'; # 372,300,12554, [EMAIL]
select * from playbooks where team_id = 372;
select * from crm_fields where crm_configuration_id = 300 and object_type = 'event'; # 141340
SELECT * FROM crm_field_values WHERE crm_field_id = 141340;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 372
and sa.provider = 'salesforce';
select * from crm_profiles where crm_configuration_id = 300;
SELECT * FROM crm_configurations WHERE team_id = 372;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Planday%'; # 291,242,11501,[EMAIL]
SELECT * FROM opportunities WHERE team_id = 291 and crm_provider_id = '006bG000005DO86QAG'; # 3207756
select * from crm_field_data where object_id = 3207756;
SELECT * FROM crm_fields WHERE id = 111834;
select f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value
FROM crm_fields f
JOIN crm_field_data fd ON f.id = fd.crm_field_id
WHERE f.crm_configuration_id = 242
AND f.object_type = 'opportunity'
AND fd.object_id IN (3207756)
ORDER BY fd.object_id, fd.updated_at;
SELECT * FROM crm_configurations WHERE auto_connect = 1;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150,[EMAIL]
select * from group_deal_risk_types drgt join groups g on drgt.group_id = g.id
where g.team_id = 187;
select * from `groups` where team_id = 187;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 187
and sa.provider = 'salesforce';
# Destination - 98870 - Destination__c
# Stage - 79014 - StageName
# Land Arrangement - 98856 - Land_Arrangement__c
# Flight - 98848 - Flight__c
# Last activity date - 98812 - LastActivityDate
# Last modified date - 98809 - LastModifiedDate
# Last inbound mail timestamp - 99151 - Last_Inbound_Mail_Timestamp__c
# next call - 98864 - Next_Call__c
select * from crm_fields where crm_configuration_id = 209 and object_type = 'opportunity';
SELECT * FROM crm_layouts WHERE crm_configuration_id = 209;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;
select * from opportunities where team_id = 187 and name LIKE'%Muriel Sal%';
select * from opportunities where team_id = 187 and user_id = 9951 and is_closed = 0;
select * from activities where opportunity_id = 3538248;
SELECT * FROM crm_profiles WHERE user_id = 8150;
select * from deal_risks where opportunity_id = 3538248;
select * from teams where crm_id IS NULL;
SELECT opp.id AS opportunity_id,
u.group_id AS group_id,
MAX(
CASE
WHEN a.type IN ("sms-inbound", "sms-outbound") THEN a.created_at
ELSE a.actual_end_time
END) as last_date
FROM opportunities opp
left join activities a on a.opportunity_id = opp.id
inner join users u on opp.user_id = u.id
where opp.user_id IN (9951)
AND opp.is_closed = 0
and a.status IN ('completed', 'received', 'delivered') OR a.status IS NULL
group by opp.id;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Cybsafe%'; # 343,301,12008,[EMAIL]
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
SELECT * FROM crm_profiles WHERE crm_configuration_id = 301;
SELECT * FROM contacts WHERE id = 6612363;
SELECT * FROM accounts WHERE id = 4235676;
SELECT * FROM opportunities WHERE crm_configuration_id = 301 and crm_provider_id = 32983784868;
select * from opportunity_stages where opportunity_id = 4503759;
# SELECT * FROM opportunities WHERE id = 4569937;
select * from activities where crm_configuration_id = 301;
SELECT * FROM activities WHERE uuid_to_bin('d3b2b28b-c3d0-4c2d-8ed0-eef42855278a') = uuid; # 26330370
SELECT * FROM participants WHERE activity_id = 26330370;
SELECT * FROM teams WHERE id = 375;
select * from playbooks where team_id = 375;
select * from stages where crm_configuration_id = 301 and type = 'opportunity';
select * from teams;
select * from contact_roles;
SELECT * FROM opportunities WHERE team_id = 343 and user_id = 12871 and close_date >= '2024-11-01';
select * from users u join crm_profiles cp on cp.user_id = u.id where u.team_id = 343;
SELECT * FROM crm_field_data WHERE object_id = 3771706;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
SELECT * FROM crm_fields WHERE crm_configuration_id = 301 and object_type = 'opportunity'
and crm_provider_id LIKE "%traffic_light%";
SELECT * FROM crm_field_values WHERE crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531);
SELECT fd.* FROM opportunities o
JOIN crm_field_data fd ON o.id = fd.object_id
WHERE o.team_id = 343
# and o.user_id IS NOT NULL
and fd.crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531)
and fd.value != ''
order by value desc
# group by o.id
;
SELECT * FROM opportunities WHERE id = 3769843;
SELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150, [EMAIL]
SELECT * FROM crm_layouts WHERE crm_configuration_id = 209;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Funding Circle%'; # 220,177,8603,[EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('7a40e99b-3b37-4bb1-b983-325b81801c01') = uuid; # 23139839
SELECT * FROM opportunities WHERE id = 3855992;
SELECT * FROM users WHERE name LIKE '%Angus Pollard%'; # 8988
SELECT * FROM teams WHERE name LIKE '%Story Terrace%'; # 379, 307, 12894
SELECT * FROM crm_fields WHERE crm_configuration_id = 307 and object_type != 'opportunity';
select * from contacts where team_id = 379 and name like '%bebro%'; # 5874411, crm: 77229348507
SELECT * FROM crm_field_data WHERE object_id = 5874411;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 379
and sa.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%mentio%'; # 117, 94, 6371, [EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('82939311-1af0-4506-8546-21e8d1fdf2c1') = uuid;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, [EMAIL]
SELECT * FROM opportunities WHERE team_id = 187 and crm_provider_id = '006Se000008xfvNIAQ'; # 3537793
select * from generic_ai_prompts where subject_id = 3537793;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120, 97, 10984, [EMAIL]
SELECT * FROM crm_configurations WHERE id = 97;
SELECT * FROM crm_layouts WHERE crm_configuration_id = 97;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 355;
SELECT * FROM crm_fields WHERE id = 32682;
select cfd.value, o.* from opportunities o
join crm_field_data cfd on o.id = cfd.object_id and cfd.crm_field_id = 32682
where team_id = 120
and cfd.value != ''
;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 120
and sa.provider = 'salesforce';
select * from opportunities where team_id = 120 and crm_provider_id = '006N1000007X8MAIA0';
SELECT * FROM crm_field_data WHERE object_id = 2313439;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE id = 410;
SELECT * FROM teams WHERE name LIKE '%Local Business Oxford%';
select * from scorecards where team_id = 410;
select * from scorecard_rules;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Funding%'; # 220, 177, 8603, [EMAIL]
select * from activities a
join opportunities o on a.opportunity_id = o.id
join users u on o.user_id = u.id
where a.crm_configuration_id = 177 and a.type LIKE '%email-out%'
# and a.actual_end_time > '2024-12-16 00:00:00'
# and o.remotely_created_at > '2024-12-01 00:00:00'
# and u.group_id = 1014
and u.id = 9021
order by a.id desc;
SELECT * FROM opportunities WHERE id in (3981384,4017346);
SELECT * FROM users WHERE team_id = 220 and id IN (8775, 11435);
select * from users where id = 9021;
select * from inboxes where user_id = 9021;
select * from inbox_emails where inbox_id = 1349 and email_date > '2024-12-18 00:00:00';
select * from email_messages where team_id = 220
and orig_date > '2024-12-16 00:00:00' and orig_date < '2024-12-19 00:00:00'
and subject LIKE '%Personal%'
# and 'from' = '[EMAIL]'
;
select * from activities a
join opportunities o on a.opportunity_id = o.id
where a.user_id = 9021 and a.type LIKE '%email-out%'
and a.actual_end_time > '2024-12-18 00:00:00'
and o.user_id IS NOT NULL
and o.remotely_created_at > '2024-12-01 00:00:00'
order by a.id desc;
SELECT * FROM opportunities WHERE team_id = 220 and name LIKE '%Right Car move Limited%' and id = 3966852;
select * from activities where crm_configuration_id = 177 and type LIKE '%email%' and opportunity_id = 3966852 order by id desc;
select * from team_settings where name IN ('useCloseDate');
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Hurree%'; # 104, 81, 6175, [EMAIL]
SELECT * FROM opportunities WHERE team_id = 104 and name = 'PropOp';
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 104
and sa.provider = 'hubspot';
select * from crm_configurations where last_synced_at > '2025-01-19 01:00:00'
select * from teams where crm_id IS NULL;
select t.name as 'team', u.name as 'owner', u.email, u.phone
from teams t
join activity_providers ap on t.id = ap.team_id
join users u on t.owner_id = u.id
where 1=1
and t.status = 'active'
and ap.is_enabled = 1
# and u.status = 1
and ap.provider = 'ms-teams';
select * from crm_configurations where provider = 'bullhorn'; # 344
SELECT * FROM teams WHERE id = 442; # 14293
select * from users where team_id = 442;
select * from social_accounts sa where sa.sociable_id = 14293;
select * from invitations where team_id = 442;
# [PASSWORD_DOTS]
SELECT * FROM users WHERE email LIKE '%[EMAIL]%'; # 14022
SELECT * FROM teams WHERE id = 429;
select * from opportunities where team_id = 429 and crm_provider_id IN (16157415775, 22246219645);
select * from activities where opportunity_id in (4340436,4353519);
select * from transcription where activity_id IN (25630961,25381771);
select * from generic_ai_prompts where subject_id IN (4353519);
SELECT
a.id as activity_id,
a.opportunity_id,
a.type as activity_type,
a.language,
CONCAT(a.title, a.description) AS mail_content,
e.from AS mail_from,
e.to AS mail_to,
e.subject AS mail_subject,
e.body AS mail_body,
p.type as prompt_type,
p.status as prompt_status,
p.content AS prompt_content,
a.actual_start_time as created_at
FROM activities a
LEFT JOIN ai_prompts p ON a.transcription_id = p.transcription_id AND p.deleted_at IS NULL
LEFT JOIN email_messages e ON a.id = e.activity_id
WHERE a.actual_start_time > '2024-01-01 00:00:00'
AND a.opportunity_id IN (4353519)
AND a.status IN ('completed', 'received', 'delivered')
AND a.deleted_at IS NULL
AND a.type NOT IN ('sms-inbound', 'sms-outbound')
ORDER BY a.opportunity_id ASC, a.id ASC;
SELECT * FROM users WHERE name LIKE '%George Fierstone%'; # 14293
SELECT * FROM teams WHERE id = 442;
SELECT * FROM crm_configurations WHERE id = 344;
select * from team_features where team_id = 442;
select * from groups where team_id = 442;
select * from playbooks where team_id = 442;
select * from playbook_categories where playbook_id = 1729;
select * from crm_fields where crm_configuration_id = 344 and id = 172024;
SELECT * FROM crm_field_values WHERE crm_field_id = 172024;
select * from crm_layouts where crm_configuration_id = 344;
select * from playbook_layouts where playbook_id = 1729;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 221, 9444
select s.*
# , s.sent_at, u.name, a.*
from activity_summary_logs s
inner join activities a on a.id = s.activity_id
inner join users u on u.id = a.user_id
where a.crm_configuration_id = 356
and s.sent_at > date_sub(now(), interval 60 day)
order by a.actual_end_time desc;
select * from activities a
# inner join activity_summary_logs s on s.activity_id = a.id
where a.crm_configuration_id = 356 and a.actual_end_time > date_sub(now(), interval 60 day)
# and a.crm_provider_id is not null
# and provider <> 'ringcentral'
and status = 'completed'
order by a.actual_end_time desc;
select * from teams order by id desc; # 17328, 32, 17830, [EMAIL]
SELECT * FROM users;
SELECT * FROM users where team_id = 260 and status = 1; # 201 - 150 active
SELECT * FROM teams WHERE id = 260;
select * from team_settings where team_id = 260;
select * from crm_configurations where team_id = 260;
SELECT * FROM crm_layouts WHERE crm_configuration_id = 356;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1184;
select * from accounts where crm_configuration_id = 221 order by id desc; # 7000
select * from leads where crm_configuration_id = 221 order by id desc; # 0
select * from contacts where crm_configuration_id = 221 order by id desc; # 200 000
select * from opportunities where crm_configuration_id = 221 order by id desc; # 0
select * from crm_profiles where crm_configuration_id = 221 order by id desc; # 23
select * from crm_fields where crm_configuration_id = 221;
select * from crm_field_values where crm_field_id = 5302 order by id desc;
select * from crm_layouts where crm_configuration_id = 221 order by id desc;
select * from stages where crm_configuration_id = 221 order by id desc;
select * from accounts where crm_configuration_id = 356 order by id desc; # 7000
select * from leads where crm_configuration_id = 356 order by id desc; # 0
select * from contacts where crm_configuration_id = 356 order by id desc; # 200 000
select * from opportunities where crm_configuration_id = 356 order by id desc; # 0
select * from crm_profiles where crm_configuration_id = 356 order by id desc; # 23
select * from crm_fields where crm_configuration_id = 356;
select * from crm_field_values where crm_field_id = 5302 order by id desc;
select * from crm_layouts where crm_configuration_id = 356 order by id desc;
select * from stages where crm_configuration_id = 356 order by id desc;
select * from playbooks where team_id = 260 order by id desc; # 4 (2 deleted)
select * from groups where team_id = 260 order by id desc; # 27 groups, (2 deleted)
select * from playbook_layouts where playbook_id IN (1410,1409,1276,1254); # 4
select ce.* from calendars c
join users u on c.user_id = u.id
join calendar_events ce on c.id = ce.calendar_id
where u.team_id = 260
and (ce.start_time > '2025-02-21 00:00:00')
;
# calendar events 1207
#
select * from opportunities where team_id = 260;
SELECT * FROM crm_field_data WHERE object_id = 4696496;
select * from activities where crm_configuration_id = 356 and crm_provider_id IS NOT NULL;
select * from activities where crm_configuration_id IN (221) and provider NOT IN ('ms-teams', 'uploader', 'zoom-bot')
# and type = 'conference' and status = 'scheduled' and activities.is_internal = 0
and created_at > '2024-03-01 00:00:00'
order by id desc; # 880 000, ringcentral, avaya
SELECT * FROM participants WHERE activity_id = 26371744;
# all activities 942 000 +
# conference 7385 - scheduled 984 - external 343
select * from activities where id = 26321812;
select * from participants where activity_id = 26321812;
select * from participants where activity_id in (26414510,26414514,26414516,26414604,26414653,26414655);
select * from leads where id in (720428,689175,731546,645866,621037);
select * from users where id = 13841;
select * from opportunities where user_id = 9541;
select * from stages where id = 15900;
select * from accounts where
# id IN (4160055,5053725,4965303,4896434)
id in (4584518,3249934,3218025,3891133,3399450,4172999,4485161,3101785,4587203,3070816,2870343,2870341,3563940,4550846,3424464,3249963,2870342)
;
select * from activities where id = 26654935;
SELECT * FROM opportunities WHERE id = 4803458;
SELECT * FROM opportunities where team_id = 260 and user_id = 13841 AND stage_id = 15900;
SELECT id, uuid, provider, type, lead_id, account_id, contact_id, opportunity_id, stage_id, status, recording_state, title, actual_start_time, actual_end_time
FROM activities WHERE user_id = 13841 AND opportunity_id IN (4729783, 4731717, 4731726, 4732064, 4732849, 4803458, 4813213);
SELECT DISTINCT
o.id, o.stage_id, s.name, a.title,
a.*
FROM activities a
# INNER JOIN tracks t ON a.id = t.activity_id
INNER JOIN users u ON a.user_id = u.id
INNER JOIN teams team ON u.team_id = team.id
INNER JOIN groups g ON u.group_id = g.id
INNER JOIN opportunities o ON a.opportunity_id = o.id
INNER JOIN stages s ON o.stage_id = s.id
WHERE
a.crm_configuration_id = 356
AND a.status IN ('completed', 'failed')
AND a.recording_state != 'stopped'
# and a.user_id = 13841
AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')
AND team.uuid = uuid_to_bin('a607fba7-452e-4683-b2af-00d6cb52c93c')
AND g.uuid = uuid_to_bin('b5d69e40-24a0-4c16-810b-5fa462299f94')
AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')
# AND t.type IN ('audio', 'video')
AND (
(a.actual_start_time BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59')
OR
(
a.actual_start_time IS NULL
AND a.type IN ('sms-outbound', 'sms-inbound')
AND a.created_at BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59'
)
)
AND (
a.is_private = 0
OR (
a.is_private = 1
AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')
)
)
AND (
# s.id = 15900
s.uuid = uuid_to_bin('04ca1c26-c666-4268-a129-419c0acffd73')
OR s.uuid IS NULL -- Include records without opportunity stage
)
ORDER BY a.actual_end_time DESC;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lead Forensics%'; # 190, 162, 8474, [EMAIL]
SELECT * FROM users WHERE team_id = 190;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 190
and sa.provider = 'hubspot';
select * from role_user where user_id = 8474;
select * from crm_configurations where provider = 'bullhorn';
SELECT * FROM opportunities WHERE uuid_to_bin('94578249-65ec-4205-90f2-7d1a7d5ab64a') = uuid;
SELECT * FROM users WHERE uuid_to_bin('26dbadeb-926f-4150-b11b-771b9d4c2f9a') = uuid;
SELECT * FROM opportunities ...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"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,"bounds":{"left":0.36635637,"top":0.17478053,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","depth":4,"bounds":{"left":0.37632978,"top":0.17478053,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.3879654,"top":0.17318435,"width":0.00731383,"height":0.018355945},"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.39527926,"top":0.17318435,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.4039229,"top":0.09896249,"width":0.008643617,"height":0.01915403},"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.41256648,"top":0.09896249,"width":0.008643617,"height":0.01915403},"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,"bounds":{"left":0.42353722,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"bounds":{"left":0.43218085,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"bounds":{"left":0.44082448,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"bounds":{"left":0.45179522,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"bounds":{"left":0.46276596,"top":0.09896249,"width":0.024268618,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"bounds":{"left":0.4893617,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"bounds":{"left":0.5003325,"top":0.09896249,"width":0.029587766,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.64261967,"top":0.09896249,"width":0.02825798,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"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":"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":"AXStaticText","text":"31","depth":4,"bounds":{"left":0.60039896,"top":0.123703115,"width":0.009640957,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"9","depth":4,"bounds":{"left":0.61203456,"top":0.123703115,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"29","depth":4,"bounds":{"left":0.62200797,"top":0.123703115,"width":0.010305851,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.6343085,"top":0.123703115,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"109","depth":4,"bounds":{"left":0.6442819,"top":0.123703115,"width":0.011968086,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.65791225,"top":0.12210695,"width":0.00731383,"height":0.018355945},"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.66522604,"top":0.12210695,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT * FROM team_features where team_id = 1;\n\nSELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922\nSELECT * FROM users WHERE team_id = 340; # 12015\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 340\nand sa.provider = 'salesforce';\n# and sa.provider = 'salesloft';\n\nselect * from crm_fields where crm_configuration_id = 270 and object_type = 'event';\n# 125558 - Event Type - Event_Type__c\n# 125552 - Event Status - Event_Status__c\n\nSELECT * FROM sidekick_settings WHERE team_id = 340;\n\nSELECT * FROM crm_field_values WHERE crm_field_id in (125552);\n\nselect * from activities where crm_configuration_id = 270\nand type = 'conference' and crm_provider_id IS NOT NULL\nand actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;\n\nSELECT * FROM activities WHERE id = 20871677;\nSELECT * FROM crm_field_data WHERE activity_id = 20871677;\n\nselect * from crm_layouts where crm_configuration_id = 270;\nselect * from crm_layout_entities where crm_layout_id in (886,887);\n\nSELECT * FROM crm_configurations WHERE id = 270;\n\nselect * from playbooks where team_id = 340; # 1514\nselect * from groups where team_id = 340;\nSELECT * FROM crm_fields WHERE id IN (125393, 125401);\n\nselect g.name as 'team name', p.name as 'playbook name', f.label as 'activity type field' from groups g\njoin playbooks p on g.playbook_id = p.id\njoin crm_fields f on p.activity_field_id = f.id\nwhere g.team_id = 340;\n\nSELECT * FROM activities WHERE uuid_to_bin('0c180357-67d2-419e-a8c3-b832a3490770') = uuid; # 20448716\nselect * from crm_field_data where object_id = 20448716;\n\nselect * from activities where crm_configuration_id = 270 and provider = 'salesloft' order by id desc;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%CybSafe%'; # 343,273,12008\nselect * from opportunities where team_id = 343;\nselect * from opportunities where team_id = 343 and crm_provider_id = '18099102526';\nselect * from opportunities where team_id = 343 and account_id = 945217482;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nselect * from accounts where team_id = 343 order by name asc;\n\nselect * from stages where crm_configuration_id = 273 and type = 'opportunity';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Voyado%'; # 353,283,12143\nSELECT * FROM activities WHERE crm_configuration_id = 283 and account_id = 3777844 order by id desc;\nSELECT * FROM accounts WHERE team_id = 353 AND name LIKE '%Salesloft%';\nSELECT * FROM activities WHERE id = 20717903;\n\nselect * from participants where activity_id IN (20929172,20928605,20928468,20926272,20926271,20926270,20926269,20916499,20916454,20916436,20916435,20900015,20900014,20900013,20897312,20897243,20897241,20897237,20897232,20897229,20893648,20893231,20893230,20893229,20893228,20889784,20885039,20885038,20885037,20885036,20885035,20882728,20882708,20882703,20882702,20869828,20869811,20869806,20869801,20869799,20869798,20869796,20869795,20869794,20869761,20869760,20869759,20868688,20868687,20850340,20847195,20841710,20833967,20827021,20825307,20825305,20825297,20824615,20824400,20823927,20821760,20795588,20794233,20794057,20793710,20785811,20781789,20781394,20781307,20762651,20758453,20758282,20757323,20756643,20756636,20756629,20756627,20756606,20756605,20756604,20756603,20756602,20756600,20756599,20756598,20756595,20756594,20756589,20756587,20756577,20756573,20748918,20748386,20748385,20748384,20748383,20748382,20748381,20748380,20748379,20748377,20748375,20748373,20743301,20717905,20717904,20717903,20717901,20717899);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 353\nand sa.provider = 'salesforce';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%modern world business solutions%'; # 345,275,12016, l.atkinson@mwbsolutions.co.uk\nSELECT * FROM activities WHERE uuid_to_bin('3921d399-3fef-4609-a291-b0097a166d43') = uuid;\n# id: 20940638, user: 12022, contact: 5305871\nSELECT * FROM activity_summary_logs WHERE activity_id = 20940638;\nselect * from contacts where team_id = 345 and crm_provider_id = '30891432415' order by name asc; # 5305871\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 345\nand sa.provider = 'hubspot';\n\nselect * from users where team_id = 345 and id = 12022;\nSELECT * FROM crm_profiles WHERE user_id = 12022;\nSELECT * FROM participants WHERE activity_id = 20940638;\nSELECT * FROM users u\nJOIN crm_profiles cp ON u.id = cp.user_id\nWHERE u.team_id = 345;\n\nselect * from contacts where team_id = 345 and crm_provider_id = '30880813535' order by name desc; # 5305871\n\nselect * from team_features where team_id = 345;\nSELECT * FROM activities WHERE uuid_to_bin('11701e2d-2f82-4dab-a616-1db4fad238df') = uuid; # 21115197\nSELECT * FROM participants WHERE activity_id = 20897406;\n\n\n\nSELECT * FROM activities WHERE uuid_to_bin('63ba55cd-1abc-447d-83da-0137000005b7') = uuid; # 20953912\nSELECT * FROM activities WHERE crm_configuration_id = 275 and provider = 'ringcentral' and title like '%1252629100%';\n\n\nSELECT * FROM activities WHERE id = 20946641;\nSELECT * FROM crm_profiles WHERE user_id = 10211;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120,97,10984, triger@lunio.ai\nSELECT * FROM opportunities WHERE crm_configuration_id = 97 and crm_provider_id = '006N1000006c5PpIAI';\nselect * from stages where crm_configuration_id = 97 and type = 'opportunity';\nselect * from opportunities where team_id = 120;\n\n\nselect * from crm_configurations crm join teams t on crm.id = t.crm_id\nwhere 1=1\nAND t.current_billing_plan IS NOT NULL\nAND crm.auto_sync_activity = 0\nand crm.provider = 'hubspot';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Exclaimer%'; # 270,205,10053,james.lewendon@exclaimer.com\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 270\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('b54df794-2a9a-4957-8d80-09a600ead5f8') = uuid; # 21637956\nSELECT * FROM crm_profiles WHERE user_id = 11446;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Cygnetise%'; # 372,300,12554, alex.chikly@cygnetise.com\nselect * from playbooks where team_id = 372;\nselect * from crm_fields where crm_configuration_id = 300 and object_type = 'event'; # 141340\nSELECT * FROM crm_field_values WHERE crm_field_id = 141340;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 372\nand sa.provider = 'salesforce';\n\nselect * from crm_profiles where crm_configuration_id = 300;\nSELECT * FROM crm_configurations WHERE team_id = 372;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Planday%'; # 291,242,11501,mfa@planday.com\nSELECT * FROM opportunities WHERE team_id = 291 and crm_provider_id = '006bG000005DO86QAG'; # 3207756\nselect * from crm_field_data where object_id = 3207756;\nSELECT * FROM crm_fields WHERE id = 111834;\n\nselect f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value\nFROM crm_fields f\nJOIN crm_field_data fd ON f.id = fd.crm_field_id\nWHERE f.crm_configuration_id = 242\nAND f.object_type = 'opportunity'\nAND fd.object_id IN (3207756)\nORDER BY fd.object_id, fd.updated_at;\n\nSELECT * FROM crm_configurations WHERE auto_connect = 1;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150,salesforce-admin@tourlane.com\nselect * from group_deal_risk_types drgt join groups g on drgt.group_id = g.id\nwhere g.team_id = 187;\n\nselect * from `groups` where team_id = 187;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 187\nand sa.provider = 'salesforce';\n\n# Destination - 98870 - Destination__c\n# Stage - 79014 - StageName\n# Land Arrangement - 98856 - Land_Arrangement__c\n# Flight - 98848 - Flight__c\n# Last activity date - 98812 - LastActivityDate\n# Last modified date - 98809 - LastModifiedDate\n# Last inbound mail timestamp - 99151 - Last_Inbound_Mail_Timestamp__c\n# next call - 98864 - Next_Call__c\n\nselect * from crm_fields where crm_configuration_id = 209 and object_type = 'opportunity';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 209;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;\n\nselect * from opportunities where team_id = 187 and name LIKE'%Muriel Sal%';\nselect * from opportunities where team_id = 187 and user_id = 9951 and is_closed = 0;\nselect * from activities where opportunity_id = 3538248;\n\nSELECT * FROM crm_profiles WHERE user_id = 8150;\n\nselect * from deal_risks where opportunity_id = 3538248;\n\nselect * from teams where crm_id IS NULL;\n\nSELECT opp.id AS opportunity_id,\n u.group_id AS group_id,\n MAX(\n CASE\n WHEN a.type IN (\"sms-inbound\", \"sms-outbound\") THEN a.created_at\n ELSE a.actual_end_time\n END) as last_date\nFROM opportunities opp\nleft join activities a on a.opportunity_id = opp.id\ninner join users u on opp.user_id = u.id\nwhere opp.user_id IN (9951)\n\nAND opp.is_closed = 0\nand a.status IN ('completed', 'received', 'delivered') OR a.status IS NULL\ngroup by opp.id;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Cybsafe%'; # 343,301,12008,polly.morphew@cybsafe.com\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 301;\nSELECT * FROM contacts WHERE id = 6612363;\nSELECT * FROM accounts WHERE id = 4235676;\nSELECT * FROM opportunities WHERE crm_configuration_id = 301 and crm_provider_id = 32983784868;\nselect * from opportunity_stages where opportunity_id = 4503759;\n# SELECT * FROM opportunities WHERE id = 4569937;\n\nselect * from activities where crm_configuration_id = 301;\nSELECT * FROM activities WHERE uuid_to_bin('d3b2b28b-c3d0-4c2d-8ed0-eef42855278a') = uuid; # 26330370\nSELECT * FROM participants WHERE activity_id = 26330370;\n\nSELECT * FROM teams WHERE id = 375;\nselect * from playbooks where team_id = 375;\n\nselect * from stages where crm_configuration_id = 301 and type = 'opportunity';\n\nselect * from teams;\nselect * from contact_roles;\n\nSELECT * FROM opportunities WHERE team_id = 343 and user_id = 12871 and close_date >= '2024-11-01';\n\nselect * from users u join crm_profiles cp on cp.user_id = u.id where u.team_id = 343;\n\nSELECT * FROM crm_field_data WHERE object_id = 3771706;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_fields WHERE crm_configuration_id = 301 and object_type = 'opportunity'\nand crm_provider_id LIKE \"%traffic_light%\";\nSELECT * FROM crm_field_values WHERE crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531);\n\nSELECT fd.* FROM opportunities o\nJOIN crm_field_data fd ON o.id = fd.object_id\nWHERE o.team_id = 343\n# and o.user_id IS NOT NULL\nand fd.crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531)\nand fd.value != ''\norder by value desc\n# group by o.id\n;\n\nSELECT * FROM opportunities WHERE id = 3769843;\n\nSELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150, salesforce-admin@tourlane.com\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 209;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Funding Circle%'; # 220,177,8603,aswini.mishra@fundingcircle.com\nSELECT * FROM activities WHERE uuid_to_bin('7a40e99b-3b37-4bb1-b983-325b81801c01') = uuid; # 23139839\n\n\nSELECT * FROM opportunities WHERE id = 3855992;\n\nSELECT * FROM users WHERE name LIKE '%Angus Pollard%'; # 8988\n\nSELECT * FROM teams WHERE name LIKE '%Story Terrace%'; # 379, 307, 12894\nSELECT * FROM crm_fields WHERE crm_configuration_id = 307 and object_type != 'opportunity';\n\nselect * from contacts where team_id = 379 and name like '%bebro%'; # 5874411, crm: 77229348507\nSELECT * FROM crm_field_data WHERE object_id = 5874411;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 379\nand sa.provider = 'hubspot';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%mentio%'; # 117, 94, 6371, nikhil.kumar@mention-me.com\nSELECT * FROM activities WHERE uuid_to_bin('82939311-1af0-4506-8546-21e8d1fdf2c1') = uuid;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, salesforce-admin@tourlane.com\nSELECT * FROM opportunities WHERE team_id = 187 and crm_provider_id = '006Se000008xfvNIAQ'; # 3537793\nselect * from generic_ai_prompts where subject_id = 3537793;\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120, 97, 10984, triger@lunio.ai\nSELECT * FROM crm_configurations WHERE id = 97;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 97;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 355;\nSELECT * FROM crm_fields WHERE id = 32682;\n\nselect cfd.value, o.* from opportunities o\njoin crm_field_data cfd on o.id = cfd.object_id and cfd.crm_field_id = 32682\nwhere team_id = 120\nand cfd.value != ''\n;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 120\nand sa.provider = 'salesforce';\n\nselect * from opportunities where team_id = 120 and crm_provider_id = '006N1000007X8MAIA0';\nSELECT * FROM crm_field_data WHERE object_id = 2313439;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE id = 410;\nSELECT * FROM teams WHERE name LIKE '%Local Business Oxford%';\nselect * from scorecards where team_id = 410;\nselect * from scorecard_rules;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Funding%'; # 220, 177, 8603, aswini.mishra@fundingcircle.com\nselect * from activities a\njoin opportunities o on a.opportunity_id = o.id\njoin users u on o.user_id = u.id\nwhere a.crm_configuration_id = 177 and a.type LIKE '%email-out%'\n# and a.actual_end_time > '2024-12-16 00:00:00'\n# and o.remotely_created_at > '2024-12-01 00:00:00'\n# and u.group_id = 1014\nand u.id = 9021\norder by a.id desc;\nSELECT * FROM opportunities WHERE id in (3981384,4017346);\nSELECT * FROM users WHERE team_id = 220 and id IN (8775, 11435);\n\nselect * from users where id = 9021;\nselect * from inboxes where user_id = 9021;\n\nselect * from inbox_emails where inbox_id = 1349 and email_date > '2024-12-18 00:00:00';\n\nselect * from email_messages where team_id = 220\nand orig_date > '2024-12-16 00:00:00' and orig_date < '2024-12-19 00:00:00'\nand subject LIKE '%Personal%'\n# and 'from' = 'credit@fundingcircle.com'\n;\n\nselect * from activities a\njoin opportunities o on a.opportunity_id = o.id\nwhere a.user_id = 9021 and a.type LIKE '%email-out%'\nand a.actual_end_time > '2024-12-18 00:00:00'\nand o.user_id IS NOT NULL\nand o.remotely_created_at > '2024-12-01 00:00:00'\norder by a.id desc;\n\nSELECT * FROM opportunities WHERE team_id = 220 and name LIKE '%Right Car move Limited%' and id = 3966852;\nselect * from activities where crm_configuration_id = 177 and type LIKE '%email%' and opportunity_id = 3966852 order by id desc;\n\nselect * from team_settings where name IN ('useCloseDate');\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Hurree%'; # 104, 81, 6175, jfarrell@hurree.co\nSELECT * FROM opportunities WHERE team_id = 104 and name = 'PropOp';\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 104\nand sa.provider = 'hubspot';\n\nselect * from crm_configurations where last_synced_at > '2025-01-19 01:00:00'\nselect * from teams where crm_id IS NULL;\n\nselect t.name as 'team', u.name as 'owner', u.email, u.phone\nfrom teams t\njoin activity_providers ap on t.id = ap.team_id\njoin users u on t.owner_id = u.id\nwhere 1=1\n and t.status = 'active'\n and ap.is_enabled = 1\n# and u.status = 1\n and ap.provider = 'ms-teams';\n\nselect * from crm_configurations where provider = 'bullhorn'; # 344\nSELECT * FROM teams WHERE id = 442; # 14293\nselect * from users where team_id = 442;\nselect * from social_accounts sa where sa.sociable_id = 14293;\nselect * from invitations where team_id = 442;\n\n# ********************************************************************************************************\nSELECT * FROM users WHERE email LIKE '%nea.liikamaa@eletive.com%'; # 14022\nSELECT * FROM teams WHERE id = 429;\nselect * from opportunities where team_id = 429 and crm_provider_id IN (16157415775, 22246219645);\nselect * from activities where opportunity_id in (4340436,4353519);\n\nselect * from transcription where activity_id IN (25630961,25381771);\nselect * from generic_ai_prompts where subject_id IN (4353519);\n\nSELECT\n a.id as activity_id,\n a.opportunity_id,\n a.type as activity_type,\n a.language,\n CONCAT(a.title, a.description) AS mail_content,\n e.from AS mail_from,\n e.to AS mail_to,\n e.subject AS mail_subject,\n e.body AS mail_body,\n p.type as prompt_type,\n p.status as prompt_status,\n p.content AS prompt_content,\n a.actual_start_time as created_at\nFROM activities a\n LEFT JOIN ai_prompts p ON a.transcription_id = p.transcription_id AND p.deleted_at IS NULL\n LEFT JOIN email_messages e ON a.id = e.activity_id\nWHERE a.actual_start_time > '2024-01-01 00:00:00'\n AND a.opportunity_id IN (4353519)\n AND a.status IN ('completed', 'received', 'delivered')\n AND a.deleted_at IS NULL\n AND a.type NOT IN ('sms-inbound', 'sms-outbound')\nORDER BY a.opportunity_id ASC, a.id ASC;\n\nSELECT * FROM users WHERE name LIKE '%George Fierstone%'; # 14293\nSELECT * FROM teams WHERE id = 442;\nSELECT * FROM crm_configurations WHERE id = 344;\nselect * from team_features where team_id = 442;\nselect * from groups where team_id = 442;\nselect * from playbooks where team_id = 442;\nselect * from playbook_categories where playbook_id = 1729;\nselect * from crm_fields where crm_configuration_id = 344 and id = 172024;\nSELECT * FROM crm_field_values WHERE crm_field_id = 172024;\nselect * from crm_layouts where crm_configuration_id = 344;\nselect * from playbook_layouts where playbook_id = 1729;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 221, 9444\n\nselect s.*\n# , s.sent_at, u.name, a.*\nfrom activity_summary_logs s\ninner join activities a on a.id = s.activity_id\ninner join users u on u.id = a.user_id\nwhere a.crm_configuration_id = 356\nand s.sent_at > date_sub(now(), interval 60 day)\norder by a.actual_end_time desc;\n\nselect * from activities a\n# inner join activity_summary_logs s on s.activity_id = a.id\nwhere a.crm_configuration_id = 356 and a.actual_end_time > date_sub(now(), interval 60 day)\n# and a.crm_provider_id is not null\n# and provider <> 'ringcentral'\nand status = 'completed'\norder by a.actual_end_time desc;\n\nselect * from teams order by id desc; # 17328, 32, 17830, integration-account@jiminny.com\nSELECT * FROM users;\nSELECT * FROM users where team_id = 260 and status = 1; # 201 - 150 active\nSELECT * FROM teams WHERE id = 260;\nselect * from team_settings where team_id = 260;\nselect * from crm_configurations where team_id = 260;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 356;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1184;\n\nselect * from accounts where crm_configuration_id = 221 order by id desc; # 7000\nselect * from leads where crm_configuration_id = 221 order by id desc; # 0\nselect * from contacts where crm_configuration_id = 221 order by id desc; # 200 000\nselect * from opportunities where crm_configuration_id = 221 order by id desc; # 0\nselect * from crm_profiles where crm_configuration_id = 221 order by id desc; # 23\nselect * from crm_fields where crm_configuration_id = 221;\nselect * from crm_field_values where crm_field_id = 5302 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 221 order by id desc;\nselect * from stages where crm_configuration_id = 221 order by id desc;\n\nselect * from accounts where crm_configuration_id = 356 order by id desc; # 7000\nselect * from leads where crm_configuration_id = 356 order by id desc; # 0\nselect * from contacts where crm_configuration_id = 356 order by id desc; # 200 000\nselect * from opportunities where crm_configuration_id = 356 order by id desc; # 0\nselect * from crm_profiles where crm_configuration_id = 356 order by id desc; # 23\nselect * from crm_fields where crm_configuration_id = 356;\nselect * from crm_field_values where crm_field_id = 5302 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 356 order by id desc;\nselect * from stages where crm_configuration_id = 356 order by id desc;\n\nselect * from playbooks where team_id = 260 order by id desc; # 4 (2 deleted)\nselect * from groups where team_id = 260 order by id desc; # 27 groups, (2 deleted)\nselect * from playbook_layouts where playbook_id IN (1410,1409,1276,1254); # 4\nselect ce.* from calendars c\njoin users u on c.user_id = u.id\njoin calendar_events ce on c.id = ce.calendar_id\nwhere u.team_id = 260\nand (ce.start_time > '2025-02-21 00:00:00')\n;\n# calendar events 1207\n#\n\nselect * from opportunities where team_id = 260;\nSELECT * FROM crm_field_data WHERE object_id = 4696496;\n\nselect * from activities where crm_configuration_id = 356 and crm_provider_id IS NOT NULL;\nselect * from activities where crm_configuration_id IN (221) and provider NOT IN ('ms-teams', 'uploader', 'zoom-bot')\n# and type = 'conference' and status = 'scheduled' and activities.is_internal = 0\nand created_at > '2024-03-01 00:00:00'\norder by id desc; # 880 000, ringcentral, avaya\nSELECT * FROM participants WHERE activity_id = 26371744;\n\n# all activities 942 000 +\n# conference 7385 - scheduled 984 - external 343\n\nselect * from activities where id = 26321812;\nselect * from participants where activity_id = 26321812;\nselect * from participants where activity_id in (26414510,26414514,26414516,26414604,26414653,26414655);\nselect * from leads where id in (720428,689175,731546,645866,621037);\n\nselect * from users where id = 13841;\nselect * from opportunities where user_id = 9541;\nselect * from stages where id = 15900;\n\nselect * from accounts where\n# id IN (4160055,5053725,4965303,4896434)\nid in (4584518,3249934,3218025,3891133,3399450,4172999,4485161,3101785,4587203,3070816,2870343,2870341,3563940,4550846,3424464,3249963,2870342)\n;\n\nselect * from activities where id = 26654935;\nSELECT * FROM opportunities WHERE id = 4803458;\n\nSELECT * FROM opportunities where team_id = 260 and user_id = 13841 AND stage_id = 15900;\nSELECT id, uuid, provider, type, lead_id, account_id, contact_id, opportunity_id, stage_id, status, recording_state, title, actual_start_time, actual_end_time\nFROM activities WHERE user_id = 13841 AND opportunity_id IN (4729783, 4731717, 4731726, 4732064, 4732849, 4803458, 4813213);\n\nSELECT DISTINCT\n o.id, o.stage_id, s.name, a.title,\n a.*\nFROM activities a\n# INNER JOIN tracks t ON a.id = t.activity_id\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams team ON u.team_id = team.id\nINNER JOIN groups g ON u.group_id = g.id\nINNER JOIN opportunities o ON a.opportunity_id = o.id\nINNER JOIN stages s ON o.stage_id = s.id\nWHERE\n a.crm_configuration_id = 356\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n# and a.user_id = 13841\n AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')\n AND team.uuid = uuid_to_bin('a607fba7-452e-4683-b2af-00d6cb52c93c')\n AND g.uuid = uuid_to_bin('b5d69e40-24a0-4c16-810b-5fa462299f94')\n\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND t.type IN ('audio', 'video')\n AND (\n (a.actual_start_time BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59')\n OR\n (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59'\n )\n )\n AND (\n a.is_private = 0\n OR (\n a.is_private = 1\n AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')\n )\n )\n AND (\n# s.id = 15900\n s.uuid = uuid_to_bin('04ca1c26-c666-4268-a129-419c0acffd73')\n OR s.uuid IS NULL -- Include records without opportunity stage\n )\n\nORDER BY a.actual_end_time DESC;\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lead Forensics%'; # 190, 162, 8474, willsc@leadforensics.com\nSELECT * FROM users WHERE team_id = 190;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 190\nand sa.provider = 'hubspot';\n\nselect * from role_user where user_id = 8474;\n\nselect * from crm_configurations where provider = 'bullhorn';\n\nSELECT * FROM opportunities WHERE uuid_to_bin('94578249-65ec-4205-90f2-7d1a7d5ab64a') = uuid;\nSELECT * FROM users WHERE uuid_to_bin('26dbadeb-926f-4150-b11b-771b9d4c2f9a') = uuid;\n\nSELECT * FROM opportunities WHERE id = 4732493;\nselect * from activities where opportunity_id = 4732493;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE id = 443; # 358, 14315, andrea.romano@correrenaturale.com\nSELECT * FROM opportunities WHERE team_id = 443;\n\nSELECT a.id, a.type, a.user_id, a.status, a.deleted_at, u.name, u.email, u.team_id as activity_team_id, u.status, u.deleted_at, t.name, t.status, s.team_id as stage_team_id\nFROM activities AS a\nJOIN stages AS s ON a.stage_id = s.id\nJOIN users AS u ON u.id = a.user_id\nJOIN teams AS t ON t.id = s.team_id\nWHERE u.team_id <> s.team_id and t.id > 135;\n\n\nSELECT\n crm_configuration_id,\n crm_provider_id,\n COUNT(*) as duplicate_count,\n GROUP_CONCAT(id) as stage_ids,\n GROUP_CONCAT(name) as stage_names\nFROM stages\nGROUP BY crm_configuration_id, crm_provider_id\nHAVING COUNT(*) > 1\nORDER BY duplicate_count DESC;\n\nselect * from stages where id IN (14898,14907);\n\nselect * from business_processes;\n\nSELECT *\nFROM crm_configurations\nWHERE team_id IN (\n SELECT team_id\n FROM crm_configurations\n GROUP BY team_id\n HAVING COUNT(*) > 1\n)\nORDER BY team_id;\n\nSELECT *\nFROM teams\nWHERE crm_id IN (\n SELECT crm_id\n FROM teams\n GROUP BY crm_id\n HAVING COUNT(*) > 1\n)\nORDER BY crm_id;\n\n# ***************************************************************************\nselect * from crm_configurations where provider = 'integration-app';\nSELECT * FROM teams WHERE id = 443; # Correre Naturale 358 14315 andrea.romano@correrenaturale.com\nselect * from activities where crm_configuration_id = 358 order by actual_end_time desc;\nselect id, uuid, actual_end_time, crm_provider_id, is_internal, playbook_category_id, type, user_id, lead_id, contact_id, account_id, opportunity_id, status, title from activities where crm_configuration_id = 358 order by actual_end_time desc;\nselect * from team_features where team_id = 358;\nselect * from activity_summary_logs;\n\nselect * from teams where id = 406;\n\n# ************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Sportfive%'; # 267, 202, 14637, srv.salesforce@sportfive.com\nselect * from activities where crm_configuration_id = 202 order by actual_end_time desc;\n\nSELECT * FROM users where id = 14637;\nSELECT * FROM teams where id = 267;\nSELECT * FROM groups where id = 1118;\n\nselect g.name, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\ninner join groups g on g.id = u.group_id\nwhere a.crm_configuration_id = 202\nand a.is_internal = 0\nand (a.scheduled_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type = 'conference'\nand a.status != 'completed'\nand a.external_id is not null\norder by a.scheduled_start_time desc;\n\nSELECT * FROM activities\nWHERE crm_configuration_id = 202\n AND status IN ('completed', 'failed')\n AND recording_state != 'stopped'\n AND type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n AND (is_private = 0 OR user_id = 14637)\n AND (\n (\n actual_start_time BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n ) OR (\n actual_start_time IS NULL\n AND type IN ('sms-outbound', 'sms-inbound')\n AND created_at BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n )\n )\n AND NOT EXISTS (\n SELECT 1\n FROM tracks\n WHERE\n tracks.activity_id = activities.id\n AND tracks.type IN ('audio', 'video')\n )\nORDER BY actual_end_time DESC;\n\nSELECT DISTINCT\n a.*\nFROM activities a\nINNER JOIN tracks t ON a.id = t.activity_id\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams team ON u.team_id = team.id\nWHERE\n a.crm_configuration_id = 202\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n# and a.user_id = 14637\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND t.type IN ('audio', 'video')\n AND (\n (a.actual_start_time BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59')\n OR\n (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n )\n )\n AND (\n a.is_private = 0\n OR (\n a.is_private = 1\n AND a.user_id = 14637\n )\n )\n\nORDER BY a.actual_end_time DESC\n;\n\nSELECT DISTINCT a.*\nFROM activities a\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams t ON u.team_id = t.id\n# INNER JOIN tracks tr ON a.id = tr.activity_id\n# INNER JOIN groups g ON u.group_id = g.id\nWHERE 1=1\n AND t.id = 267\n# AND t.uuid = uuid_to_bin('aed4927b-f1ea-499e-94c3-83762fd233e8')\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND tr.type NOT IN ('audio', 'video')\n AND (\n a.is_private = 0\n OR a.user_id = 14637\n )\n AND (\n (a.actual_start_time BETWEEN '2025-03-19 00:00:00' AND '2025-03-21 23:59:59')\n OR (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-19 00:00:00' AND '2025-03-21 23:59:59'\n )\n )\n# and NOT EXISTS (\n# SELECT 1\n# FROM tracks t\n# WHERE t.activity_id = a.id\n# AND t.type IN ('audio', 'video')\n# )\n\nORDER BY a.actual_end_time DESC;\n\nSELECT * FROM tracks WHERE activity_id = 26485995;\n\nselect a.is_private, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\nwhere a.crm_configuration_id = 202\n# and a.is_internal = 0\nand (a.actual_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type IN (\"softphone\",\"softphone-inbound\",\"conference\",\"sms-inbound\")\nand a.status IN ('completed', 'failed')\n# and a.external_id is not null\norder by a.actual_end_time desc;\n\nselect * from activities a where a.crm_configuration_id = 202\nand a.actual_start_time between '2025-03-20 00:00:00' and '2025-03-21 00:00:00'\n# AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n\nselect g.name, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\ninner join groups g on g.id = u.group_id\nwhere a.crm_configuration_id = 202\nand a.is_internal = 0\nand (a.scheduled_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type = 'conference'\nand a.status != 'completed'\nand a.external_id is not null\norder by a.scheduled_start_time desc;\n\nSELECT * FROM teams WHERE name LIKE '%Tourlane%';\nSELECT * FROM crm_fields WHERE crm_configuration_id = 209 and object_type = 'opportunity';\nSELECT * FROM crm_field_data WHERE crm_field_id = 98809;\n\nselect * from users where status = 1 AND timezone = 'MDT';\n\nselect * from opportunities where id = 3769814;\nselect * from deal_risks where opportunity_id = 3769814;\n\nselect cp.* from crm_profiles cp\njoin users u on cp.user_id = u.id\njoin crm_configurations crm on cp.crm_configuration_id = crm.id\nwhere crm.provider = 'hubspot' AND u.status = 1 AND log_notes != 'none';\n\nselect * from crm_fields where id = 154575;\n\nselect * from team_features where feature = 'SUPPORTS_SYNC_MISSING_CALL_DISPOSITIONS';\nSELECT * FROM teams WHERE id = 176; # crm 148\nselect * from activities where crm_configuration_id = 148 and provider = 'hubspot' order by id desc;\n\nselect * from activity_providers where provider = 'amazon-connect';\n\nselect * from crm_fields cf\njoin crm_configurations crm on crm.id = cf.crm_configuration_id\nwhere crm.provider = 'hubspot' and cf.object_type IN ('account', 'contact');\n\n# *********************************************************************************************\nSELECT * FROM users WHERE id IN (15415, 15418);\nSELECT * FROM groups WHERE id IN (1805,1806);\nSELECT * FROM playbooks WHERE id = 1860;\nSELECT * FROM playbook_categories WHERE id = 38634;\nSELECT * FROM crm_fields WHERE id = 189962;\n\nSELECT * FROM teams WHERE name = 'Pulsar Group'; # 472, 380, 15138 raza.gilani@vuelio.com\n\nSELECT * FROM crm_profiles WHERE user_id = 15415;\nSELECT * FROM social_accounts WHERE sociable_id = 15415 and provider = 'salesforce';\n\nselect * from sidekick_settings where team_id = 472;\n\nSELECT * FROM activities WHERE uuid_to_bin('452c58c7-b87c-4fdd-953e-d7af185e9588') = uuid; # 28617536, user: 15418\nSELECT * FROM activities WHERE uuid_to_bin('399114ee-d3a8-458c-bff5-5f654658db0a') = uuid; # 28344407, user: 15415\nSELECT * FROM activities WHERE uuid_to_bin('f0aa567f-0ab1-4bbb-96aa-37dcf184676b') = uuid; # 28580288, user: 15415\nSELECT * FROM activities WHERE uuid_to_bin('50c086b1-2770-4bca-b5ae-6bac22ec426b') = uuid; # 28566069, user: 15415\n\n# *********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%TeamTailor%'; # 109, 218, 13969, salesforce-integrations@teamtailor.com\nselect * from crm_configurations where id = 218;\nSELECT * FROM activities WHERE uuid_to_bin('e39b5857-7fdb-4f5a-951a-8d3ca69bb1b0') = uuid; # 28338765\nSELECT * FROM users WHERE id IN (13232, 13230);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\n\n0057R00000EPL5HQAX Inez Ekblad\n\n1091cb81-5ea1-4951-a0ed-f00b568f0140 Triman Kaur\n\nSELECT * FROM crm_profiles WHERE user_id IN (13232, 13230);\n\n############################################################################################\nSELECT * FROM activities WHERE uuid_to_bin('675eeaeb-5681-42db-90bc-54c07a604408') = uuid; # 28655939 00UVg00000FLvnSMAT\nSELECT * FROM crm_field_data WHERE activity_id = 28655939;\nSELECT * FROM crm_fields WHERE id IN (94491,94493,94498);\nSELECT * FROM users WHERE id = 13658;\nSELECT * FROM teams WHERE id = 109;\nSELECT * FROM crm_configurations WHERE id = 218;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Strengthscope%'; # 481, 390, 15420, katy.holden@strengthscope.comk\nSELECT * FROM stages WHERE crm_configuration_id = 390;\nselect * from business_processes where team_id = 481 and crm_configuration_id = 390;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 481\nand sa.provider = 'salesforce';\n\n\nSELECT * FROM users WHERE id = 15780; # team 462\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 462\nand sa.provider = 'hubspot';\n\n\nselect * from teams where id = 495;\nSELECT * FROM users WHERE id = 15794;\nselect * from social_accounts where sociable_id = 15794;\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Flight%'; # 427, 333, 13752\nSELECT * FROM accounts WHERE team_id = 427 and crm_provider_id = '668731000183444517';\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Group GTI%'; # 495, 407, 15794\nSELECT * FROM activities WHERE crm_configuration_id = 407\nand status = 'completed' and type = 'conference'\norder by id desc;\n\nselect ru.*, pr.*, p.* from users u join role_user ru on ru.user_id = u.id\njoin permission_role pr on pr.role_id = ru.role_id\n join permissions p on p.id = pr.permission_id\nwhere team_id = 495 and p.name IN ('dial');\n\nselect * from permission_role;\n\nselect * from activities where crm_configuration_id = 407 and status = 'completed' order by id desc;\nSELECT * FROM activities WHERE id = 29512773;\nSELECT * FROM activities WHERE id IN (29042721,28991325,29002874);\n\nSELECT al.* from activity_summary_logs al join activities a on a.id = al.activity_id\nwhere a.crm_configuration_id = 407\n# and a.id IN (29042721,28991325,29002874);\n\nSELECT * FROM users WHERE id = 15794;\nSELECT * FROM users WHERE team_id = 495;\nSELECT * FROM social_accounts WHERE sociable_id = 15794;\nSELECT * FROM opportunities WHERE team_id = 495 and name like '%OC:%';\nSELECT * FROM contacts WHERE team_id = 495;\nSELECT * FROM leads WHERE team_id = 495;\nSELECT * FROM accounts WHERE team_id = 495;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 407;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 407;\nSELECT * FROM crm_configurations WHERE id = 407;\nSELECT * FROM opportunities WHERE team_id = 495 and close_date BETWEEN '2025-06-01' AND '2025-07-01'\nand user_id IS NOT NULL and is_closed = 1 and is_won = 1;\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Hamilton Court FX LLP%'; # 249, 187, 10103\nSELECT * FROM activities WHERE uuid_to_bin('4659c2bb-9a49-484e-9327-a3d66f1e028c') = uuid; # 28951064\nSELECT * FROM crm_fields WHERE crm_configuration_id = 187 and object_type IN ('tasks', 'event');\n\n# *********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Checkstep%'; # 325, 256, 11753\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 325\nand sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('7be372e2-1916-4d79-a2f3-ca3db1346db3') = uuid; # 28611085\nSELECT * FROM activities WHERE uuid_to_bin('980f0336-840b-4185-a5a9-30cf8b0749a8') = uuid; # 28719733\nSELECT * FROM activity_summary_logs where activity_id = 28719733;\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 356, 9444\nSELECT * FROM activity_summary_logs where sent_at BETWEEN '2025-06-09 11:38:00' AND '2025-06-09 11:40:00';\nSELECT * FROM leads WHERE crm_configuration_id = 356 and crm_provider_id = '230045001502770504'; # 823630\nselect * from activities where crm_configuration_id = 356 and lead_id = 841732;\n\nSELECT * from activity_summary_logs al join activities a on a.id = al.activity_id\nwhere a.crm_configuration_id = 356;\n\nselect * from activities where crm_configuration_id = 356\nand actual_end_time between '2025-06-09 11:00:00' and '2025-06-09 12:00:00'\norder by id desc;\n\nselect * from accounts where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\nselect * from leads where crm_configuration_id = 356 and crm_provider_id = '230045001514275654' order by id desc;\nselect * from contacts where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\nselect * from opportunities where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\n\nselect * from team_features where team_id = 260;\nselect * from features where id IN (1,2,4,6,18,19,20,9,10,3,23,24,25,26,27);\n\nSELECT * FROM activities WHERE uuid_to_bin('7be372e2-1916-4d79-a2f3-ca3db1346db3') = uuid;\n\nselect * from crm_fields;\nselect * from crm_layout_entities;\n\nSELECT * FROM teams WHERE name LIKE '%Optable%';\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Teamtailor%'; # 109, 218, 13969\nSELECT * FROM crm_configurations WHERE id = 218;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('675eeaeb-5681-42db-90bc-54c07a604408') = uuid; # 28655939\nSELECT * FROM crm_field_data WHERE activity_id = 28655939;\nSELECT * FROM crm_fields WHERE id in (94491,94493,94498);\n\nselect * from teams where crm_id IS NULL;\n\nSELECT * FROM activities WHERE uuid_to_bin('71aa8a0c-9652-4ff6-bee7-d98ae60abef6') = uuid;\n\n# *************************************************************************************************\nselect * from team_domains where team_id = 399;\nSELECT * FROM teams WHERE name LIKE '%Rydoo%'; # 399, 318, 13207\n\nselect * from calendar_events where id = 5163781;\nSELECT * FROM activities WHERE uuid_to_bin('be2cbc52-7fda-46a0-9ae0-25d9553eafc0') = uuid; # 29443896\nSELECT * FROM participants WHERE activity_id = 29443896;\nselect * from contacts where crm_configuration_id = 318 and email = 'marianne.westeng@strawberry.no';\nselect * from leads where crm_configuration_id = 318 and email = 'marianne.westeng@strawberry.no';\n\nselect * from activities where user_id = 14937 order by created_at ;\n\nselect * from users where id = 14937;\n\nselect * from contacts where crm_configuration_id = 318 and email LIKE '%@strawberry.se';\nselect * from opportunities where crm_configuration_id = 318 and crm_provider_id = '006Sf00000D1WOAIA3';\n\nselect * from activities a join participants p on a.id = p.activity_id\nwhere crm_configuration_id = 318 and a.updated_at > '2025-06-23T08:18:43Z';\n\n# *************************************************************************************************\nSELECT * FROM opportunities WHERE team_id = 379 and crm_provider_id = '39334518886';\nSELECT * FROM opportunities WHERE team_id = 379 order by id desc;\nSELECT * FROM teams WHERE id = 379;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 379 and sociable_id = 13852\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations WHERE id = 307;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 307;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1027;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 307\n and id IN (144750,144855,145158,155227);\n\nSELECT * FROM activities;\n\n\nselect * from activities\nwhere created_at > '2025-07-01 00:00:00'\n# and created_at < '2025-08-01 00:00:00'\nand type not in ('email-outbound', 'email-inbound')\nand account_id is null\nand contact_id is null\nand lead_id is null\nand opportunity_id is not null\n;\nSELECT * FROM activities WHERE id IN (25344155, 25344296, 25501909, 28692187);\nSELECT * FROM crm_configurations WHERE id in (335,301,200);\n\nselect * from crm_fields where crm_configuration_id = 230 and crm_provider_id = 'Age2__c';\n\nSELECT * FROM teams WHERE name LIKE '%Resights%';\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\n\nselect * from crm_configurations where provider = 'bullhorn'; # 344\nselect * from teams where id IN (442);\n\nselect * from activities\nwhere crm_configuration_id = 177\nand provider = 'amazon-connect'\n order by id desc;\n# and source <> 'gong';\n\nselect * from activity_providers where provider = 'amazon-connect';\n\nSELECT * FROM activities WHERE uuid_to_bin('cec1993b-a7e5-4164-b74d-d680ea51d2f2') = uuid;\n\n\nselect * from crm_configurations where store_transcript = 1;\nSELECT * FROM teams WHERE id IN (80);\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Sedna%'; # 277, 213, 12594\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 277\nand sa.provider = 'salesforce';\n\nselect * from activities where crm_configuration_id = 213 and account_id = 2511502;\n\nselect * from crm_configurations where id = 213;\n\nSELECT * FROM activities WHERE uuid_to_bin('35aa790a-8569-4544-8268-66f9a4a26804') = uuid; # 33981604\nSELECT * FROM participants WHERE activity_id = 33981604;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 337 and object_type = 'task';\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 431\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('b5476c7d-19a8-491b-869d-676ea1e857b6') = uuid; # 33997223\nselect * from activity_summary_logs where activity_id = 33997223;\nselect * from activity_notes where activity_id = 33997223;\n\n# ***********************************\nSELECT * FROM teams WHERE name LIKE '%Abode%';\n\n\nselect * from features;\nselect * from teams t\nwhere t.status = 'active'\nand id NOT IN (select team_id from team_features where feature_id = 9)\n;\n\n\nselect * from playbook_layouts where playbook_id = 1725;\nSELECT * FROM activities WHERE uuid_to_bin('65cc283c-4849-49e6-927f-4c281c8fea19') = uuid; # 34297473\nselect * from teams where id = 318;\nselect * from crm_configurations where team_id = 318;\nselect * from playbooks where team_id = 318;\nSELECT * FROM crm_layouts where crm_configuration_id = 381;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1259;\nSELECT * FROM crm_fields WHERE id IN (192938,192936,192939);\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1266;\nSELECT * FROM crm_fields WHERE id IN (192980,192991,192997,192998,193064,193067);\n\nSELECT * FROM activities WHERE uuid_to_bin('a902289b-285c-48eb-9cc2-6ad6c5d938f5') = uuid; # 34297533\n\n\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 927;\nSELECT * FROM crm_fields WHERE id IN (131668,131669,131670,131671,131676,131797);\n\nSELECT * FROM teams WHERE name LIKE '%Peripass%'; # 351, 281, 12124\nselect * from crm_layouts where crm_configuration_id = 281;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 927;\nselect * from crm_fields where crm_configuration_id = 281 and id in (131668,131669,131670,131671,131676,131797);\nselect * from opportunities where crm_configuration_id = 281;\n\nSELECT * FROM activities WHERE id IN (34211315, 34130075);\nSELECT * FROM crm_field_data WHERE object_id IN (34211315, 34130075);\n\nselect cf.crm_configuration_id, cle.crm_layout_id, cle.id, cf.id from crm_field_data cfd\njoin crm_layout_entities cle on cle.id = cfd.crm_layout_entity_id\njoin crm_fields cf on cle.crm_field_id = cf.id\nwhere cf.deleted_at IS NOT NULL\nGROUP BY cle.id, cf.id;\n\nselect * from crm_layouts where id IN (355);\nselect u.email, t.crm_id, t.* from teams t\njoin users u on u.id = t.owner_id\nwhere crm_id IN (97);\n\nSELECT * FROM crm_fields WHERE id = 96492;\n\nselect * from permissions;\nselect * from permission_role where permission_id = 247;\nselect * from roles;\n\nselect * from migrations;\n# *****************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('291e3c21-11cc-4728-aee7-6e4bedf86d72') = uuid; # 34262174\nSELECT * FROM crm_configurations WHERE id = 301;\nSELECT * FROM teams WHERE id = 343;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nselect * from participants where activity_id = 34262174;\n\nselect * from contacts where crm_configuration_id = 301 and id = 6976326;\nselect * from accounts where crm_configuration_id = 301 and id IN (4647626, 4815829); # 30761335403\n\nselect * from activity_summary_logs where activity_id = 34262174;\n\nselect * from users where status = 1 AND timezone = 'EST';\n\n# ****************************************************************************\nSELECT * FROM users WHERE id = 13869;\nSELECT * FROM crm_configurations WHERE id = 320;\nSELECT * FROM teams WHERE id = 401;\n\nSELECT * FROM activities WHERE uuid_to_bin('2228c16f-10be-48d5-90d4-67385219dc01') = uuid; # 29670601\n\nSELECT * FROM accounts WHERE id = 7761483;\nSELECT * FROM opportunities WHERE id = 6051814;\n\nSELECT * FROM teams WHERE name LIKE '%Seedlegals%';\n\n;select * from opportunities where updated_at > '2025-10-11' AND crm_provider_id = '34713761166';\n\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 177;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 577;\nSELECT * FROM crm_fields WHERE id IN (68458,68459,68480,68497,68524,68530,68554,68618,68662,68781,68810,68898,68981,69049,97467);\n\nSELECT t.id, crm.id, t.name, crm.sync_objects, crm.provider, crm.last_synced_at FROM crm_configurations crm join teams t on t.crm_id = crm.id\nwhere t.status = 'active' AND crm.provider = 'hubspot' AND crm.last_synced_at < '2025-10-22 00:00:00';\n\nSELECT * FROM activities WHERE uuid_to_bin('fa09449f-cba9-496a-b8f3-865cd3c72351') = uuid;\nSELECT * FROM crm_configurations where id = 184;\nSELECT * FROM teams WHERE id = 246;\nSELECT * FROM social_accounts WHERE sociable_id = 9259 and provider = 'hubspot';\n\nSELECT * FROM users WHERE email LIKE '%rhian.old@bud.co.uk%'; # 17700\nSELECT * FROM teams WHERE id = 551;\n\nSELECT * FROM crm_configurations WHERE id = 471;\nSELECT * FROM activities WHERE crm_configuration_id = 471 and crm_provider_id IS NOT NULL;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 471;\nSELECT * FROM crm_fields WHERE id = 307260;\nSELECT * FROM crm_field_values WHERE crm_field_id = 307260;\n\nselect * from crm_layouts where crm_configuration_id = 471;\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1547;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1548;\n\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 = 551 and sa.provider = 'hubspot';\n\nSELECT * FROM teams WHERE name LIKE '%$PCS%';\n\n# ********************************************************************************************************\nselect * from crm_configurations crm\njoin teams t on t.crm_id = crm.id\nwhere t.status = 'active'\nand crm.provider = 'hubspot';\n\n# $slug = 'HUBSPOT_WEBHOOK_SYNC';\n# $team = Jiminny\\Models\\Team::find(2);\n# $feature = Feature::query()->where('slug', $slug)->first();\n# TeamFeature::query()->create(['feature_id' => $feature->getId(),'team_id' => $team->getId()]);\n\n# hubspot_webhook_metrics\n\nselect * from crm_configurations where id = 331; # 416\nSELECT * FROM teams WHERE id = 416;\nSELECT * FROM opportunities WHERE team_id = 190;\n\nSELECT * FROM teams WHERE name LIKE '%Lead Forensics%';\nSELECT sa.id,\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 = 190 and sa.provider = 'hubspot';\n\n\n\nSELECT * FROM teams WHERE name LIKE '%Rapaport%'; # 431, 337\nSELECT * FROM teams where id = 431;\nSELECT * FROM crm_configurations where team_id = 431;\nSELECT * FROM activity_providers where team_id = 431;\nSELECT * FROM activities where crm_configuration_id = 337 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\nSELECT sa.id,\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 = 431 and sa.provider = 'salesforce';\n\nSELECT * FROM teams WHERE name LIKE '%BiP%'; # 401, 320\nSELECT * FROM teams where id = 401;\nSELECT * FROM crm_configurations where team_id = 401;\nSELECT * FROM activity_providers where team_id = 401;\nSELECT * FROM activities where crm_configuration_id = 320 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\nSELECT sa.id,\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 = 401 and sa.provider = 'salesforce';\n\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 307; # 379 - Story Terrace Inc , portalId: 3921157\nSELECT * FROM contacts WHERE team_id = 379 and updated_at > '2026-01-31 11:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 379 and updated_at > '2026-02-01 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 379 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\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 = 379 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 485; # 563 - LATUS Group (ad94d501-5d09-44fd-878f-ca3a9f8865c3) , portalId: 3904501\nSELECT * FROM opportunities WHERE team_id = 563 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 563 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 338; # 432 - Formalize , portalId: 9214205\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 = 432 and sa.provider = 'hubspot';\nSELECT * FROM opportunities WHERE team_id = 432 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 432 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 436; # 519 - Moxso , portalId: 25531989\nSELECT * FROM opportunities WHERE team_id = 519 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 519 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 96; # 119 - Nourish Care , portalId: 26617984\nSELECT * FROM opportunities WHERE team_id = 119 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 119 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 331; # 416 - The National College , portalId: 7213852\nSELECT * FROM opportunities WHERE team_id = 416 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 416 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 308; # 380 - Foodles , portalId: 7723616\nSELECT * FROM opportunities WHERE team_id = 380 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 380 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 379; # 471 - imat-uve , portalId: 9177354\nSELECT * FROM opportunities WHERE team_id = 471 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 471 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 465; # 545 - Spotler , portalId: 144759271\nSELECT * FROM opportunities WHERE team_id = 545 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 545 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 455; # 537 - indevis , portalId: 25666868\nSELECT * FROM opportunities WHERE team_id = 537 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 537 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 200; # 265 - Jobadder , portalId: 6426676\nSELECT * FROM opportunities WHERE team_id = 265 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 265 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 335; # 429 - Eletive , portalId: 6110563\nSELECT * FROM opportunities WHERE team_id = 429 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 429 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 363; # 456 - Global Group , portalId: 8901981\nSELECT * FROM opportunities WHERE team_id = 456 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 456 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 297; # 369 - Unbiased , portalId: 9229005\nSELECT * FROM opportunities WHERE team_id = 369 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 369 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 353; # 449 - Fuuse , portalId: 25781745\nSELECT * FROM opportunities WHERE team_id = 449 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 449 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 487; # 566 - Nimbus , portalId: 39982590\nSELECT * FROM opportunities WHERE team_id = 566 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 566 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 487;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1630;\nselect * from crm_fields where crm_configuration_id = 487 and\n(uuid_to_bin('4c6b2971-64d4-45b8-b377-427be758b5a5') = uuid or uuid_to_bin('59e368d8-65a0-4b77-b611-db37c99fbe68') = uuid);\nSELECT * FROM crm_field_values WHERE crm_field_id = 375177;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 420; # 506 - voiio , portalId: 145629154\nSELECT * FROM opportunities WHERE team_id = 506 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 506 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 479; # 558 - Momice , portalId: 535962\nSELECT * FROM opportunities WHERE team_id = 558 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 558 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 59; # 80 - Storyclash GmbH , portalId: 4268479\nSELECT * FROM opportunities WHERE team_id = 80 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 80 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 175; # 203 - Team iAM , portalId: 5534732\nSELECT * FROM opportunities WHERE team_id = 203 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 203 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 368; # 460 - OneTouch Health , portalId: 5534732183355\nSELECT * FROM opportunities WHERE team_id = 460 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 460 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\n\n\nselect * from users where id = 29643;\nSELECT * FROM crm_field_values WHERE crm_field_id = 375177;\n# ********************************************************************\nSELECT * FROM teams WHERE name LIKE '%Buynomics%'; # 462, 482, 14910\nSELECT * FROM activities WHERE crm_configuration_id = 482\nand type NOT IN ('email-inbound', 'email-outbound')\n# and description like '%The call focused on understanding Welch%'\norder by id desc;\n\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 = 462 and sa.provider = 'salesforce';\n\nselect * from contacts where crm_configuration_id = 482 and name = 'Cyndall Hill'; # 15504749\nselect * from contacts where id = 10891096; # 482\nSELECT * FROM activities WHERE crm_configuration_id = 482\nand type NOT IN ('email-inbound', 'email-outbound')\nand contact_id = 15504749\norder by id desc;\n\nselect * from activities where id = 36793003; # 96cc7bc1-8622-4d27-92f4-baf664fc1a56, 00UOf00000PDdOXMA1\nselect * from transcription where id = 7646782;\nselect * from ai_prompts where transcription_id = 7646782;\n\n# ********************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('7a8471a3-847e-4822-802b-ddf426bbc252') = uuid; # 37370018\nSELECT * FROM activity_summary_logs WHERE activity_id = 37370018;\nSELECT * FROM teams WHERE id = 555;\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 = 555 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('7c17b8aa-09df-4f85-a0f7-51f47afd712d') = uuid; # 37395250\nSELECT * FROM activities WHERE uuid_to_bin('14d60388-260d-494b-aa0d-63fdb1c78026') = uuid; # 37395250\n\nSELECT a.* FROM activities a JOIN crm_configurations c on c.id = a.crm_configuration_id\nwhere a.type IN ('softphone', 'softphone-outbound') and c.provider = 'hubspot'\nand a.provider NOT IN ('hubspot')\n# and a.provider IN ('salesloft')\n# and c.id NOT IN (70)\n# and a.duration > 30\n# and actual_start_time > '2026-02-05 00:00:00'\norder by a.id desc;\n\nSELECT * FROM activities WHERE id = 37549787;\nSELECT * FROM crm_profiles WHERE user_id = 17613;\n\nSELECT * FROM crm_configurations WHERE id = 70;\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 = 93 and sa.provider = 'hubspot';\n\nSELECT asf.activity_search_id, asf.id, asf.value\nFROM activity_search_filters asf\nWHERE asf.filter = 'group_id'\nAND asf.value IN (\n SELECT CONCAT(\n HEX(SUBSTR(uuid, 5, 4)), '-',\n HEX(SUBSTR(uuid, 3, 2)), '-',\n HEX(SUBSTR(uuid, 1, 2)), '-',\n HEX(SUBSTR(uuid, 9, 2)), '-',\n HEX(SUBSTR(uuid, 11))\n )\n FROM groups\n WHERE deleted_at IS NOT NULL\n);\n\nSELECT * FROM crm_configurations WHERE id = 373; # KPSBremen.de 465 # - no social account\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 = 465 and sa.provider = 'hubspot';\n\nselect * from crm_configurations where id = 494;\n\nSELECT * FROM teams WHERE name LIKE '%splose%'; # 572, 495, 18708\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 = 572 and sa.provider = 'pipedrive';\n\nselect * from opportunities where team_id = 572\n# and name like '%Onebright%'\n# and is_closed = 1 and is_won = 0\n order by id desc;\n\n\nselect * from users where deleted_at is null and status = 2;\n\nselect * from contacts where id = 17900517;\nselect * from accounts where id = 10109838;\nselect * from opportunities where id = 6955880;\n\nselect * from opportunity_contacts where opportunity_id = 6955880;\nselect * from opportunity_contacts where contact_id = 17900517;\n\nselect * from contact_roles cr join crm_configurations crm on cr.crm_configuration_id = crm.id\nwhere crm.provider != 'salesforce';\n\nSELECT * FROM activities WHERE uuid_to_bin('adcb8331-5988-4353-834e-383a355abba2') = uuid; # 38056424, crm 104659682404\nselect * from teams where id = 456;\nSELECT * FROM crm_configurations WHERE id = 363;\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 = 456 and sa.provider = 'hubspot';\n\nselect * from crm_layouts where crm_configuration_id = 363;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id IN (1203, 1204, 1635);\nSELECT * FROM crm_fields WHERE id IN (181536, 181538, 213455);\n\nSELECT * FROM teams WHERE name LIKE '%Electric%'; # 342, 272, 12767\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 = 342 and sa.provider = 'pipedrive';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 and name like 'NORTHUMBRIA POL%'; # and updated_at > '2025-07-01 00:00:00';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 order by remotely_created_at asc; # and updated_at > '2025-07-01 00:00:00';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 and updated_at > '2026-01-01 00:00:00';\nSELECT * FROM crm_fields WHERE crm_configuration_id = 272 and object_type = 'opportunity';\nSELECT * FROM crm_field_values WHERE crm_field_id = 127164;\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 = 342 and sa.provider = 'pipedrive';\n\nSELECT * FROM teams WHERE id = 472;\nSELECT * FROM crm_configurations WHERE id = 380;\nselect * from activities where id = 38285673; # 38285673\nSELECT * FROM users WHERE id = 16942;\nSELECT * FROM groups WHERE id = 1964;\nSELECT * FROM playbooks WHERE id = 2033;\n\nselect * from teams where created_at > '2026-03-09';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 499; # 1065\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1678;\n\nSELECT * FROM teams WHERE id = 575;\nselect * from opportunities where team_id = 575;\n\nSELECT * FROM activities WHERE uuid_to_bin('96b1261f-2357-49f9-ab38-23ce12008ea0') = uuid;\n\nselect * from contacts c\nwhere c.crm_configuration_id = 370 order by c.updated_at desc;\n\nSELECT * FROM participants where activity_id = 38833541;\nSELECT * FROM participants where activity_id = 39216301;\nSELECT * FROM activity_summary_logs where activity_id = 39216301;\nSELECT * FROM activities WHERE uuid_to_bin('c7d99fbe-1fb1-41f2-8f4d-52e2bf70e1e9') = uuid; # 38833541, crm 478116564181\nSELECT * FROM activities WHERE uuid_to_bin('2e6ff4d3-9faa-447a-a8c1-9acde4d885ae') = uuid; # 39216301, crm 480171536586\nselect * from crm_profiles where crm_configuration_id = 319 and crm_provider_id = 525785080;\nselect * from opportunities where crm_configuration_id = 319 and crm_provider_id = 410150124747;\nselect * from accounts where crm_configuration_id = 319 and crm_provider_id = 47150650569;\nselect * from contacts where crm_configuration_id = 319 and crm_provider_id IN ('665587441856', '742723347700');\n# owner 13236 525785080\n# contact 1 16779180 665587441856 - activity - Alex Howes alex@supportroom.com created 2026-01-26\n# contact 2 19247563 742723347700 - ash@supportroom.com 2026-03-24\n# company 4176133 47150650569\n# deal 7100953 410150124747\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 = 400 and sa.provider = 'hubspot';\n\nselect * from features;\nselect * from team_features where feature_id = 40;\n\nselect * from teams where id = 556; # owner: 18101, crm: 477\nselect * from crm_configurations where id = 477;\nSELECT * FROM users WHERE id = 18101;\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 = 556 and sa.provider = 'integration-app';\n\nselect * from opportunities where id = 7594349;\nselect * from opportunity_stages where opportunity_id = 7594349 order by created_at desc;\nselect * from business_processes where id = 6024;\nselect * from business_process_stages where stage_id = 16352;\nselect * from business_process_stages where business_process_id = 6024;\nselect * from stages where team_id = 459;\nselect * from teams where id = 459;\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 = 459 and sa.provider = 'hubspot';\n\nSELECT os.stage_id, s.crm_provider_id, s.name, COUNT(*) as cnt\nFROM opportunity_stages os\nJOIN stages s ON s.id = os.stage_id\nWHERE os.opportunity_id = 7594349\nGROUP BY os.stage_id, s.crm_provider_id, s.name\nORDER BY cnt DESC;\n\nSELECT s.id, s.crm_provider_id, s.name, s.team_id, s.crm_configuration_id\nFROM stages s\nJOIN business_process_stages bps ON bps.stage_id = s.id\nWHERE bps.business_process_id = 6024\nAND s.crm_provider_id = 'contractsent';\n\nselect * from stages where id IN (16352,20612,18281,7344,16378,16309,5036,15223,14535,6293,12098,11607)\n\nSELECT * FROM teams WHERE name LIKE '%Pulsar Group%'; # 472, 380, 15138, raza.gilani@vuelio.com\nselect * from playbooks where team_id = 472; # event 226147\nSELECT * FROM playbook_categories WHERE playbook_id = 2288;\nSELECT * FROM crm_fields WHERE id = 226147;\nSELECT * FROM crm_field_values WHERE crm_field_id = 226147;\n\nSELECT * FROM crm_configurations WHERE id = 380;\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 = 472 and sa.provider = 'salesforce';\n\nselect * from activities where id = 58081273;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2;\n\nSELECT * FROM users WHERE name LIKE '%Neil Hoyle%'; # 17651\nSELECT * FROM social_accounts WHERE sociable_id = 17651;\n\nSELECT * FROM activities WHERE uuid_to_bin('975c6830-7d49-4c1e-b2e9-ac80c10a738a') = uuid;\nSELECT * FROM opportunities WHERE id IN (7842553, 6211727);\nSELECT * FROM contacts WHERE id IN (10202724, 6211727);\nSELECT * FROM opportunity_stages WHERE opportunity_id = 7842553;\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 = 519 and sa.provider = 'hubspot';\n\nselect * from crm_configurations where id = 436;\nselect * from crm_profiles where crm_configuration_id = 436; # 76091797 -> 16612\n\nselect * from contact_roles where contact_id = 10202724;\n\nselect * from stages where team_id = 519; # 18778\n18775\n\nSELECT\n id,\n crm_provider_id,\n stage_id,\n is_closed,\n is_won,\n stage_updated_at,\n updated_at\nFROM opportunities\nWHERE id IN (6211727, 7842553);\n\nSELECT * FROM opportunity_contacts\nWHERE opportunity_id = 6211727 AND contact_id = 10202724;\n\nSELECT id, name, stage_id, is_closed, is_won, updated_at, remotely_created_at\nFROM opportunities\nWHERE account_id = 8179134\nORDER BY updated_at DESC;\n\n\nselect * from text_relays where created_at > '2026-01-01';\nAND id IN (691, 692);\n\nselect * from teams;\n\n# ***************\nSELECT DISTINCT u.id, u.email, u.name, u.softphone_number, COUNT(a.id) as sms_count\nFROM users u\nINNER JOIN activities a ON u.id = a.user_id\nWHERE a.type LIKE 'sms%'\nAND a.created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)\nGROUP BY u.id, u.email, u.name, u.softphone_number\nORDER BY sms_count DESC;\n\nSELECT DISTINCT u.id, u.email, u.name, u.team_id, t.name as team_name,\n t.twilio_sms_sid, t.twilio_messaging_sid\nFROM users u\nINNER JOIN teams t ON u.team_id = t.id\nWHERE (t.twilio_sms_sid IS NOT NULL OR t.twilio_messaging_sid IS NOT NULL)\nAND u.status = 1\nORDER BY t.name, u.email;\n\nSELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, salesforce-admin@tourlane.com\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 = 187 and sa.provider = 'salesforce';\n\nselect * from activities where id = 31264367;\nselect * from contacts where id = 6331639;\nselect * from accounts where id = 4156632;\nselect * from opportunities where id = 4843610;\n# update `activities` set `account_id` = 4156632, `contact_id` = 6331639, `opportunity_id` = 4843610,\n# `stage_id` = 13273, `activities`.`updated_at` = 2026-05-22 07:16:17 where `id` = 31264367)\"\n\nselect * from text_relays where created_at > '2026-05-01';\n\nselect * from activities order by id desc;\n\nselect * from users where name like '%Subra%';\n\nSELECT * FROM opportunities WHERE uuid_to_bin('04a9cfad-2c87-4453-9e72-20aeb78ccf8d') = uuid;\nselect * from teams where id = 555;\nselect * from stages where team_id = 555;\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 = 100 and sa.provider = 'hubspot';","depth":4,"on_screen":true,"value":"SELECT * FROM team_features where team_id = 1;\n\nSELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922\nSELECT * FROM users WHERE team_id = 340; # 12015\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 340\nand sa.provider = 'salesforce';\n# and sa.provider = 'salesloft';\n\nselect * from crm_fields where crm_configuration_id = 270 and object_type = 'event';\n# 125558 - Event Type - Event_Type__c\n# 125552 - Event Status - Event_Status__c\n\nSELECT * FROM sidekick_settings WHERE team_id = 340;\n\nSELECT * FROM crm_field_values WHERE crm_field_id in (125552);\n\nselect * from activities where crm_configuration_id = 270\nand type = 'conference' and crm_provider_id IS NOT NULL\nand actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;\n\nSELECT * FROM activities WHERE id = 20871677;\nSELECT * FROM crm_field_data WHERE activity_id = 20871677;\n\nselect * from crm_layouts where crm_configuration_id = 270;\nselect * from crm_layout_entities where crm_layout_id in (886,887);\n\nSELECT * FROM crm_configurations WHERE id = 270;\n\nselect * from playbooks where team_id = 340; # 1514\nselect * from groups where team_id = 340;\nSELECT * FROM crm_fields WHERE id IN (125393, 125401);\n\nselect g.name as 'team name', p.name as 'playbook name', f.label as 'activity type field' from groups g\njoin playbooks p on g.playbook_id = p.id\njoin crm_fields f on p.activity_field_id = f.id\nwhere g.team_id = 340;\n\nSELECT * FROM activities WHERE uuid_to_bin('0c180357-67d2-419e-a8c3-b832a3490770') = uuid; # 20448716\nselect * from crm_field_data where object_id = 20448716;\n\nselect * from activities where crm_configuration_id = 270 and provider = 'salesloft' order by id desc;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%CybSafe%'; # 343,273,12008\nselect * from opportunities where team_id = 343;\nselect * from opportunities where team_id = 343 and crm_provider_id = '18099102526';\nselect * from opportunities where team_id = 343 and account_id = 945217482;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nselect * from accounts where team_id = 343 order by name asc;\n\nselect * from stages where crm_configuration_id = 273 and type = 'opportunity';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Voyado%'; # 353,283,12143\nSELECT * FROM activities WHERE crm_configuration_id = 283 and account_id = 3777844 order by id desc;\nSELECT * FROM accounts WHERE team_id = 353 AND name LIKE '%Salesloft%';\nSELECT * FROM activities WHERE id = 20717903;\n\nselect * from participants where activity_id IN (20929172,20928605,20928468,20926272,20926271,20926270,20926269,20916499,20916454,20916436,20916435,20900015,20900014,20900013,20897312,20897243,20897241,20897237,20897232,20897229,20893648,20893231,20893230,20893229,20893228,20889784,20885039,20885038,20885037,20885036,20885035,20882728,20882708,20882703,20882702,20869828,20869811,20869806,20869801,20869799,20869798,20869796,20869795,20869794,20869761,20869760,20869759,20868688,20868687,20850340,20847195,20841710,20833967,20827021,20825307,20825305,20825297,20824615,20824400,20823927,20821760,20795588,20794233,20794057,20793710,20785811,20781789,20781394,20781307,20762651,20758453,20758282,20757323,20756643,20756636,20756629,20756627,20756606,20756605,20756604,20756603,20756602,20756600,20756599,20756598,20756595,20756594,20756589,20756587,20756577,20756573,20748918,20748386,20748385,20748384,20748383,20748382,20748381,20748380,20748379,20748377,20748375,20748373,20743301,20717905,20717904,20717903,20717901,20717899);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 353\nand sa.provider = 'salesforce';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%modern world business solutions%'; # 345,275,12016, l.atkinson@mwbsolutions.co.uk\nSELECT * FROM activities WHERE uuid_to_bin('3921d399-3fef-4609-a291-b0097a166d43') = uuid;\n# id: 20940638, user: 12022, contact: 5305871\nSELECT * FROM activity_summary_logs WHERE activity_id = 20940638;\nselect * from contacts where team_id = 345 and crm_provider_id = '30891432415' order by name asc; # 5305871\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 345\nand sa.provider = 'hubspot';\n\nselect * from users where team_id = 345 and id = 12022;\nSELECT * FROM crm_profiles WHERE user_id = 12022;\nSELECT * FROM participants WHERE activity_id = 20940638;\nSELECT * FROM users u\nJOIN crm_profiles cp ON u.id = cp.user_id\nWHERE u.team_id = 345;\n\nselect * from contacts where team_id = 345 and crm_provider_id = '30880813535' order by name desc; # 5305871\n\nselect * from team_features where team_id = 345;\nSELECT * FROM activities WHERE uuid_to_bin('11701e2d-2f82-4dab-a616-1db4fad238df') = uuid; # 21115197\nSELECT * FROM participants WHERE activity_id = 20897406;\n\n\n\nSELECT * FROM activities WHERE uuid_to_bin('63ba55cd-1abc-447d-83da-0137000005b7') = uuid; # 20953912\nSELECT * FROM activities WHERE crm_configuration_id = 275 and provider = 'ringcentral' and title like '%1252629100%';\n\n\nSELECT * FROM activities WHERE id = 20946641;\nSELECT * FROM crm_profiles WHERE user_id = 10211;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120,97,10984, triger@lunio.ai\nSELECT * FROM opportunities WHERE crm_configuration_id = 97 and crm_provider_id = '006N1000006c5PpIAI';\nselect * from stages where crm_configuration_id = 97 and type = 'opportunity';\nselect * from opportunities where team_id = 120;\n\n\nselect * from crm_configurations crm join teams t on crm.id = t.crm_id\nwhere 1=1\nAND t.current_billing_plan IS NOT NULL\nAND crm.auto_sync_activity = 0\nand crm.provider = 'hubspot';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Exclaimer%'; # 270,205,10053,james.lewendon@exclaimer.com\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 270\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('b54df794-2a9a-4957-8d80-09a600ead5f8') = uuid; # 21637956\nSELECT * FROM crm_profiles WHERE user_id = 11446;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Cygnetise%'; # 372,300,12554, alex.chikly@cygnetise.com\nselect * from playbooks where team_id = 372;\nselect * from crm_fields where crm_configuration_id = 300 and object_type = 'event'; # 141340\nSELECT * FROM crm_field_values WHERE crm_field_id = 141340;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 372\nand sa.provider = 'salesforce';\n\nselect * from crm_profiles where crm_configuration_id = 300;\nSELECT * FROM crm_configurations WHERE team_id = 372;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Planday%'; # 291,242,11501,mfa@planday.com\nSELECT * FROM opportunities WHERE team_id = 291 and crm_provider_id = '006bG000005DO86QAG'; # 3207756\nselect * from crm_field_data where object_id = 3207756;\nSELECT * FROM crm_fields WHERE id = 111834;\n\nselect f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value\nFROM crm_fields f\nJOIN crm_field_data fd ON f.id = fd.crm_field_id\nWHERE f.crm_configuration_id = 242\nAND f.object_type = 'opportunity'\nAND fd.object_id IN (3207756)\nORDER BY fd.object_id, fd.updated_at;\n\nSELECT * FROM crm_configurations WHERE auto_connect = 1;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150,salesforce-admin@tourlane.com\nselect * from group_deal_risk_types drgt join groups g on drgt.group_id = g.id\nwhere g.team_id = 187;\n\nselect * from `groups` where team_id = 187;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 187\nand sa.provider = 'salesforce';\n\n# Destination - 98870 - Destination__c\n# Stage - 79014 - StageName\n# Land Arrangement - 98856 - Land_Arrangement__c\n# Flight - 98848 - Flight__c\n# Last activity date - 98812 - LastActivityDate\n# Last modified date - 98809 - LastModifiedDate\n# Last inbound mail timestamp - 99151 - Last_Inbound_Mail_Timestamp__c\n# next call - 98864 - Next_Call__c\n\nselect * from crm_fields where crm_configuration_id = 209 and object_type = 'opportunity';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 209;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;\n\nselect * from opportunities where team_id = 187 and name LIKE'%Muriel Sal%';\nselect * from opportunities where team_id = 187 and user_id = 9951 and is_closed = 0;\nselect * from activities where opportunity_id = 3538248;\n\nSELECT * FROM crm_profiles WHERE user_id = 8150;\n\nselect * from deal_risks where opportunity_id = 3538248;\n\nselect * from teams where crm_id IS NULL;\n\nSELECT opp.id AS opportunity_id,\n u.group_id AS group_id,\n MAX(\n CASE\n WHEN a.type IN (\"sms-inbound\", \"sms-outbound\") THEN a.created_at\n ELSE a.actual_end_time\n END) as last_date\nFROM opportunities opp\nleft join activities a on a.opportunity_id = opp.id\ninner join users u on opp.user_id = u.id\nwhere opp.user_id IN (9951)\n\nAND opp.is_closed = 0\nand a.status IN ('completed', 'received', 'delivered') OR a.status IS NULL\ngroup by opp.id;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Cybsafe%'; # 343,301,12008,polly.morphew@cybsafe.com\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 301;\nSELECT * FROM contacts WHERE id = 6612363;\nSELECT * FROM accounts WHERE id = 4235676;\nSELECT * FROM opportunities WHERE crm_configuration_id = 301 and crm_provider_id = 32983784868;\nselect * from opportunity_stages where opportunity_id = 4503759;\n# SELECT * FROM opportunities WHERE id = 4569937;\n\nselect * from activities where crm_configuration_id = 301;\nSELECT * FROM activities WHERE uuid_to_bin('d3b2b28b-c3d0-4c2d-8ed0-eef42855278a') = uuid; # 26330370\nSELECT * FROM participants WHERE activity_id = 26330370;\n\nSELECT * FROM teams WHERE id = 375;\nselect * from playbooks where team_id = 375;\n\nselect * from stages where crm_configuration_id = 301 and type = 'opportunity';\n\nselect * from teams;\nselect * from contact_roles;\n\nSELECT * FROM opportunities WHERE team_id = 343 and user_id = 12871 and close_date >= '2024-11-01';\n\nselect * from users u join crm_profiles cp on cp.user_id = u.id where u.team_id = 343;\n\nSELECT * FROM crm_field_data WHERE object_id = 3771706;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_fields WHERE crm_configuration_id = 301 and object_type = 'opportunity'\nand crm_provider_id LIKE \"%traffic_light%\";\nSELECT * FROM crm_field_values WHERE crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531);\n\nSELECT fd.* FROM opportunities o\nJOIN crm_field_data fd ON o.id = fd.object_id\nWHERE o.team_id = 343\n# and o.user_id IS NOT NULL\nand fd.crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531)\nand fd.value != ''\norder by value desc\n# group by o.id\n;\n\nSELECT * FROM opportunities WHERE id = 3769843;\n\nSELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150, salesforce-admin@tourlane.com\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 209;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Funding Circle%'; # 220,177,8603,aswini.mishra@fundingcircle.com\nSELECT * FROM activities WHERE uuid_to_bin('7a40e99b-3b37-4bb1-b983-325b81801c01') = uuid; # 23139839\n\n\nSELECT * FROM opportunities WHERE id = 3855992;\n\nSELECT * FROM users WHERE name LIKE '%Angus Pollard%'; # 8988\n\nSELECT * FROM teams WHERE name LIKE '%Story Terrace%'; # 379, 307, 12894\nSELECT * FROM crm_fields WHERE crm_configuration_id = 307 and object_type != 'opportunity';\n\nselect * from contacts where team_id = 379 and name like '%bebro%'; # 5874411, crm: 77229348507\nSELECT * FROM crm_field_data WHERE object_id = 5874411;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 379\nand sa.provider = 'hubspot';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%mentio%'; # 117, 94, 6371, nikhil.kumar@mention-me.com\nSELECT * FROM activities WHERE uuid_to_bin('82939311-1af0-4506-8546-21e8d1fdf2c1') = uuid;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, salesforce-admin@tourlane.com\nSELECT * FROM opportunities WHERE team_id = 187 and crm_provider_id = '006Se000008xfvNIAQ'; # 3537793\nselect * from generic_ai_prompts where subject_id = 3537793;\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120, 97, 10984, triger@lunio.ai\nSELECT * FROM crm_configurations WHERE id = 97;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 97;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 355;\nSELECT * FROM crm_fields WHERE id = 32682;\n\nselect cfd.value, o.* from opportunities o\njoin crm_field_data cfd on o.id = cfd.object_id and cfd.crm_field_id = 32682\nwhere team_id = 120\nand cfd.value != ''\n;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 120\nand sa.provider = 'salesforce';\n\nselect * from opportunities where team_id = 120 and crm_provider_id = '006N1000007X8MAIA0';\nSELECT * FROM crm_field_data WHERE object_id = 2313439;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE id = 410;\nSELECT * FROM teams WHERE name LIKE '%Local Business Oxford%';\nselect * from scorecards where team_id = 410;\nselect * from scorecard_rules;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Funding%'; # 220, 177, 8603, aswini.mishra@fundingcircle.com\nselect * from activities a\njoin opportunities o on a.opportunity_id = o.id\njoin users u on o.user_id = u.id\nwhere a.crm_configuration_id = 177 and a.type LIKE '%email-out%'\n# and a.actual_end_time > '2024-12-16 00:00:00'\n# and o.remotely_created_at > '2024-12-01 00:00:00'\n# and u.group_id = 1014\nand u.id = 9021\norder by a.id desc;\nSELECT * FROM opportunities WHERE id in (3981384,4017346);\nSELECT * FROM users WHERE team_id = 220 and id IN (8775, 11435);\n\nselect * from users where id = 9021;\nselect * from inboxes where user_id = 9021;\n\nselect * from inbox_emails where inbox_id = 1349 and email_date > '2024-12-18 00:00:00';\n\nselect * from email_messages where team_id = 220\nand orig_date > '2024-12-16 00:00:00' and orig_date < '2024-12-19 00:00:00'\nand subject LIKE '%Personal%'\n# and 'from' = 'credit@fundingcircle.com'\n;\n\nselect * from activities a\njoin opportunities o on a.opportunity_id = o.id\nwhere a.user_id = 9021 and a.type LIKE '%email-out%'\nand a.actual_end_time > '2024-12-18 00:00:00'\nand o.user_id IS NOT NULL\nand o.remotely_created_at > '2024-12-01 00:00:00'\norder by a.id desc;\n\nSELECT * FROM opportunities WHERE team_id = 220 and name LIKE '%Right Car move Limited%' and id = 3966852;\nselect * from activities where crm_configuration_id = 177 and type LIKE '%email%' and opportunity_id = 3966852 order by id desc;\n\nselect * from team_settings where name IN ('useCloseDate');\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Hurree%'; # 104, 81, 6175, jfarrell@hurree.co\nSELECT * FROM opportunities WHERE team_id = 104 and name = 'PropOp';\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 104\nand sa.provider = 'hubspot';\n\nselect * from crm_configurations where last_synced_at > '2025-01-19 01:00:00'\nselect * from teams where crm_id IS NULL;\n\nselect t.name as 'team', u.name as 'owner', u.email, u.phone\nfrom teams t\njoin activity_providers ap on t.id = ap.team_id\njoin users u on t.owner_id = u.id\nwhere 1=1\n and t.status = 'active'\n and ap.is_enabled = 1\n# and u.status = 1\n and ap.provider = 'ms-teams';\n\nselect * from crm_configurations where provider = 'bullhorn'; # 344\nSELECT * FROM teams WHERE id = 442; # 14293\nselect * from users where team_id = 442;\nselect * from social_accounts sa where sa.sociable_id = 14293;\nselect * from invitations where team_id = 442;\n\n# ********************************************************************************************************\nSELECT * FROM users WHERE email LIKE '%nea.liikamaa@eletive.com%'; # 14022\nSELECT * FROM teams WHERE id = 429;\nselect * from opportunities where team_id = 429 and crm_provider_id IN (16157415775, 22246219645);\nselect * from activities where opportunity_id in (4340436,4353519);\n\nselect * from transcription where activity_id IN (25630961,25381771);\nselect * from generic_ai_prompts where subject_id IN (4353519);\n\nSELECT\n a.id as activity_id,\n a.opportunity_id,\n a.type as activity_type,\n a.language,\n CONCAT(a.title, a.description) AS mail_content,\n e.from AS mail_from,\n e.to AS mail_to,\n e.subject AS mail_subject,\n e.body AS mail_body,\n p.type as prompt_type,\n p.status as prompt_status,\n p.content AS prompt_content,\n a.actual_start_time as created_at\nFROM activities a\n LEFT JOIN ai_prompts p ON a.transcription_id = p.transcription_id AND p.deleted_at IS NULL\n LEFT JOIN email_messages e ON a.id = e.activity_id\nWHERE a.actual_start_time > '2024-01-01 00:00:00'\n AND a.opportunity_id IN (4353519)\n AND a.status IN ('completed', 'received', 'delivered')\n AND a.deleted_at IS NULL\n AND a.type NOT IN ('sms-inbound', 'sms-outbound')\nORDER BY a.opportunity_id ASC, a.id ASC;\n\nSELECT * FROM users WHERE name LIKE '%George Fierstone%'; # 14293\nSELECT * FROM teams WHERE id = 442;\nSELECT * FROM crm_configurations WHERE id = 344;\nselect * from team_features where team_id = 442;\nselect * from groups where team_id = 442;\nselect * from playbooks where team_id = 442;\nselect * from playbook_categories where playbook_id = 1729;\nselect * from crm_fields where crm_configuration_id = 344 and id = 172024;\nSELECT * FROM crm_field_values WHERE crm_field_id = 172024;\nselect * from crm_layouts where crm_configuration_id = 344;\nselect * from playbook_layouts where playbook_id = 1729;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 221, 9444\n\nselect s.*\n# , s.sent_at, u.name, a.*\nfrom activity_summary_logs s\ninner join activities a on a.id = s.activity_id\ninner join users u on u.id = a.user_id\nwhere a.crm_configuration_id = 356\nand s.sent_at > date_sub(now(), interval 60 day)\norder by a.actual_end_time desc;\n\nselect * from activities a\n# inner join activity_summary_logs s on s.activity_id = a.id\nwhere a.crm_configuration_id = 356 and a.actual_end_time > date_sub(now(), interval 60 day)\n# and a.crm_provider_id is not null\n# and provider <> 'ringcentral'\nand status = 'completed'\norder by a.actual_end_time desc;\n\nselect * from teams order by id desc; # 17328, 32, 17830, integration-account@jiminny.com\nSELECT * FROM users;\nSELECT * FROM users where team_id = 260 and status = 1; # 201 - 150 active\nSELECT * FROM teams WHERE id = 260;\nselect * from team_settings where team_id = 260;\nselect * from crm_configurations where team_id = 260;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 356;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1184;\n\nselect * from accounts where crm_configuration_id = 221 order by id desc; # 7000\nselect * from leads where crm_configuration_id = 221 order by id desc; # 0\nselect * from contacts where crm_configuration_id = 221 order by id desc; # 200 000\nselect * from opportunities where crm_configuration_id = 221 order by id desc; # 0\nselect * from crm_profiles where crm_configuration_id = 221 order by id desc; # 23\nselect * from crm_fields where crm_configuration_id = 221;\nselect * from crm_field_values where crm_field_id = 5302 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 221 order by id desc;\nselect * from stages where crm_configuration_id = 221 order by id desc;\n\nselect * from accounts where crm_configuration_id = 356 order by id desc; # 7000\nselect * from leads where crm_configuration_id = 356 order by id desc; # 0\nselect * from contacts where crm_configuration_id = 356 order by id desc; # 200 000\nselect * from opportunities where crm_configuration_id = 356 order by id desc; # 0\nselect * from crm_profiles where crm_configuration_id = 356 order by id desc; # 23\nselect * from crm_fields where crm_configuration_id = 356;\nselect * from crm_field_values where crm_field_id = 5302 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 356 order by id desc;\nselect * from stages where crm_configuration_id = 356 order by id desc;\n\nselect * from playbooks where team_id = 260 order by id desc; # 4 (2 deleted)\nselect * from groups where team_id = 260 order by id desc; # 27 groups, (2 deleted)\nselect * from playbook_layouts where playbook_id IN (1410,1409,1276,1254); # 4\nselect ce.* from calendars c\njoin users u on c.user_id = u.id\njoin calendar_events ce on c.id = ce.calendar_id\nwhere u.team_id = 260\nand (ce.start_time > '2025-02-21 00:00:00')\n;\n# calendar events 1207\n#\n\nselect * from opportunities where team_id = 260;\nSELECT * FROM crm_field_data WHERE object_id = 4696496;\n\nselect * from activities where crm_configuration_id = 356 and crm_provider_id IS NOT NULL;\nselect * from activities where crm_configuration_id IN (221) and provider NOT IN ('ms-teams', 'uploader', 'zoom-bot')\n# and type = 'conference' and status = 'scheduled' and activities.is_internal = 0\nand created_at > '2024-03-01 00:00:00'\norder by id desc; # 880 000, ringcentral, avaya\nSELECT * FROM participants WHERE activity_id = 26371744;\n\n# all activities 942 000 +\n# conference 7385 - scheduled 984 - external 343\n\nselect * from activities where id = 26321812;\nselect * from participants where activity_id = 26321812;\nselect * from participants where activity_id in (26414510,26414514,26414516,26414604,26414653,26414655);\nselect * from leads where id in (720428,689175,731546,645866,621037);\n\nselect * from users where id = 13841;\nselect * from opportunities where user_id = 9541;\nselect * from stages where id = 15900;\n\nselect * from accounts where\n# id IN (4160055,5053725,4965303,4896434)\nid in (4584518,3249934,3218025,3891133,3399450,4172999,4485161,3101785,4587203,3070816,2870343,2870341,3563940,4550846,3424464,3249963,2870342)\n;\n\nselect * from activities where id = 26654935;\nSELECT * FROM opportunities WHERE id = 4803458;\n\nSELECT * FROM opportunities where team_id = 260 and user_id = 13841 AND stage_id = 15900;\nSELECT id, uuid, provider, type, lead_id, account_id, contact_id, opportunity_id, stage_id, status, recording_state, title, actual_start_time, actual_end_time\nFROM activities WHERE user_id = 13841 AND opportunity_id IN (4729783, 4731717, 4731726, 4732064, 4732849, 4803458, 4813213);\n\nSELECT DISTINCT\n o.id, o.stage_id, s.name, a.title,\n a.*\nFROM activities a\n# INNER JOIN tracks t ON a.id = t.activity_id\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams team ON u.team_id = team.id\nINNER JOIN groups g ON u.group_id = g.id\nINNER JOIN opportunities o ON a.opportunity_id = o.id\nINNER JOIN stages s ON o.stage_id = s.id\nWHERE\n a.crm_configuration_id = 356\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n# and a.user_id = 13841\n AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')\n AND team.uuid = uuid_to_bin('a607fba7-452e-4683-b2af-00d6cb52c93c')\n AND g.uuid = uuid_to_bin('b5d69e40-24a0-4c16-810b-5fa462299f94')\n\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND t.type IN ('audio', 'video')\n AND (\n (a.actual_start_time BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59')\n OR\n (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59'\n )\n )\n AND (\n a.is_private = 0\n OR (\n a.is_private = 1\n AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')\n )\n )\n AND (\n# s.id = 15900\n s.uuid = uuid_to_bin('04ca1c26-c666-4268-a129-419c0acffd73')\n OR s.uuid IS NULL -- Include records without opportunity stage\n )\n\nORDER BY a.actual_end_time DESC;\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lead Forensics%'; # 190, 162, 8474, willsc@leadforensics.com\nSELECT * FROM users WHERE team_id = 190;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 190\nand sa.provider = 'hubspot';\n\nselect * from role_user where user_id = 8474;\n\nselect * from crm_configurations where provider = 'bullhorn';\n\nSELECT * FROM opportunities WHERE uuid_to_bin('94578249-65ec-4205-90f2-7d1a7d5ab64a') = uuid;\nSELECT * FROM users WHERE uuid_to_bin('26dbadeb-926f-4150-b11b-771b9d4c2f9a') = uuid;\n\nSELECT * FROM opportunities WHERE id = 4732493;\nselect * from activities where opportunity_id = 4732493;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE id = 443; # 358, 14315, andrea.romano@correrenaturale.com\nSELECT * FROM opportunities WHERE team_id = 443;\n\nSELECT a.id, a.type, a.user_id, a.status, a.deleted_at, u.name, u.email, u.team_id as activity_team_id, u.status, u.deleted_at, t.name, t.status, s.team_id as stage_team_id\nFROM activities AS a\nJOIN stages AS s ON a.stage_id = s.id\nJOIN users AS u ON u.id = a.user_id\nJOIN teams AS t ON t.id = s.team_id\nWHERE u.team_id <> s.team_id and t.id > 135;\n\n\nSELECT\n crm_configuration_id,\n crm_provider_id,\n COUNT(*) as duplicate_count,\n GROUP_CONCAT(id) as stage_ids,\n GROUP_CONCAT(name) as stage_names\nFROM stages\nGROUP BY crm_configuration_id, crm_provider_id\nHAVING COUNT(*) > 1\nORDER BY duplicate_count DESC;\n\nselect * from stages where id IN (14898,14907);\n\nselect * from business_processes;\n\nSELECT *\nFROM crm_configurations\nWHERE team_id IN (\n SELECT team_id\n FROM crm_configurations\n GROUP BY team_id\n HAVING COUNT(*) > 1\n)\nORDER BY team_id;\n\nSELECT *\nFROM teams\nWHERE crm_id IN (\n SELECT crm_id\n FROM teams\n GROUP BY crm_id\n HAVING COUNT(*) > 1\n)\nORDER BY crm_id;\n\n# ***************************************************************************\nselect * from crm_configurations where provider = 'integration-app';\nSELECT * FROM teams WHERE id = 443; # Correre Naturale 358 14315 andrea.romano@correrenaturale.com\nselect * from activities where crm_configuration_id = 358 order by actual_end_time desc;\nselect id, uuid, actual_end_time, crm_provider_id, is_internal, playbook_category_id, type, user_id, lead_id, contact_id, account_id, opportunity_id, status, title from activities where crm_configuration_id = 358 order by actual_end_time desc;\nselect * from team_features where team_id = 358;\nselect * from activity_summary_logs;\n\nselect * from teams where id = 406;\n\n# ************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Sportfive%'; # 267, 202, 14637, srv.salesforce@sportfive.com\nselect * from activities where crm_configuration_id = 202 order by actual_end_time desc;\n\nSELECT * FROM users where id = 14637;\nSELECT * FROM teams where id = 267;\nSELECT * FROM groups where id = 1118;\n\nselect g.name, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\ninner join groups g on g.id = u.group_id\nwhere a.crm_configuration_id = 202\nand a.is_internal = 0\nand (a.scheduled_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type = 'conference'\nand a.status != 'completed'\nand a.external_id is not null\norder by a.scheduled_start_time desc;\n\nSELECT * FROM activities\nWHERE crm_configuration_id = 202\n AND status IN ('completed', 'failed')\n AND recording_state != 'stopped'\n AND type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n AND (is_private = 0 OR user_id = 14637)\n AND (\n (\n actual_start_time BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n ) OR (\n actual_start_time IS NULL\n AND type IN ('sms-outbound', 'sms-inbound')\n AND created_at BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n )\n )\n AND NOT EXISTS (\n SELECT 1\n FROM tracks\n WHERE\n tracks.activity_id = activities.id\n AND tracks.type IN ('audio', 'video')\n )\nORDER BY actual_end_time DESC;\n\nSELECT DISTINCT\n a.*\nFROM activities a\nINNER JOIN tracks t ON a.id = t.activity_id\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams team ON u.team_id = team.id\nWHERE\n a.crm_configuration_id = 202\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n# and a.user_id = 14637\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND t.type IN ('audio', 'video')\n AND (\n (a.actual_start_time BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59')\n OR\n (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n )\n )\n AND (\n a.is_private = 0\n OR (\n a.is_private = 1\n AND a.user_id = 14637\n )\n )\n\nORDER BY a.actual_end_time DESC\n;\n\nSELECT DISTINCT a.*\nFROM activities a\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams t ON u.team_id = t.id\n# INNER JOIN tracks tr ON a.id = tr.activity_id\n# INNER JOIN groups g ON u.group_id = g.id\nWHERE 1=1\n AND t.id = 267\n# AND t.uuid = uuid_to_bin('aed4927b-f1ea-499e-94c3-83762fd233e8')\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND tr.type NOT IN ('audio', 'video')\n AND (\n a.is_private = 0\n OR a.user_id = 14637\n )\n AND (\n (a.actual_start_time BETWEEN '2025-03-19 00:00:00' AND '2025-03-21 23:59:59')\n OR (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-19 00:00:00' AND '2025-03-21 23:59:59'\n )\n )\n# and NOT EXISTS (\n# SELECT 1\n# FROM tracks t\n# WHERE t.activity_id = a.id\n# AND t.type IN ('audio', 'video')\n# )\n\nORDER BY a.actual_end_time DESC;\n\nSELECT * FROM tracks WHERE activity_id = 26485995;\n\nselect a.is_private, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\nwhere a.crm_configuration_id = 202\n# and a.is_internal = 0\nand (a.actual_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type IN (\"softphone\",\"softphone-inbound\",\"conference\",\"sms-inbound\")\nand a.status IN ('completed', 'failed')\n# and a.external_id is not null\norder by a.actual_end_time desc;\n\nselect * from activities a where a.crm_configuration_id = 202\nand a.actual_start_time between '2025-03-20 00:00:00' and '2025-03-21 00:00:00'\n# AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n\nselect g.name, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\ninner join groups g on g.id = u.group_id\nwhere a.crm_configuration_id = 202\nand a.is_internal = 0\nand (a.scheduled_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type = 'conference'\nand a.status != 'completed'\nand a.external_id is not null\norder by a.scheduled_start_time desc;\n\nSELECT * FROM teams WHERE name LIKE '%Tourlane%';\nSELECT * FROM crm_fields WHERE crm_configuration_id = 209 and object_type = 'opportunity';\nSELECT * FROM crm_field_data WHERE crm_field_id = 98809;\n\nselect * from users where status = 1 AND timezone = 'MDT';\n\nselect * from opportunities where id = 3769814;\nselect * from deal_risks where opportunity_id = 3769814;\n\nselect cp.* from crm_profiles cp\njoin users u on cp.user_id = u.id\njoin crm_configurations crm on cp.crm_configuration_id = crm.id\nwhere crm.provider = 'hubspot' AND u.status = 1 AND log_notes != 'none';\n\nselect * from crm_fields where id = 154575;\n\nselect * from team_features where feature = 'SUPPORTS_SYNC_MISSING_CALL_DISPOSITIONS';\nSELECT * FROM teams WHERE id = 176; # crm 148\nselect * from activities where crm_configuration_id = 148 and provider = 'hubspot' order by id desc;\n\nselect * from activity_providers where provider = 'amazon-connect';\n\nselect * from crm_fields cf\njoin crm_configurations crm on crm.id = cf.crm_configuration_id\nwhere crm.provider = 'hubspot' and cf.object_type IN ('account', 'contact');\n\n# *********************************************************************************************\nSELECT * FROM users WHERE id IN (15415, 15418);\nSELECT * FROM groups WHERE id IN (1805,1806);\nSELECT * FROM playbooks WHERE id = 1860;\nSELECT * FROM playbook_categories WHERE id = 38634;\nSELECT * FROM crm_fields WHERE id = 189962;\n\nSELECT * FROM teams WHERE name = 'Pulsar Group'; # 472, 380, 15138 raza.gilani@vuelio.com\n\nSELECT * FROM crm_profiles WHERE user_id = 15415;\nSELECT * FROM social_accounts WHERE sociable_id = 15415 and provider = 'salesforce';\n\nselect * from sidekick_settings where team_id = 472;\n\nSELECT * FROM activities WHERE uuid_to_bin('452c58c7-b87c-4fdd-953e-d7af185e9588') = uuid; # 28617536, user: 15418\nSELECT * FROM activities WHERE uuid_to_bin('399114ee-d3a8-458c-bff5-5f654658db0a') = uuid; # 28344407, user: 15415\nSELECT * FROM activities WHERE uuid_to_bin('f0aa567f-0ab1-4bbb-96aa-37dcf184676b') = uuid; # 28580288, user: 15415\nSELECT * FROM activities WHERE uuid_to_bin('50c086b1-2770-4bca-b5ae-6bac22ec426b') = uuid; # 28566069, user: 15415\n\n# *********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%TeamTailor%'; # 109, 218, 13969, salesforce-integrations@teamtailor.com\nselect * from crm_configurations where id = 218;\nSELECT * FROM activities WHERE uuid_to_bin('e39b5857-7fdb-4f5a-951a-8d3ca69bb1b0') = uuid; # 28338765\nSELECT * FROM users WHERE id IN (13232, 13230);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\n\n0057R00000EPL5HQAX Inez Ekblad\n\n1091cb81-5ea1-4951-a0ed-f00b568f0140 Triman Kaur\n\nSELECT * FROM crm_profiles WHERE user_id IN (13232, 13230);\n\n############################################################################################\nSELECT * FROM activities WHERE uuid_to_bin('675eeaeb-5681-42db-90bc-54c07a604408') = uuid; # 28655939 00UVg00000FLvnSMAT\nSELECT * FROM crm_field_data WHERE activity_id = 28655939;\nSELECT * FROM crm_fields WHERE id IN (94491,94493,94498);\nSELECT * FROM users WHERE id = 13658;\nSELECT * FROM teams WHERE id = 109;\nSELECT * FROM crm_configurations WHERE id = 218;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Strengthscope%'; # 481, 390, 15420, katy.holden@strengthscope.comk\nSELECT * FROM stages WHERE crm_configuration_id = 390;\nselect * from business_processes where team_id = 481 and crm_configuration_id = 390;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 481\nand sa.provider = 'salesforce';\n\n\nSELECT * FROM users WHERE id = 15780; # team 462\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 462\nand sa.provider = 'hubspot';\n\n\nselect * from teams where id = 495;\nSELECT * FROM users WHERE id = 15794;\nselect * from social_accounts where sociable_id = 15794;\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Flight%'; # 427, 333, 13752\nSELECT * FROM accounts WHERE team_id = 427 and crm_provider_id = '668731000183444517';\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Group GTI%'; # 495, 407, 15794\nSELECT * FROM activities WHERE crm_configuration_id = 407\nand status = 'completed' and type = 'conference'\norder by id desc;\n\nselect ru.*, pr.*, p.* from users u join role_user ru on ru.user_id = u.id\njoin permission_role pr on pr.role_id = ru.role_id\n join permissions p on p.id = pr.permission_id\nwhere team_id = 495 and p.name IN ('dial');\n\nselect * from permission_role;\n\nselect * from activities where crm_configuration_id = 407 and status = 'completed' order by id desc;\nSELECT * FROM activities WHERE id = 29512773;\nSELECT * FROM activities WHERE id IN (29042721,28991325,29002874);\n\nSELECT al.* from activity_summary_logs al join activities a on a.id = al.activity_id\nwhere a.crm_configuration_id = 407\n# and a.id IN (29042721,28991325,29002874);\n\nSELECT * FROM users WHERE id = 15794;\nSELECT * FROM users WHERE team_id = 495;\nSELECT * FROM social_accounts WHERE sociable_id = 15794;\nSELECT * FROM opportunities WHERE team_id = 495 and name like '%OC:%';\nSELECT * FROM contacts WHERE team_id = 495;\nSELECT * FROM leads WHERE team_id = 495;\nSELECT * FROM accounts WHERE team_id = 495;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 407;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 407;\nSELECT * FROM crm_configurations WHERE id = 407;\nSELECT * FROM opportunities WHERE team_id = 495 and close_date BETWEEN '2025-06-01' AND '2025-07-01'\nand user_id IS NOT NULL and is_closed = 1 and is_won = 1;\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Hamilton Court FX LLP%'; # 249, 187, 10103\nSELECT * FROM activities WHERE uuid_to_bin('4659c2bb-9a49-484e-9327-a3d66f1e028c') = uuid; # 28951064\nSELECT * FROM crm_fields WHERE crm_configuration_id = 187 and object_type IN ('tasks', 'event');\n\n# *********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Checkstep%'; # 325, 256, 11753\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 325\nand sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('7be372e2-1916-4d79-a2f3-ca3db1346db3') = uuid; # 28611085\nSELECT * FROM activities WHERE uuid_to_bin('980f0336-840b-4185-a5a9-30cf8b0749a8') = uuid; # 28719733\nSELECT * FROM activity_summary_logs where activity_id = 28719733;\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 356, 9444\nSELECT * FROM activity_summary_logs where sent_at BETWEEN '2025-06-09 11:38:00' AND '2025-06-09 11:40:00';\nSELECT * FROM leads WHERE crm_configuration_id = 356 and crm_provider_id = '230045001502770504'; # 823630\nselect * from activities where crm_configuration_id = 356 and lead_id = 841732;\n\nSELECT * from activity_summary_logs al join activities a on a.id = al.activity_id\nwhere a.crm_configuration_id = 356;\n\nselect * from activities where crm_configuration_id = 356\nand actual_end_time between '2025-06-09 11:00:00' and '2025-06-09 12:00:00'\norder by id desc;\n\nselect * from accounts where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\nselect * from leads where crm_configuration_id = 356 and crm_provider_id = '230045001514275654' order by id desc;\nselect * from contacts where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\nselect * from opportunities where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\n\nselect * from team_features where team_id = 260;\nselect * from features where id IN (1,2,4,6,18,19,20,9,10,3,23,24,25,26,27);\n\nSELECT * FROM activities WHERE uuid_to_bin('7be372e2-1916-4d79-a2f3-ca3db1346db3') = uuid;\n\nselect * from crm_fields;\nselect * from crm_layout_entities;\n\nSELECT * FROM teams WHERE name LIKE '%Optable%';\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Teamtailor%'; # 109, 218, 13969\nSELECT * FROM crm_configurations WHERE id = 218;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('675eeaeb-5681-42db-90bc-54c07a604408') = uuid; # 28655939\nSELECT * FROM crm_field_data WHERE activity_id = 28655939;\nSELECT * FROM crm_fields WHERE id in (94491,94493,94498);\n\nselect * from teams where crm_id IS NULL;\n\nSELECT * FROM activities WHERE uuid_to_bin('71aa8a0c-9652-4ff6-bee7-d98ae60abef6') = uuid;\n\n# *************************************************************************************************\nselect * from team_domains where team_id = 399;\nSELECT * FROM teams WHERE name LIKE '%Rydoo%'; # 399, 318, 13207\n\nselect * from calendar_events where id = 5163781;\nSELECT * FROM activities WHERE uuid_to_bin('be2cbc52-7fda-46a0-9ae0-25d9553eafc0') = uuid; # 29443896\nSELECT * FROM participants WHERE activity_id = 29443896;\nselect * from contacts where crm_configuration_id = 318 and email = 'marianne.westeng@strawberry.no';\nselect * from leads where crm_configuration_id = 318 and email = 'marianne.westeng@strawberry.no';\n\nselect * from activities where user_id = 14937 order by created_at ;\n\nselect * from users where id = 14937;\n\nselect * from contacts where crm_configuration_id = 318 and email LIKE '%@strawberry.se';\nselect * from opportunities where crm_configuration_id = 318 and crm_provider_id = '006Sf00000D1WOAIA3';\n\nselect * from activities a join participants p on a.id = p.activity_id\nwhere crm_configuration_id = 318 and a.updated_at > '2025-06-23T08:18:43Z';\n\n# *************************************************************************************************\nSELECT * FROM opportunities WHERE team_id = 379 and crm_provider_id = '39334518886';\nSELECT * FROM opportunities WHERE team_id = 379 order by id desc;\nSELECT * FROM teams WHERE id = 379;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 379 and sociable_id = 13852\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations WHERE id = 307;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 307;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1027;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 307\n and id IN (144750,144855,145158,155227);\n\nSELECT * FROM activities;\n\n\nselect * from activities\nwhere created_at > '2025-07-01 00:00:00'\n# and created_at < '2025-08-01 00:00:00'\nand type not in ('email-outbound', 'email-inbound')\nand account_id is null\nand contact_id is null\nand lead_id is null\nand opportunity_id is not null\n;\nSELECT * FROM activities WHERE id IN (25344155, 25344296, 25501909, 28692187);\nSELECT * FROM crm_configurations WHERE id in (335,301,200);\n\nselect * from crm_fields where crm_configuration_id = 230 and crm_provider_id = 'Age2__c';\n\nSELECT * FROM teams WHERE name LIKE '%Resights%';\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\n\nselect * from crm_configurations where provider = 'bullhorn'; # 344\nselect * from teams where id IN (442);\n\nselect * from activities\nwhere crm_configuration_id = 177\nand provider = 'amazon-connect'\n order by id desc;\n# and source <> 'gong';\n\nselect * from activity_providers where provider = 'amazon-connect';\n\nSELECT * FROM activities WHERE uuid_to_bin('cec1993b-a7e5-4164-b74d-d680ea51d2f2') = uuid;\n\n\nselect * from crm_configurations where store_transcript = 1;\nSELECT * FROM teams WHERE id IN (80);\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Sedna%'; # 277, 213, 12594\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 277\nand sa.provider = 'salesforce';\n\nselect * from activities where crm_configuration_id = 213 and account_id = 2511502;\n\nselect * from crm_configurations where id = 213;\n\nSELECT * FROM activities WHERE uuid_to_bin('35aa790a-8569-4544-8268-66f9a4a26804') = uuid; # 33981604\nSELECT * FROM participants WHERE activity_id = 33981604;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 337 and object_type = 'task';\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 431\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('b5476c7d-19a8-491b-869d-676ea1e857b6') = uuid; # 33997223\nselect * from activity_summary_logs where activity_id = 33997223;\nselect * from activity_notes where activity_id = 33997223;\n\n# ***********************************\nSELECT * FROM teams WHERE name LIKE '%Abode%';\n\n\nselect * from features;\nselect * from teams t\nwhere t.status = 'active'\nand id NOT IN (select team_id from team_features where feature_id = 9)\n;\n\n\nselect * from playbook_layouts where playbook_id = 1725;\nSELECT * FROM activities WHERE uuid_to_bin('65cc283c-4849-49e6-927f-4c281c8fea19') = uuid; # 34297473\nselect * from teams where id = 318;\nselect * from crm_configurations where team_id = 318;\nselect * from playbooks where team_id = 318;\nSELECT * FROM crm_layouts where crm_configuration_id = 381;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1259;\nSELECT * FROM crm_fields WHERE id IN (192938,192936,192939);\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1266;\nSELECT * FROM crm_fields WHERE id IN (192980,192991,192997,192998,193064,193067);\n\nSELECT * FROM activities WHERE uuid_to_bin('a902289b-285c-48eb-9cc2-6ad6c5d938f5') = uuid; # 34297533\n\n\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 927;\nSELECT * FROM crm_fields WHERE id IN (131668,131669,131670,131671,131676,131797);\n\nSELECT * FROM teams WHERE name LIKE '%Peripass%'; # 351, 281, 12124\nselect * from crm_layouts where crm_configuration_id = 281;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 927;\nselect * from crm_fields where crm_configuration_id = 281 and id in (131668,131669,131670,131671,131676,131797);\nselect * from opportunities where crm_configuration_id = 281;\n\nSELECT * FROM activities WHERE id IN (34211315, 34130075);\nSELECT * FROM crm_field_data WHERE object_id IN (34211315, 34130075);\n\nselect cf.crm_configuration_id, cle.crm_layout_id, cle.id, cf.id from crm_field_data cfd\njoin crm_layout_entities cle on cle.id = cfd.crm_layout_entity_id\njoin crm_fields cf on cle.crm_field_id = cf.id\nwhere cf.deleted_at IS NOT NULL\nGROUP BY cle.id, cf.id;\n\nselect * from crm_layouts where id IN (355);\nselect u.email, t.crm_id, t.* from teams t\njoin users u on u.id = t.owner_id\nwhere crm_id IN (97);\n\nSELECT * FROM crm_fields WHERE id = 96492;\n\nselect * from permissions;\nselect * from permission_role where permission_id = 247;\nselect * from roles;\n\nselect * from migrations;\n# *****************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('291e3c21-11cc-4728-aee7-6e4bedf86d72') = uuid; # 34262174\nSELECT * FROM crm_configurations WHERE id = 301;\nSELECT * FROM teams WHERE id = 343;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nselect * from participants where activity_id = 34262174;\n\nselect * from contacts where crm_configuration_id = 301 and id = 6976326;\nselect * from accounts where crm_configuration_id = 301 and id IN (4647626, 4815829); # 30761335403\n\nselect * from activity_summary_logs where activity_id = 34262174;\n\nselect * from users where status = 1 AND timezone = 'EST';\n\n# ****************************************************************************\nSELECT * FROM users WHERE id = 13869;\nSELECT * FROM crm_configurations WHERE id = 320;\nSELECT * FROM teams WHERE id = 401;\n\nSELECT * FROM activities WHERE uuid_to_bin('2228c16f-10be-48d5-90d4-67385219dc01') = uuid; # 29670601\n\nSELECT * FROM accounts WHERE id = 7761483;\nSELECT * FROM opportunities WHERE id = 6051814;\n\nSELECT * FROM teams WHERE name LIKE '%Seedlegals%';\n\n;select * from opportunities where updated_at > '2025-10-11' AND crm_provider_id = '34713761166';\n\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 177;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 577;\nSELECT * FROM crm_fields WHERE id IN (68458,68459,68480,68497,68524,68530,68554,68618,68662,68781,68810,68898,68981,69049,97467);\n\nSELECT t.id, crm.id, t.name, crm.sync_objects, crm.provider, crm.last_synced_at FROM crm_configurations crm join teams t on t.crm_id = crm.id\nwhere t.status = 'active' AND crm.provider = 'hubspot' AND crm.last_synced_at < '2025-10-22 00:00:00';\n\nSELECT * FROM activities WHERE uuid_to_bin('fa09449f-cba9-496a-b8f3-865cd3c72351') = uuid;\nSELECT * FROM crm_configurations where id = 184;\nSELECT * FROM teams WHERE id = 246;\nSELECT * FROM social_accounts WHERE sociable_id = 9259 and provider = 'hubspot';\n\nSELECT * FROM users WHERE email LIKE '%rhian.old@bud.co.uk%'; # 17700\nSELECT * FROM teams WHERE id = 551;\n\nSELECT * FROM crm_configurations WHERE id = 471;\nSELECT * FROM activities WHERE crm_configuration_id = 471 and crm_provider_id IS NOT NULL;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 471;\nSELECT * FROM crm_fields WHERE id = 307260;\nSELECT * FROM crm_field_values WHERE crm_field_id = 307260;\n\nselect * from crm_layouts where crm_configuration_id = 471;\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1547;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1548;\n\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 = 551 and sa.provider = 'hubspot';\n\nSELECT * FROM teams WHERE name LIKE '%$PCS%';\n\n# ********************************************************************************************************\nselect * from crm_configurations crm\njoin teams t on t.crm_id = crm.id\nwhere t.status = 'active'\nand crm.provider = 'hubspot';\n\n# $slug = 'HUBSPOT_WEBHOOK_SYNC';\n# $team = Jiminny\\Models\\Team::find(2);\n# $feature = Feature::query()->where('slug', $slug)->first();\n# TeamFeature::query()->create(['feature_id' => $feature->getId(),'team_id' => $team->getId()]);\n\n# hubspot_webhook_metrics\n\nselect * from crm_configurations where id = 331; # 416\nSELECT * FROM teams WHERE id = 416;\nSELECT * FROM opportunities WHERE team_id = 190;\n\nSELECT * FROM teams WHERE name LIKE '%Lead Forensics%';\nSELECT sa.id,\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 = 190 and sa.provider = 'hubspot';\n\n\n\nSELECT * FROM teams WHERE name LIKE '%Rapaport%'; # 431, 337\nSELECT * FROM teams where id = 431;\nSELECT * FROM crm_configurations where team_id = 431;\nSELECT * FROM activity_providers where team_id = 431;\nSELECT * FROM activities where crm_configuration_id = 337 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\nSELECT sa.id,\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 = 431 and sa.provider = 'salesforce';\n\nSELECT * FROM teams WHERE name LIKE '%BiP%'; # 401, 320\nSELECT * FROM teams where id = 401;\nSELECT * FROM crm_configurations where team_id = 401;\nSELECT * FROM activity_providers where team_id = 401;\nSELECT * FROM activities where crm_configuration_id = 320 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\nSELECT sa.id,\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 = 401 and sa.provider = 'salesforce';\n\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 307; # 379 - Story Terrace Inc , portalId: 3921157\nSELECT * FROM contacts WHERE team_id = 379 and updated_at > '2026-01-31 11:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 379 and updated_at > '2026-02-01 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 379 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\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 = 379 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 485; # 563 - LATUS Group (ad94d501-5d09-44fd-878f-ca3a9f8865c3) , portalId: 3904501\nSELECT * FROM opportunities WHERE team_id = 563 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 563 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 338; # 432 - Formalize , portalId: 9214205\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 = 432 and sa.provider = 'hubspot';\nSELECT * FROM opportunities WHERE team_id = 432 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 432 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 436; # 519 - Moxso , portalId: 25531989\nSELECT * FROM opportunities WHERE team_id = 519 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 519 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 96; # 119 - Nourish Care , portalId: 26617984\nSELECT * FROM opportunities WHERE team_id = 119 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 119 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 331; # 416 - The National College , portalId: 7213852\nSELECT * FROM opportunities WHERE team_id = 416 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 416 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 308; # 380 - Foodles , portalId: 7723616\nSELECT * FROM opportunities WHERE team_id = 380 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 380 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 379; # 471 - imat-uve , portalId: 9177354\nSELECT * FROM opportunities WHERE team_id = 471 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 471 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 465; # 545 - Spotler , portalId: 144759271\nSELECT * FROM opportunities WHERE team_id = 545 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 545 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 455; # 537 - indevis , portalId: 25666868\nSELECT * FROM opportunities WHERE team_id = 537 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 537 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 200; # 265 - Jobadder , portalId: 6426676\nSELECT * FROM opportunities WHERE team_id = 265 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 265 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 335; # 429 - Eletive , portalId: 6110563\nSELECT * FROM opportunities WHERE team_id = 429 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 429 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 363; # 456 - Global Group , portalId: 8901981\nSELECT * FROM opportunities WHERE team_id = 456 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 456 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 297; # 369 - Unbiased , portalId: 9229005\nSELECT * FROM opportunities WHERE team_id = 369 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 369 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 353; # 449 - Fuuse , portalId: 25781745\nSELECT * FROM opportunities WHERE team_id = 449 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 449 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 487; # 566 - Nimbus , portalId: 39982590\nSELECT * FROM opportunities WHERE team_id = 566 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 566 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 487;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1630;\nselect * from crm_fields where crm_configuration_id = 487 and\n(uuid_to_bin('4c6b2971-64d4-45b8-b377-427be758b5a5') = uuid or uuid_to_bin('59e368d8-65a0-4b77-b611-db37c99fbe68') = uuid);\nSELECT * FROM crm_field_values WHERE crm_field_id = 375177;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 420; # 506 - voiio , portalId: 145629154\nSELECT * FROM opportunities WHERE team_id = 506 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 506 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 479; # 558 - Momice , portalId: 535962\nSELECT * FROM opportunities WHERE team_id = 558 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 558 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 59; # 80 - Storyclash GmbH , portalId: 4268479\nSELECT * FROM opportunities WHERE team_id = 80 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 80 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 175; # 203 - Team iAM , portalId: 5534732\nSELECT * FROM opportunities WHERE team_id = 203 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 203 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 368; # 460 - OneTouch Health , portalId: 5534732183355\nSELECT * FROM opportunities WHERE team_id = 460 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 460 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\n\n\nselect * from users where id = 29643;\nSELECT * FROM crm_field_values WHERE crm_field_id = 375177;\n# ********************************************************************\nSELECT * FROM teams WHERE name LIKE '%Buynomics%'; # 462, 482, 14910\nSELECT * FROM activities WHERE crm_configuration_id = 482\nand type NOT IN ('email-inbound', 'email-outbound')\n# and description like '%The call focused on understanding Welch%'\norder by id desc;\n\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 = 462 and sa.provider = 'salesforce';\n\nselect * from contacts where crm_configuration_id = 482 and name = 'Cyndall Hill'; # 15504749\nselect * from contacts where id = 10891096; # 482\nSELECT * FROM activities WHERE crm_configuration_id = 482\nand type NOT IN ('email-inbound', 'email-outbound')\nand contact_id = 15504749\norder by id desc;\n\nselect * from activities where id = 36793003; # 96cc7bc1-8622-4d27-92f4-baf664fc1a56, 00UOf00000PDdOXMA1\nselect * from transcription where id = 7646782;\nselect * from ai_prompts where transcription_id = 7646782;\n\n# ********************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('7a8471a3-847e-4822-802b-ddf426bbc252') = uuid; # 37370018\nSELECT * FROM activity_summary_logs WHERE activity_id = 37370018;\nSELECT * FROM teams WHERE id = 555;\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 = 555 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('7c17b8aa-09df-4f85-a0f7-51f47afd712d') = uuid; # 37395250\nSELECT * FROM activities WHERE uuid_to_bin('14d60388-260d-494b-aa0d-63fdb1c78026') = uuid; # 37395250\n\nSELECT a.* FROM activities a JOIN crm_configurations c on c.id = a.crm_configuration_id\nwhere a.type IN ('softphone', 'softphone-outbound') and c.provider = 'hubspot'\nand a.provider NOT IN ('hubspot')\n# and a.provider IN ('salesloft')\n# and c.id NOT IN (70)\n# and a.duration > 30\n# and actual_start_time > '2026-02-05 00:00:00'\norder by a.id desc;\n\nSELECT * FROM activities WHERE id = 37549787;\nSELECT * FROM crm_profiles WHERE user_id = 17613;\n\nSELECT * FROM crm_configurations WHERE id = 70;\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 = 93 and sa.provider = 'hubspot';\n\nSELECT asf.activity_search_id, asf.id, asf.value\nFROM activity_search_filters asf\nWHERE asf.filter = 'group_id'\nAND asf.value IN (\n SELECT CONCAT(\n HEX(SUBSTR(uuid, 5, 4)), '-',\n HEX(SUBSTR(uuid, 3, 2)), '-',\n HEX(SUBSTR(uuid, 1, 2)), '-',\n HEX(SUBSTR(uuid, 9, 2)), '-',\n HEX(SUBSTR(uuid, 11))\n )\n FROM groups\n WHERE deleted_at IS NOT NULL\n);\n\nSELECT * FROM crm_configurations WHERE id = 373; # KPSBremen.de 465 # - no social account\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 = 465 and sa.provider = 'hubspot';\n\nselect * from crm_configurations where id = 494;\n\nSELECT * FROM teams WHERE name LIKE '%splose%'; # 572, 495, 18708\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 = 572 and sa.provider = 'pipedrive';\n\nselect * from opportunities where team_id = 572\n# and name like '%Onebright%'\n# and is_closed = 1 and is_won = 0\n order by id desc;\n\n\nselect * from users where deleted_at is null and status = 2;\n\nselect * from contacts where id = 17900517;\nselect * from accounts where id = 10109838;\nselect * from opportunities where id = 6955880;\n\nselect * from opportunity_contacts where opportunity_id = 6955880;\nselect * from opportunity_contacts where contact_id = 17900517;\n\nselect * from contact_roles cr join crm_configurations crm on cr.crm_configuration_id = crm.id\nwhere crm.provider != 'salesforce';\n\nSELECT * FROM activities WHERE uuid_to_bin('adcb8331-5988-4353-834e-383a355abba2') = uuid; # 38056424, crm 104659682404\nselect * from teams where id = 456;\nSELECT * FROM crm_configurations WHERE id = 363;\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 = 456 and sa.provider = 'hubspot';\n\nselect * from crm_layouts where crm_configuration_id = 363;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id IN (1203, 1204, 1635);\nSELECT * FROM crm_fields WHERE id IN (181536, 181538, 213455);\n\nSELECT * FROM teams WHERE name LIKE '%Electric%'; # 342, 272, 12767\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 = 342 and sa.provider = 'pipedrive';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 and name like 'NORTHUMBRIA POL%'; # and updated_at > '2025-07-01 00:00:00';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 order by remotely_created_at asc; # and updated_at > '2025-07-01 00:00:00';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 and updated_at > '2026-01-01 00:00:00';\nSELECT * FROM crm_fields WHERE crm_configuration_id = 272 and object_type = 'opportunity';\nSELECT * FROM crm_field_values WHERE crm_field_id = 127164;\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 = 342 and sa.provider = 'pipedrive';\n\nSELECT * FROM teams WHERE id = 472;\nSELECT * FROM crm_configurations WHERE id = 380;\nselect * from activities where id = 38285673; # 38285673\nSELECT * FROM users WHERE id = 16942;\nSELECT * FROM groups WHERE id = 1964;\nSELECT * FROM playbooks WHERE id = 2033;\n\nselect * from teams where created_at > '2026-03-09';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 499; # 1065\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1678;\n\nSELECT * FROM teams WHERE id = 575;\nselect * from opportunities where team_id = 575;\n\nSELECT * FROM activities WHERE uuid_to_bin('96b1261f-2357-49f9-ab38-23ce12008ea0') = uuid;\n\nselect * from contacts c\nwhere c.crm_configuration_id = 370 order by c.updated_at desc;\n\nSELECT * FROM participants where activity_id = 38833541;\nSELECT * FROM participants where activity_id = 39216301;\nSELECT * FROM activity_summary_logs where activity_id = 39216301;\nSELECT * FROM activities WHERE uuid_to_bin('c7d99fbe-1fb1-41f2-8f4d-52e2bf70e1e9') = uuid; # 38833541, crm 478116564181\nSELECT * FROM activities WHERE uuid_to_bin('2e6ff4d3-9faa-447a-a8c1-9acde4d885ae') = uuid; # 39216301, crm 480171536586\nselect * from crm_profiles where crm_configuration_id = 319 and crm_provider_id = 525785080;\nselect * from opportunities where crm_configuration_id = 319 and crm_provider_id = 410150124747;\nselect * from accounts where crm_configuration_id = 319 and crm_provider_id = 47150650569;\nselect * from contacts where crm_configuration_id = 319 and crm_provider_id IN ('665587441856', '742723347700');\n# owner 13236 525785080\n# contact 1 16779180 665587441856 - activity - Alex Howes alex@supportroom.com created 2026-01-26\n# contact 2 19247563 742723347700 - ash@supportroom.com 2026-03-24\n# company 4176133 47150650569\n# deal 7100953 410150124747\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 = 400 and sa.provider = 'hubspot';\n\nselect * from features;\nselect * from team_features where feature_id = 40;\n\nselect * from teams where id = 556; # owner: 18101, crm: 477\nselect * from crm_configurations where id = 477;\nSELECT * FROM users WHERE id = 18101;\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 = 556 and sa.provider = 'integration-app';\n\nselect * from opportunities where id = 7594349;\nselect * from opportunity_stages where opportunity_id = 7594349 order by created_at desc;\nselect * from business_processes where id = 6024;\nselect * from business_process_stages where stage_id = 16352;\nselect * from business_process_stages where business_process_id = 6024;\nselect * from stages where team_id = 459;\nselect * from teams where id = 459;\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 = 459 and sa.provider = 'hubspot';\n\nSELECT os.stage_id, s.crm_provider_id, s.name, COUNT(*) as cnt\nFROM opportunity_stages os\nJOIN stages s ON s.id = os.stage_id\nWHERE os.opportunity_id = 7594349\nGROUP BY os.stage_id, s.crm_provider_id, s.name\nORDER BY cnt DESC;\n\nSELECT s.id, s.crm_provider_id, s.name, s.team_id, s.crm_configuration_id\nFROM stages s\nJOIN business_process_stages bps ON bps.stage_id = s.id\nWHERE bps.business_process_id = 6024\nAND s.crm_provider_id = 'contractsent';\n\nselect * from stages where id IN (16352,20612,18281,7344,16378,16309,5036,15223,14535,6293,12098,11607)\n\nSELECT * FROM teams WHERE name LIKE '%Pulsar Group%'; # 472, 380, 15138, raza.gilani@vuelio.com\nselect * from playbooks where team_id = 472; # event 226147\nSELECT * FROM playbook_categories WHERE playbook_id = 2288;\nSELECT * FROM crm_fields WHERE id = 226147;\nSELECT * FROM crm_field_values WHERE crm_field_id = 226147;\n\nSELECT * FROM crm_configurations WHERE id = 380;\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 = 472 and sa.provider = 'salesforce';\n\nselect * from activities where id = 58081273;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2;\n\nSELECT * FROM users WHERE name LIKE '%Neil Hoyle%'; # 17651\nSELECT * FROM social_accounts WHERE sociable_id = 17651;\n\nSELECT * FROM activities WHERE uuid_to_bin('975c6830-7d49-4c1e-b2e9-ac80c10a738a') = uuid;\nSELECT * FROM opportunities WHERE id IN (7842553, 6211727);\nSELECT * FROM contacts WHERE id IN (10202724, 6211727);\nSELECT * FROM opportunity_stages WHERE opportunity_id = 7842553;\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 = 519 and sa.provider = 'hubspot';\n\nselect * from crm_configurations where id = 436;\nselect * from crm_profiles where crm_configuration_id = 436; # 76091797 -> 16612\n\nselect * from contact_roles where contact_id = 10202724;\n\nselect * from stages where team_id = 519; # 18778\n18775\n\nSELECT\n id,\n crm_provider_id,\n stage_id,\n is_closed,\n is_won,\n stage_updated_at,\n updated_at\nFROM opportunities\nWHERE id IN (6211727, 7842553);\n\nSELECT * FROM opportunity_contacts\nWHERE opportunity_id = 6211727 AND contact_id = 10202724;\n\nSELECT id, name, stage_id, is_closed, is_won, updated_at, remotely_created_at\nFROM opportunities\nWHERE account_id = 8179134\nORDER BY updated_at DESC;\n\n\nselect * from text_relays where created_at > '2026-01-01';\nAND id IN (691, 692);\n\nselect * from teams;\n\n# ***************\nSELECT DISTINCT u.id, u.email, u.name, u.softphone_number, COUNT(a.id) as sms_count\nFROM users u\nINNER JOIN activities a ON u.id = a.user_id\nWHERE a.type LIKE 'sms%'\nAND a.created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)\nGROUP BY u.id, u.email, u.name, u.softphone_number\nORDER BY sms_count DESC;\n\nSELECT DISTINCT u.id, u.email, u.name, u.team_id, t.name as team_name,\n t.twilio_sms_sid, t.twilio_messaging_sid\nFROM users u\nINNER JOIN teams t ON u.team_id = t.id\nWHERE (t.twilio_sms_sid IS NOT NULL OR t.twilio_messaging_sid IS NOT NULL)\nAND u.status = 1\nORDER BY t.name, u.email;\n\nSELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, salesforce-admin@tourlane.com\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 = 187 and sa.provider = 'salesforce';\n\nselect * from activities where id = 31264367;\nselect * from contacts where id = 6331639;\nselect * from accounts where id = 4156632;\nselect * from opportunities where id = 4843610;\n# update `activities` set `account_id` = 4156632, `contact_id` = 6331639, `opportunity_id` = 4843610,\n# `stage_id` = 13273, `activities`.`updated_at` = 2026-05-22 07:16:17 where `id` = 31264367)\"\n\nselect * from text_relays where created_at > '2026-05-01';\n\nselect * from activities order by id desc;\n\nselect * from users where name like '%Subra%';\n\nSELECT * FROM opportunities WHERE uuid_to_bin('04a9cfad-2c87-4453-9e72-20aeb78ccf8d') = uuid;\nselect * from teams where id = 555;\nselect * from stages where team_id = 555;\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 = 100 and sa.provider = 'hubspot';","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.011968086,"top":0.047885075,"width":0.024268618,"height":0.024740623},"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}]...
|
6342989898062187878
|
2074961217668396653
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Code changed:
Hide
Sync Changes
Hide This Notification
31
9
29
3
109
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM team_features where team_id = 1;
SELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922
SELECT * FROM users WHERE team_id = 340; # 12015
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 340
and sa.provider = 'salesforce';
# and sa.provider = 'salesloft';
select * from crm_fields where crm_configuration_id = 270 and object_type = 'event';
# 125558 - Event Type - Event_Type__c
# 125552 - Event Status - Event_Status__c
SELECT * FROM sidekick_settings WHERE team_id = 340;
SELECT * FROM crm_field_values WHERE crm_field_id in (125552);
select * from activities where crm_configuration_id = 270
and type = 'conference' and crm_provider_id IS NOT NULL
and actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;
SELECT * FROM activities WHERE id = 20871677;
SELECT * FROM crm_field_data WHERE activity_id = 20871677;
select * from crm_layouts where crm_configuration_id = 270;
select * from crm_layout_entities where crm_layout_id in (886,887);
SELECT * FROM crm_configurations WHERE id = 270;
select * from playbooks where team_id = 340; # 1514
select * from groups where team_id = 340;
SELECT * FROM crm_fields WHERE id IN (125393, 125401);
select g.name as 'team name', p.name as 'playbook name', f.label as 'activity type field' from groups g
join playbooks p on g.playbook_id = p.id
join crm_fields f on p.activity_field_id = f.id
where g.team_id = 340;
SELECT * FROM activities WHERE uuid_to_bin('0c180357-67d2-419e-a8c3-b832a3490770') = uuid; # 20448716
select * from crm_field_data where object_id = 20448716;
select * from activities where crm_configuration_id = 270 and provider = 'salesloft' order by id desc;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%CybSafe%'; # 343,273,12008
select * from opportunities where team_id = 343;
select * from opportunities where team_id = 343 and crm_provider_id = '18099102526';
select * from opportunities where team_id = 343 and account_id = 945217482;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
select * from accounts where team_id = 343 order by name asc;
select * from stages where crm_configuration_id = 273 and type = 'opportunity';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Voyado%'; # 353,283,12143
SELECT * FROM activities WHERE crm_configuration_id = 283 and account_id = 3777844 order by id desc;
SELECT * FROM accounts WHERE team_id = 353 AND name LIKE '%Salesloft%';
SELECT * FROM activities WHERE id = 20717903;
select * from participants where activity_id IN (20929172,20928605,20928468,20926272,20926271,20926270,20926269,20916499,20916454,20916436,20916435,20900015,20900014,20900013,20897312,20897243,20897241,20897237,20897232,20897229,20893648,20893231,20893230,20893229,20893228,20889784,20885039,20885038,20885037,20885036,20885035,20882728,20882708,20882703,20882702,20869828,20869811,20869806,20869801,20869799,20869798,20869796,20869795,20869794,20869761,20869760,20869759,20868688,20868687,20850340,20847195,20841710,20833967,20827021,20825307,20825305,20825297,20824615,20824400,20823927,20821760,20795588,20794233,20794057,20793710,20785811,20781789,20781394,20781307,20762651,20758453,20758282,20757323,20756643,20756636,20756629,20756627,20756606,20756605,20756604,20756603,20756602,20756600,20756599,20756598,20756595,20756594,20756589,20756587,20756577,20756573,20748918,20748386,20748385,20748384,20748383,20748382,20748381,20748380,20748379,20748377,20748375,20748373,20743301,20717905,20717904,20717903,20717901,20717899);
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 353
and sa.provider = 'salesforce';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%modern world business solutions%'; # 345,275,12016, [EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('3921d399-3fef-4609-a291-b0097a166d43') = uuid;
# id: 20940638, user: 12022, contact: 5305871
SELECT * FROM activity_summary_logs WHERE activity_id = 20940638;
select * from contacts where team_id = 345 and crm_provider_id = '30891432415' order by name asc; # 5305871
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 345
and sa.provider = 'hubspot';
select * from users where team_id = 345 and id = 12022;
SELECT * FROM crm_profiles WHERE user_id = 12022;
SELECT * FROM participants WHERE activity_id = 20940638;
SELECT * FROM users u
JOIN crm_profiles cp ON u.id = cp.user_id
WHERE u.team_id = 345;
select * from contacts where team_id = 345 and crm_provider_id = '30880813535' order by name desc; # 5305871
select * from team_features where team_id = 345;
SELECT * FROM activities WHERE uuid_to_bin('11701e2d-2f82-4dab-a616-1db4fad238df') = uuid; # 21115197
SELECT * FROM participants WHERE activity_id = 20897406;
SELECT * FROM activities WHERE uuid_to_bin('63ba55cd-1abc-447d-83da-0137000005b7') = uuid; # 20953912
SELECT * FROM activities WHERE crm_configuration_id = 275 and provider = 'ringcentral' and title like '%1252629100%';
SELECT * FROM activities WHERE id = 20946641;
SELECT * FROM crm_profiles WHERE user_id = 10211;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120,97,10984, [EMAIL]
SELECT * FROM opportunities WHERE crm_configuration_id = 97 and crm_provider_id = '006N1000006c5PpIAI';
select * from stages where crm_configuration_id = 97 and type = 'opportunity';
select * from opportunities where team_id = 120;
select * from crm_configurations crm join teams t on crm.id = t.crm_id
where 1=1
AND t.current_billing_plan IS NOT NULL
AND crm.auto_sync_activity = 0
and crm.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Exclaimer%'; # 270,205,10053,[EMAIL]
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 270
and sa.provider = 'salesforce';
SELECT * FROM activities WHERE uuid_to_bin('b54df794-2a9a-4957-8d80-09a600ead5f8') = uuid; # 21637956
SELECT * FROM crm_profiles WHERE user_id = 11446;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Cygnetise%'; # 372,300,12554, [EMAIL]
select * from playbooks where team_id = 372;
select * from crm_fields where crm_configuration_id = 300 and object_type = 'event'; # 141340
SELECT * FROM crm_field_values WHERE crm_field_id = 141340;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 372
and sa.provider = 'salesforce';
select * from crm_profiles where crm_configuration_id = 300;
SELECT * FROM crm_configurations WHERE team_id = 372;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Planday%'; # 291,242,11501,[EMAIL]
SELECT * FROM opportunities WHERE team_id = 291 and crm_provider_id = '006bG000005DO86QAG'; # 3207756
select * from crm_field_data where object_id = 3207756;
SELECT * FROM crm_fields WHERE id = 111834;
select f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value
FROM crm_fields f
JOIN crm_field_data fd ON f.id = fd.crm_field_id
WHERE f.crm_configuration_id = 242
AND f.object_type = 'opportunity'
AND fd.object_id IN (3207756)
ORDER BY fd.object_id, fd.updated_at;
SELECT * FROM crm_configurations WHERE auto_connect = 1;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150,[EMAIL]
select * from group_deal_risk_types drgt join groups g on drgt.group_id = g.id
where g.team_id = 187;
select * from `groups` where team_id = 187;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 187
and sa.provider = 'salesforce';
# Destination - 98870 - Destination__c
# Stage - 79014 - StageName
# Land Arrangement - 98856 - Land_Arrangement__c
# Flight - 98848 - Flight__c
# Last activity date - 98812 - LastActivityDate
# Last modified date - 98809 - LastModifiedDate
# Last inbound mail timestamp - 99151 - Last_Inbound_Mail_Timestamp__c
# next call - 98864 - Next_Call__c
select * from crm_fields where crm_configuration_id = 209 and object_type = 'opportunity';
SELECT * FROM crm_layouts WHERE crm_configuration_id = 209;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;
select * from opportunities where team_id = 187 and name LIKE'%Muriel Sal%';
select * from opportunities where team_id = 187 and user_id = 9951 and is_closed = 0;
select * from activities where opportunity_id = 3538248;
SELECT * FROM crm_profiles WHERE user_id = 8150;
select * from deal_risks where opportunity_id = 3538248;
select * from teams where crm_id IS NULL;
SELECT opp.id AS opportunity_id,
u.group_id AS group_id,
MAX(
CASE
WHEN a.type IN ("sms-inbound", "sms-outbound") THEN a.created_at
ELSE a.actual_end_time
END) as last_date
FROM opportunities opp
left join activities a on a.opportunity_id = opp.id
inner join users u on opp.user_id = u.id
where opp.user_id IN (9951)
AND opp.is_closed = 0
and a.status IN ('completed', 'received', 'delivered') OR a.status IS NULL
group by opp.id;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Cybsafe%'; # 343,301,12008,[EMAIL]
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
SELECT * FROM crm_profiles WHERE crm_configuration_id = 301;
SELECT * FROM contacts WHERE id = 6612363;
SELECT * FROM accounts WHERE id = 4235676;
SELECT * FROM opportunities WHERE crm_configuration_id = 301 and crm_provider_id = 32983784868;
select * from opportunity_stages where opportunity_id = 4503759;
# SELECT * FROM opportunities WHERE id = 4569937;
select * from activities where crm_configuration_id = 301;
SELECT * FROM activities WHERE uuid_to_bin('d3b2b28b-c3d0-4c2d-8ed0-eef42855278a') = uuid; # 26330370
SELECT * FROM participants WHERE activity_id = 26330370;
SELECT * FROM teams WHERE id = 375;
select * from playbooks where team_id = 375;
select * from stages where crm_configuration_id = 301 and type = 'opportunity';
select * from teams;
select * from contact_roles;
SELECT * FROM opportunities WHERE team_id = 343 and user_id = 12871 and close_date >= '2024-11-01';
select * from users u join crm_profiles cp on cp.user_id = u.id where u.team_id = 343;
SELECT * FROM crm_field_data WHERE object_id = 3771706;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
SELECT * FROM crm_fields WHERE crm_configuration_id = 301 and object_type = 'opportunity'
and crm_provider_id LIKE "%traffic_light%";
SELECT * FROM crm_field_values WHERE crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531);
SELECT fd.* FROM opportunities o
JOIN crm_field_data fd ON o.id = fd.object_id
WHERE o.team_id = 343
# and o.user_id IS NOT NULL
and fd.crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531)
and fd.value != ''
order by value desc
# group by o.id
;
SELECT * FROM opportunities WHERE id = 3769843;
SELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150, [EMAIL]
SELECT * FROM crm_layouts WHERE crm_configuration_id = 209;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Funding Circle%'; # 220,177,8603,[EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('7a40e99b-3b37-4bb1-b983-325b81801c01') = uuid; # 23139839
SELECT * FROM opportunities WHERE id = 3855992;
SELECT * FROM users WHERE name LIKE '%Angus Pollard%'; # 8988
SELECT * FROM teams WHERE name LIKE '%Story Terrace%'; # 379, 307, 12894
SELECT * FROM crm_fields WHERE crm_configuration_id = 307 and object_type != 'opportunity';
select * from contacts where team_id = 379 and name like '%bebro%'; # 5874411, crm: 77229348507
SELECT * FROM crm_field_data WHERE object_id = 5874411;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 379
and sa.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%mentio%'; # 117, 94, 6371, [EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('82939311-1af0-4506-8546-21e8d1fdf2c1') = uuid;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, [EMAIL]
SELECT * FROM opportunities WHERE team_id = 187 and crm_provider_id = '006Se000008xfvNIAQ'; # 3537793
select * from generic_ai_prompts where subject_id = 3537793;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120, 97, 10984, [EMAIL]
SELECT * FROM crm_configurations WHERE id = 97;
SELECT * FROM crm_layouts WHERE crm_configuration_id = 97;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 355;
SELECT * FROM crm_fields WHERE id = 32682;
select cfd.value, o.* from opportunities o
join crm_field_data cfd on o.id = cfd.object_id and cfd.crm_field_id = 32682
where team_id = 120
and cfd.value != ''
;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 120
and sa.provider = 'salesforce';
select * from opportunities where team_id = 120 and crm_provider_id = '006N1000007X8MAIA0';
SELECT * FROM crm_field_data WHERE object_id = 2313439;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE id = 410;
SELECT * FROM teams WHERE name LIKE '%Local Business Oxford%';
select * from scorecards where team_id = 410;
select * from scorecard_rules;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Funding%'; # 220, 177, 8603, [EMAIL]
select * from activities a
join opportunities o on a.opportunity_id = o.id
join users u on o.user_id = u.id
where a.crm_configuration_id = 177 and a.type LIKE '%email-out%'
# and a.actual_end_time > '2024-12-16 00:00:00'
# and o.remotely_created_at > '2024-12-01 00:00:00'
# and u.group_id = 1014
and u.id = 9021
order by a.id desc;
SELECT * FROM opportunities WHERE id in (3981384,4017346);
SELECT * FROM users WHERE team_id = 220 and id IN (8775, 11435);
select * from users where id = 9021;
select * from inboxes where user_id = 9021;
select * from inbox_emails where inbox_id = 1349 and email_date > '2024-12-18 00:00:00';
select * from email_messages where team_id = 220
and orig_date > '2024-12-16 00:00:00' and orig_date < '2024-12-19 00:00:00'
and subject LIKE '%Personal%'
# and 'from' = '[EMAIL]'
;
select * from activities a
join opportunities o on a.opportunity_id = o.id
where a.user_id = 9021 and a.type LIKE '%email-out%'
and a.actual_end_time > '2024-12-18 00:00:00'
and o.user_id IS NOT NULL
and o.remotely_created_at > '2024-12-01 00:00:00'
order by a.id desc;
SELECT * FROM opportunities WHERE team_id = 220 and name LIKE '%Right Car move Limited%' and id = 3966852;
select * from activities where crm_configuration_id = 177 and type LIKE '%email%' and opportunity_id = 3966852 order by id desc;
select * from team_settings where name IN ('useCloseDate');
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Hurree%'; # 104, 81, 6175, [EMAIL]
SELECT * FROM opportunities WHERE team_id = 104 and name = 'PropOp';
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 104
and sa.provider = 'hubspot';
select * from crm_configurations where last_synced_at > '2025-01-19 01:00:00'
select * from teams where crm_id IS NULL;
select t.name as 'team', u.name as 'owner', u.email, u.phone
from teams t
join activity_providers ap on t.id = ap.team_id
join users u on t.owner_id = u.id
where 1=1
and t.status = 'active'
and ap.is_enabled = 1
# and u.status = 1
and ap.provider = 'ms-teams';
select * from crm_configurations where provider = 'bullhorn'; # 344
SELECT * FROM teams WHERE id = 442; # 14293
select * from users where team_id = 442;
select * from social_accounts sa where sa.sociable_id = 14293;
select * from invitations where team_id = 442;
# [PASSWORD_DOTS]
SELECT * FROM users WHERE email LIKE '%[EMAIL]%'; # 14022
SELECT * FROM teams WHERE id = 429;
select * from opportunities where team_id = 429 and crm_provider_id IN (16157415775, 22246219645);
select * from activities where opportunity_id in (4340436,4353519);
select * from transcription where activity_id IN (25630961,25381771);
select * from generic_ai_prompts where subject_id IN (4353519);
SELECT
a.id as activity_id,
a.opportunity_id,
a.type as activity_type,
a.language,
CONCAT(a.title, a.description) AS mail_content,
e.from AS mail_from,
e.to AS mail_to,
e.subject AS mail_subject,
e.body AS mail_body,
p.type as prompt_type,
p.status as prompt_status,
p.content AS prompt_content,
a.actual_start_time as created_at
FROM activities a
LEFT JOIN ai_prompts p ON a.transcription_id = p.transcription_id AND p.deleted_at IS NULL
LEFT JOIN email_messages e ON a.id = e.activity_id
WHERE a.actual_start_time > '2024-01-01 00:00:00'
AND a.opportunity_id IN (4353519)
AND a.status IN ('completed', 'received', 'delivered')
AND a.deleted_at IS NULL
AND a.type NOT IN ('sms-inbound', 'sms-outbound')
ORDER BY a.opportunity_id ASC, a.id ASC;
SELECT * FROM users WHERE name LIKE '%George Fierstone%'; # 14293
SELECT * FROM teams WHERE id = 442;
SELECT * FROM crm_configurations WHERE id = 344;
select * from team_features where team_id = 442;
select * from groups where team_id = 442;
select * from playbooks where team_id = 442;
select * from playbook_categories where playbook_id = 1729;
select * from crm_fields where crm_configuration_id = 344 and id = 172024;
SELECT * FROM crm_field_values WHERE crm_field_id = 172024;
select * from crm_layouts where crm_configuration_id = 344;
select * from playbook_layouts where playbook_id = 1729;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 221, 9444
select s.*
# , s.sent_at, u.name, a.*
from activity_summary_logs s
inner join activities a on a.id = s.activity_id
inner join users u on u.id = a.user_id
where a.crm_configuration_id = 356
and s.sent_at > date_sub(now(), interval 60 day)
order by a.actual_end_time desc;
select * from activities a
# inner join activity_summary_logs s on s.activity_id = a.id
where a.crm_configuration_id = 356 and a.actual_end_time > date_sub(now(), interval 60 day)
# and a.crm_provider_id is not null
# and provider <> 'ringcentral'
and status = 'completed'
order by a.actual_end_time desc;
select * from teams order by id desc; # 17328, 32, 17830, [EMAIL]
SELECT * FROM users;
SELECT * FROM users where team_id = 260 and status = 1; # 201 - 150 active
SELECT * FROM teams WHERE id = 260;
select * from team_settings where team_id = 260;
select * from crm_configurations where team_id = 260;
SELECT * FROM crm_layouts WHERE crm_configuration_id = 356;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1184;
select * from accounts where crm_configuration_id = 221 order by id desc; # 7000
select * from leads where crm_configuration_id = 221 order by id desc; # 0
select * from contacts where crm_configuration_id = 221 order by id desc; # 200 000
select * from opportunities where crm_configuration_id = 221 order by id desc; # 0
select * from crm_profiles where crm_configuration_id = 221 order by id desc; # 23
select * from crm_fields where crm_configuration_id = 221;
select * from crm_field_values where crm_field_id = 5302 order by id desc;
select * from crm_layouts where crm_configuration_id = 221 order by id desc;
select * from stages where crm_configuration_id = 221 order by id desc;
select * from accounts where crm_configuration_id = 356 order by id desc; # 7000
select * from leads where crm_configuration_id = 356 order by id desc; # 0
select * from contacts where crm_configuration_id = 356 order by id desc; # 200 000
select * from opportunities where crm_configuration_id = 356 order by id desc; # 0
select * from crm_profiles where crm_configuration_id = 356 order by id desc; # 23
select * from crm_fields where crm_configuration_id = 356;
select * from crm_field_values where crm_field_id = 5302 order by id desc;
select * from crm_layouts where crm_configuration_id = 356 order by id desc;
select * from stages where crm_configuration_id = 356 order by id desc;
select * from playbooks where team_id = 260 order by id desc; # 4 (2 deleted)
select * from groups where team_id = 260 order by id desc; # 27 groups, (2 deleted)
select * from playbook_layouts where playbook_id IN (1410,1409,1276,1254); # 4
select ce.* from calendars c
join users u on c.user_id = u.id
join calendar_events ce on c.id = ce.calendar_id
where u.team_id = 260
and (ce.start_time > '2025-02-21 00:00:00')
;
# calendar events 1207
#
select * from opportunities where team_id = 260;
SELECT * FROM crm_field_data WHERE object_id = 4696496;
select * from activities where crm_configuration_id = 356 and crm_provider_id IS NOT NULL;
select * from activities where crm_configuration_id IN (221) and provider NOT IN ('ms-teams', 'uploader', 'zoom-bot')
# and type = 'conference' and status = 'scheduled' and activities.is_internal = 0
and created_at > '2024-03-01 00:00:00'
order by id desc; # 880 000, ringcentral, avaya
SELECT * FROM participants WHERE activity_id = 26371744;
# all activities 942 000 +
# conference 7385 - scheduled 984 - external 343
select * from activities where id = 26321812;
select * from participants where activity_id = 26321812;
select * from participants where activity_id in (26414510,26414514,26414516,26414604,26414653,26414655);
select * from leads where id in (720428,689175,731546,645866,621037);
select * from users where id = 13841;
select * from opportunities where user_id = 9541;
select * from stages where id = 15900;
select * from accounts where
# id IN (4160055,5053725,4965303,4896434)
id in (4584518,3249934,3218025,3891133,3399450,4172999,4485161,3101785,4587203,3070816,2870343,2870341,3563940,4550846,3424464,3249963,2870342)
;
select * from activities where id = 26654935;
SELECT * FROM opportunities WHERE id = 4803458;
SELECT * FROM opportunities where team_id = 260 and user_id = 13841 AND stage_id = 15900;
SELECT id, uuid, provider, type, lead_id, account_id, contact_id, opportunity_id, stage_id, status, recording_state, title, actual_start_time, actual_end_time
FROM activities WHERE user_id = 13841 AND opportunity_id IN (4729783, 4731717, 4731726, 4732064, 4732849, 4803458, 4813213);
SELECT DISTINCT
o.id, o.stage_id, s.name, a.title,
a.*
FROM activities a
# INNER JOIN tracks t ON a.id = t.activity_id
INNER JOIN users u ON a.user_id = u.id
INNER JOIN teams team ON u.team_id = team.id
INNER JOIN groups g ON u.group_id = g.id
INNER JOIN opportunities o ON a.opportunity_id = o.id
INNER JOIN stages s ON o.stage_id = s.id
WHERE
a.crm_configuration_id = 356
AND a.status IN ('completed', 'failed')
AND a.recording_state != 'stopped'
# and a.user_id = 13841
AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')
AND team.uuid = uuid_to_bin('a607fba7-452e-4683-b2af-00d6cb52c93c')
AND g.uuid = uuid_to_bin('b5d69e40-24a0-4c16-810b-5fa462299f94')
AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')
# AND t.type IN ('audio', 'video')
AND (
(a.actual_start_time BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59')
OR
(
a.actual_start_time IS NULL
AND a.type IN ('sms-outbound', 'sms-inbound')
AND a.created_at BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59'
)
)
AND (
a.is_private = 0
OR (
a.is_private = 1
AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')
)
)
AND (
# s.id = 15900
s.uuid = uuid_to_bin('04ca1c26-c666-4268-a129-419c0acffd73')
OR s.uuid IS NULL -- Include records without opportunity stage
)
ORDER BY a.actual_end_time DESC;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lead Forensics%'; # 190, 162, 8474, [EMAIL]
SELECT * FROM users WHERE team_id = 190;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 190
and sa.provider = 'hubspot';
select * from role_user where user_id = 8474;
select * from crm_configurations where provider = 'bullhorn';
SELECT * FROM opportunities WHERE uuid_to_bin('94578249-65ec-4205-90f2-7d1a7d5ab64a') = uuid;
SELECT * FROM users WHERE uuid_to_bin('26dbadeb-926f-4150-b11b-771b9d4c2f9a') = uuid;
SELECT * FROM opportunities ...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87832
|
3001
|
4
|
2026-05-28T16:25:29.447057+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985529447_m2.jpg...
|
PhpStorm
|
faVsco.js – console [EU]
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Code changed:
Hide
Sync Changes
Hide This Notification
31
9
29
3
109
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM team_features where team_id = 1;
SELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922
SELECT * FROM users WHERE team_id = 340; # 12015
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 340
and sa.provider = 'salesforce';
# and sa.provider = 'salesloft';
select * from crm_fields where crm_configuration_id = 270 and object_type = 'event';
# 125558 - Event Type - Event_Type__c
# 125552 - Event Status - Event_Status__c
SELECT * FROM sidekick_settings WHERE team_id = 340;
SELECT * FROM crm_field_values WHERE crm_field_id in (125552);
select * from activities where crm_configuration_id = 270
and type = 'conference' and crm_provider_id IS NOT NULL
and actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;
SELECT * FROM activities WHERE id = 20871677;
SELECT * FROM crm_field_data WHERE activity_id = 20871677;
select * from crm_layouts where crm_configuration_id = 270;
select * from crm_layout_entities where crm_layout_id in (886,887);
SELECT * FROM crm_configurations WHERE id = 270;
select * from playbooks where team_id = 340; # 1514
select * from groups where team_id = 340;
SELECT * FROM crm_fields WHERE id IN (125393, 125401);
select g.name as 'team name', p.name as 'playbook name', f.label as 'activity type field' from groups g
join playbooks p on g.playbook_id = p.id
join crm_fields f on p.activity_field_id = f.id
where g.team_id = 340;
SELECT * FROM activities WHERE uuid_to_bin('0c180357-67d2-419e-a8c3-b832a3490770') = uuid; # 20448716
select * from crm_field_data where object_id = 20448716;
select * from activities where crm_configuration_id = 270 and provider = 'salesloft' order by id desc;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%CybSafe%'; # 343,273,12008
select * from opportunities where team_id = 343;
select * from opportunities where team_id = 343 and crm_provider_id = '18099102526';
select * from opportunities where team_id = 343 and account_id = 945217482;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
select * from accounts where team_id = 343 order by name asc;
select * from stages where crm_configuration_id = 273 and type = 'opportunity';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Voyado%'; # 353,283,12143
SELECT * FROM activities WHERE crm_configuration_id = 283 and account_id = 3777844 order by id desc;
SELECT * FROM accounts WHERE team_id = 353 AND name LIKE '%Salesloft%';
SELECT * FROM activities WHERE id = 20717903;
select * from participants where activity_id IN (20929172,20928605,20928468,20926272,20926271,20926270,20926269,20916499,20916454,20916436,20916435,20900015,20900014,20900013,20897312,20897243,20897241,20897237,20897232,20897229,20893648,20893231,20893230,20893229,20893228,20889784,20885039,20885038,20885037,20885036,20885035,20882728,20882708,20882703,20882702,20869828,20869811,20869806,20869801,20869799,20869798,20869796,20869795,20869794,20869761,20869760,20869759,20868688,20868687,20850340,20847195,20841710,20833967,20827021,20825307,20825305,20825297,20824615,20824400,20823927,20821760,20795588,20794233,20794057,20793710,20785811,20781789,20781394,20781307,20762651,20758453,20758282,20757323,20756643,20756636,20756629,20756627,20756606,20756605,20756604,20756603,20756602,20756600,20756599,20756598,20756595,20756594,20756589,20756587,20756577,20756573,20748918,20748386,20748385,20748384,20748383,20748382,20748381,20748380,20748379,20748377,20748375,20748373,20743301,20717905,20717904,20717903,20717901,20717899);
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 353
and sa.provider = 'salesforce';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%modern world business solutions%'; # 345,275,12016, [EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('3921d399-3fef-4609-a291-b0097a166d43') = uuid;
# id: 20940638, user: 12022, contact: 5305871
SELECT * FROM activity_summary_logs WHERE activity_id = 20940638;
select * from contacts where team_id = 345 and crm_provider_id = '30891432415' order by name asc; # 5305871
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 345
and sa.provider = 'hubspot';
select * from users where team_id = 345 and id = 12022;
SELECT * FROM crm_profiles WHERE user_id = 12022;
SELECT * FROM participants WHERE activity_id = 20940638;
SELECT * FROM users u
JOIN crm_profiles cp ON u.id = cp.user_id
WHERE u.team_id = 345;
select * from contacts where team_id = 345 and crm_provider_id = '30880813535' order by name desc; # 5305871
select * from team_features where team_id = 345;
SELECT * FROM activities WHERE uuid_to_bin('11701e2d-2f82-4dab-a616-1db4fad238df') = uuid; # 21115197
SELECT * FROM participants WHERE activity_id = 20897406;
SELECT * FROM activities WHERE uuid_to_bin('63ba55cd-1abc-447d-83da-0137000005b7') = uuid; # 20953912
SELECT * FROM activities WHERE crm_configuration_id = 275 and provider = 'ringcentral' and title like '%1252629100%';
SELECT * FROM activities WHERE id = 20946641;
SELECT * FROM crm_profiles WHERE user_id = 10211;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120,97,10984, [EMAIL]
SELECT * FROM opportunities WHERE crm_configuration_id = 97 and crm_provider_id = '006N1000006c5PpIAI';
select * from stages where crm_configuration_id = 97 and type = 'opportunity';
select * from opportunities where team_id = 120;
select * from crm_configurations crm join teams t on crm.id = t.crm_id
where 1=1
AND t.current_billing_plan IS NOT NULL
AND crm.auto_sync_activity = 0
and crm.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Exclaimer%'; # 270,205,10053,[EMAIL]
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 270
and sa.provider = 'salesforce';
SELECT * FROM activities WHERE uuid_to_bin('b54df794-2a9a-4957-8d80-09a600ead5f8') = uuid; # 21637956
SELECT * FROM crm_profiles WHERE user_id = 11446;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Cygnetise%'; # 372,300,12554, [EMAIL]
select * from playbooks where team_id = 372;
select * from crm_fields where crm_configuration_id = 300 and object_type = 'event'; # 141340
SELECT * FROM crm_field_values WHERE crm_field_id = 141340;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 372
and sa.provider = 'salesforce';
select * from crm_profiles where crm_configuration_id = 300;
SELECT * FROM crm_configurations WHERE team_id = 372;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Planday%'; # 291,242,11501,[EMAIL]
SELECT * FROM opportunities WHERE team_id = 291 and crm_provider_id = '006bG000005DO86QAG'; # 3207756
select * from crm_field_data where object_id = 3207756;
SELECT * FROM crm_fields WHERE id = 111834;
select f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value
FROM crm_fields f
JOIN crm_field_data fd ON f.id = fd.crm_field_id
WHERE f.crm_configuration_id = 242
AND f.object_type = 'opportunity'
AND fd.object_id IN (3207756)
ORDER BY fd.object_id, fd.updated_at;
SELECT * FROM crm_configurations WHERE auto_connect = 1;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150,[EMAIL]
select * from group_deal_risk_types drgt join groups g on drgt.group_id = g.id
where g.team_id = 187;
select * from `groups` where team_id = 187;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 187
and sa.provider = 'salesforce';
# Destination - 98870 - Destination__c
# Stage - 79014 - StageName
# Land Arrangement - 98856 - Land_Arrangement__c
# Flight - 98848 - Flight__c
# Last activity date - 98812 - LastActivityDate
# Last modified date - 98809 - LastModifiedDate
# Last inbound mail timestamp - 99151 - Last_Inbound_Mail_Timestamp__c
# next call - 98864 - Next_Call__c
select * from crm_fields where crm_configuration_id = 209 and object_type = 'opportunity';
SELECT * FROM crm_layouts WHERE crm_configuration_id = 209;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;
select * from opportunities where team_id = 187 and name LIKE'%Muriel Sal%';
select * from opportunities where team_id = 187 and user_id = 9951 and is_closed = 0;
select * from activities where opportunity_id = 3538248;
SELECT * FROM crm_profiles WHERE user_id = 8150;
select * from deal_risks where opportunity_id = 3538248;
select * from teams where crm_id IS NULL;
SELECT opp.id AS opportunity_id,
u.group_id AS group_id,
MAX(
CASE
WHEN a.type IN ("sms-inbound", "sms-outbound") THEN a.created_at
ELSE a.actual_end_time
END) as last_date
FROM opportunities opp
left join activities a on a.opportunity_id = opp.id
inner join users u on opp.user_id = u.id
where opp.user_id IN (9951)
AND opp.is_closed = 0
and a.status IN ('completed', 'received', 'delivered') OR a.status IS NULL
group by opp.id;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Cybsafe%'; # 343,301,12008,[EMAIL]
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
SELECT * FROM crm_profiles WHERE crm_configuration_id = 301;
SELECT * FROM contacts WHERE id = 6612363;
SELECT * FROM accounts WHERE id = 4235676;
SELECT * FROM opportunities WHERE crm_configuration_id = 301 and crm_provider_id = 32983784868;
select * from opportunity_stages where opportunity_id = 4503759;
# SELECT * FROM opportunities WHERE id = 4569937;
select * from activities where crm_configuration_id = 301;
SELECT * FROM activities WHERE uuid_to_bin('d3b2b28b-c3d0-4c2d-8ed0-eef42855278a') = uuid; # 26330370
SELECT * FROM participants WHERE activity_id = 26330370;
SELECT * FROM teams WHERE id = 375;
select * from playbooks where team_id = 375;
select * from stages where crm_configuration_id = 301 and type = 'opportunity';
select * from teams;
select * from contact_roles;
SELECT * FROM opportunities WHERE team_id = 343 and user_id = 12871 and close_date >= '2024-11-01';
select * from users u join crm_profiles cp on cp.user_id = u.id where u.team_id = 343;
SELECT * FROM crm_field_data WHERE object_id = 3771706;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
SELECT * FROM crm_fields WHERE crm_configuration_id = 301 and object_type = 'opportunity'
and crm_provider_id LIKE "%traffic_light%";
SELECT * FROM crm_field_values WHERE crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531);
SELECT fd.* FROM opportunities o
JOIN crm_field_data fd ON o.id = fd.object_id
WHERE o.team_id = 343
# and o.user_id IS NOT NULL
and fd.crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531)
and fd.value != ''
order by value desc
# group by o.id
;
SELECT * FROM opportunities WHERE id = 3769843;
SELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150, [EMAIL]
SELECT * FROM crm_layouts WHERE crm_configuration_id = 209;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Funding Circle%'; # 220,177,8603,[EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('7a40e99b-3b37-4bb1-b983-325b81801c01') = uuid; # 23139839
SELECT * FROM opportunities WHERE id = 3855992;
SELECT * FROM users WHERE name LIKE '%Angus Pollard%'; # 8988
SELECT * FROM teams WHERE name LIKE '%Story Terrace%'; # 379, 307, 12894
SELECT * FROM crm_fields WHERE crm_configuration_id = 307 and object_type != 'opportunity';
select * from contacts where team_id = 379 and name like '%bebro%'; # 5874411, crm: 77229348507
SELECT * FROM crm_field_data WHERE object_id = 5874411;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 379
and sa.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%mentio%'; # 117, 94, 6371, [EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('82939311-1af0-4506-8546-21e8d1fdf2c1') = uuid;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, [EMAIL]
SELECT * FROM opportunities WHERE team_id = 187 and crm_provider_id = '006Se000008xfvNIAQ'; # 3537793
select * from generic_ai_prompts where subject_id = 3537793;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120, 97, 10984, [EMAIL]
SELECT * FROM crm_configurations WHERE id = 97;
SELECT * FROM crm_layouts WHERE crm_configuration_id = 97;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 355;
SELECT * FROM crm_fields WHERE id = 32682;
select cfd.value, o.* from opportunities o
join crm_field_data cfd on o.id = cfd.object_id and cfd.crm_field_id = 32682
where team_id = 120
and cfd.value != ''
;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 120
and sa.provider = 'salesforce';
select * from opportunities where team_id = 120 and crm_provider_id = '006N1000007X8MAIA0';
SELECT * FROM crm_field_data WHERE object_id = 2313439;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE id = 410;
SELECT * FROM teams WHERE name LIKE '%Local Business Oxford%';
select * from scorecards where team_id = 410;
select * from scorecard_rules;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Funding%'; # 220, 177, 8603, [EMAIL]
select * from activities a
join opportunities o on a.opportunity_id = o.id
join users u on o.user_id = u.id
where a.crm_configuration_id = 177 and a.type LIKE '%email-out%'
# and a.actual_end_time > '2024-12-16 00:00:00'
# and o.remotely_created_at > '2024-12-01 00:00:00'
# and u.group_id = 1014
and u.id = 9021
order by a.id desc;
SELECT * FROM opportunities WHERE id in (3981384,4017346);
SELECT * FROM users WHERE team_id = 220 and id IN (8775, 11435);
select * from users where id = 9021;
select * from inboxes where user_id = 9021;
select * from inbox_emails where inbox_id = 1349 and email_date > '2024-12-18 00:00:00';
select * from email_messages where team_id = 220
and orig_date > '2024-12-16 00:00:00' and orig_date < '2024-12-19 00:00:00'
and subject LIKE '%Personal%'
# and 'from' = '[EMAIL]'
;
select * from activities a
join opportunities o on a.opportunity_id = o.id
where a.user_id = 9021 and a.type LIKE '%email-out%'
and a.actual_end_time > '2024-12-18 00:00:00'
and o.user_id IS NOT NULL
and o.remotely_created_at > '2024-12-01 00:00:00'
order by a.id desc;
SELECT * FROM opportunities WHERE team_id = 220 and name LIKE '%Right Car move Limited%' and id = 3966852;
select * from activities where crm_configuration_id = 177 and type LIKE '%email%' and opportunity_id = 3966852 order by id desc;
select * from team_settings where name IN ('useCloseDate');
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Hurree%'; # 104, 81, 6175, [EMAIL]
SELECT * FROM opportunities WHERE team_id = 104 and name = 'PropOp';
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 104
and sa.provider = 'hubspot';
select * from crm_configurations where last_synced_at > '2025-01-19 01:00:00'
select * from teams where crm_id IS NULL;
select t.name as 'team', u.name as 'owner', u.email, u.phone
from teams t
join activity_providers ap on t.id = ap.team_id
join users u on t.owner_id = u.id
where 1=1
and t.status = 'active'
and ap.is_enabled = 1
# and u.status = 1
and ap.provider = 'ms-teams';
select * from crm_configurations where provider = 'bullhorn'; # 344
SELECT * FROM teams WHERE id = 442; # 14293
select * from users where team_id = 442;
select * from social_accounts sa where sa.sociable_id = 14293;
select * from invitations where team_id = 442;
# [PASSWORD_DOTS]
SELECT * FROM users WHERE email LIKE '%[EMAIL]%'; # 14022
SELECT * FROM teams WHERE id = 429;
select * from opportunities where team_id = 429 and crm_provider_id IN (16157415775, 22246219645);
select * from activities where opportunity_id in (4340436,4353519);
select * from transcription where activity_id IN (25630961,25381771);
select * from generic_ai_prompts where subject_id IN (4353519);
SELECT
a.id as activity_id,
a.opportunity_id,
a.type as activity_type,
a.language,
CONCAT(a.title, a.description) AS mail_content,
e.from AS mail_from,
e.to AS mail_to,
e.subject AS mail_subject,
e.body AS mail_body,
p.type as prompt_type,
p.status as prompt_status,
p.content AS prompt_content,
a.actual_start_time as created_at
FROM activities a
LEFT JOIN ai_prompts p ON a.transcription_id = p.transcription_id AND p.deleted_at IS NULL
LEFT JOIN email_messages e ON a.id = e.activity_id
WHERE a.actual_start_time > '2024-01-01 00:00:00'
AND a.opportunity_id IN (4353519)
AND a.status IN ('completed', 'received', 'delivered')
AND a.deleted_at IS NULL
AND a.type NOT IN ('sms-inbound', 'sms-outbound')
ORDER BY a.opportunity_id ASC, a.id ASC;
SELECT * FROM users WHERE name LIKE '%George Fierstone%'; # 14293
SELECT * FROM teams WHERE id = 442;
SELECT * FROM crm_configurations WHERE id = 344;
select * from team_features where team_id = 442;
select * from groups where team_id = 442;
select * from playbooks where team_id = 442;
select * from playbook_categories where playbook_id = 1729;
select * from crm_fields where crm_configuration_id = 344 and id = 172024;
SELECT * FROM crm_field_values WHERE crm_field_id = 172024;
select * from crm_layouts where crm_configuration_id = 344;
select * from playbook_layouts where playbook_id = 1729;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 221, 9444
select s.*
# , s.sent_at, u.name, a.*
from activity_summary_logs s
inner join activities a on a.id = s.activity_id
inner join users u on u.id = a.user_id
where a.crm_configuration_id = 356
and s.sent_at > date_sub(now(), interval 60 day)
order by a.actual_end_time desc;
select * from activities a
# inner join activity_summary_logs s on s.activity_id = a.id
where a.crm_configuration_id = 356 and a.actual_end_time > date_sub(now(), interval 60 day)
# and a.crm_provider_id is not null
# and provider <> 'ringcentral'
and status = 'completed'
order by a.actual_end_time desc;
select * from teams order by id desc; # 17328, 32, 17830, [EMAIL]
SELECT * FROM users;
SELECT * FROM users where team_id = 260 and status = 1; # 201 - 150 active
SELECT * FROM teams WHERE id = 260;
select * from team_settings where team_id = 260;
select * from crm_configurations where team_id = 260;
SELECT * FROM crm_layouts WHERE crm_configuration_id = 356;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1184;
select * from accounts where crm_configuration_id = 221 order by id desc; # 7000
select * from leads where crm_configuration_id = 221 order by id desc; # 0
select * from contacts where crm_configuration_id = 221 order by id desc; # 200 000
select * from opportunities where crm_configuration_id = 221 order by id desc; # 0
select * from crm_profiles where crm_configuration_id = 221 order by id desc; # 23
select * from crm_fields where crm_configuration_id = 221;
select * from crm_field_values where crm_field_id = 5302 order by id desc;
select * from crm_layouts where crm_configuration_id = 221 order by id desc;
select * from stages where crm_configuration_id = 221 order by id desc;
select * from accounts where crm_configuration_id = 356 order by id desc; # 7000
select * from leads where crm_configuration_id = 356 order by id desc; # 0
select * from contacts where crm_configuration_id = 356 order by id desc; # 200 000
select * from opportunities where crm_configuration_id = 356 order by id desc; # 0
select * from crm_profiles where crm_configuration_id = 356 order by id desc; # 23
select * from crm_fields where crm_configuration_id = 356;
select * from crm_field_values where crm_field_id = 5302 order by id desc;
select * from crm_layouts where crm_configuration_id = 356 order by id desc;
select * from stages where crm_configuration_id = 356 order by id desc;
select * from playbooks where team_id = 260 order by id desc; # 4 (2 deleted)
select * from groups where team_id = 260 order by id desc; # 27 groups, (2 deleted)
select * from playbook_layouts where playbook_id IN (1410,1409,1276,1254); # 4
select ce.* from calendars c
join users u on c.user_id = u.id
join calendar_events ce on c.id = ce.calendar_id
where u.team_id = 260
and (ce.start_time > '2025-02-21 00:00:00')
;
# calendar events 1207
#
select * from opportunities where team_id = 260;
SELECT * FROM crm_field_data WHERE object_id = 4696496;
select * from activities where crm_configuration_id = 356 and crm_provider_id IS NOT NULL;
select * from activities where crm_configuration_id IN (221) and provider NOT IN ('ms-teams', 'uploader', 'zoom-bot')
# and type = 'conference' and status = 'scheduled' and activities.is_internal = 0
and created_at > '2024-03-01 00:00:00'
order by id desc; # 880 000, ringcentral, avaya
SELECT * FROM participants WHERE activity_id = 26371744;
# all activities 942 000 +
# conference 7385 - scheduled 984 - external 343
select * from activities where id = 26321812;
select * from participants where activity_id = 26321812;
select * from participants where activity_id in (26414510,26414514,26414516,26414604,26414653,26414655);
select * from leads where id in (720428,689175,731546,645866,621037);
select * from users where id = 13841;
select * from opportunities where user_id = 9541;
select * from stages where id = 15900;
select * from accounts where
# id IN (4160055,5053725,4965303,4896434)
id in (4584518,3249934,3218025,3891133,3399450,4172999,4485161,3101785,4587203,3070816,2870343,2870341,3563940,4550846,3424464,3249963,2870342)
;
select * from activities where id = 26654935;
SELECT * FROM opportunities WHERE id = 4803458;
SELECT * FROM opportunities where team_id = 260 and user_id = 13841 AND stage_id = 15900;
SELECT id, uuid, provider, type, lead_id, account_id, contact_id, opportunity_id, stage_id, status, recording_state, title, actual_start_time, actual_end_time
FROM activities WHERE user_id = 13841 AND opportunity_id IN (4729783, 4731717, 4731726, 4732064, 4732849, 4803458, 4813213);
SELECT DISTINCT
o.id, o.stage_id, s.name, a.title,
a.*
FROM activities a
# INNER JOIN tracks t ON a.id = t.activity_id
INNER JOIN users u ON a.user_id = u.id
INNER JOIN teams team ON u.team_id = team.id
INNER JOIN groups g ON u.group_id = g.id
INNER JOIN opportunities o ON a.opportunity_id = o.id
INNER JOIN stages s ON o.stage_id = s.id
WHERE
a.crm_configuration_id = 356
AND a.status IN ('completed', 'failed')
AND a.recording_state != 'stopped'
# and a.user_id = 13841
AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')
AND team.uuid = uuid_to_bin('a607fba7-452e-4683-b2af-00d6cb52c93c')
AND g.uuid = uuid_to_bin('b5d69e40-24a0-4c16-810b-5fa462299f94')
AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')
# AND t.type IN ('audio', 'video')
AND (
(a.actual_start_time BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59')
OR
(
a.actual_start_time IS NULL
AND a.type IN ('sms-outbound', 'sms-inbound')
AND a.created_at BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59'
)
)
AND (
a.is_private = 0
OR (
a.is_private = 1
AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')
)
)
AND (
# s.id = 15900
s.uuid = uuid_to_bin('04ca1c26-c666-4268-a129-419c0acffd73')
OR s.uuid IS NULL -- Include records without opportunity stage
)
ORDER BY a.actual_end_time DESC;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lead Forensics%'; # 190, 162, 8474, [EMAIL]
SELECT * FROM users WHERE team_id = 190;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 190
and sa.provider = 'hubspot';
select * from role_user where user_id = 8474;
select * from crm_configurations where provider = 'bullhorn';
SELECT * FROM opportunities WHERE uuid_to_bin('94578249-65ec-4205-90f2-7d1a7d5ab64a') = uuid;
SELECT * FROM users WHERE uuid_to_bin('26dbadeb-926f-4150-b11b-771b9d4c2f9a') = uuid;
SELECT * FROM opportunities ...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"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,"bounds":{"left":0.36635637,"top":0.17478053,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","depth":4,"bounds":{"left":0.37632978,"top":0.17478053,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.3879654,"top":0.17318435,"width":0.00731383,"height":0.018355945},"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.39527926,"top":0.17318435,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.4039229,"top":0.09896249,"width":0.008643617,"height":0.01915403},"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.41256648,"top":0.09896249,"width":0.008643617,"height":0.01915403},"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,"bounds":{"left":0.42353722,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"bounds":{"left":0.43218085,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"bounds":{"left":0.44082448,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"bounds":{"left":0.45179522,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"bounds":{"left":0.46276596,"top":0.09896249,"width":0.024268618,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"bounds":{"left":0.4893617,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"bounds":{"left":0.5003325,"top":0.09896249,"width":0.029587766,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.64261967,"top":0.09896249,"width":0.02825798,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"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":"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":"AXStaticText","text":"31","depth":4,"bounds":{"left":0.60039896,"top":0.123703115,"width":0.009640957,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"9","depth":4,"bounds":{"left":0.61203456,"top":0.123703115,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"29","depth":4,"bounds":{"left":0.62200797,"top":0.123703115,"width":0.010305851,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.6343085,"top":0.123703115,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"109","depth":4,"bounds":{"left":0.6442819,"top":0.123703115,"width":0.011968086,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.65791225,"top":0.12210695,"width":0.00731383,"height":0.018355945},"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.66522604,"top":0.12210695,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT * FROM team_features where team_id = 1;\n\nSELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922\nSELECT * FROM users WHERE team_id = 340; # 12015\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 340\nand sa.provider = 'salesforce';\n# and sa.provider = 'salesloft';\n\nselect * from crm_fields where crm_configuration_id = 270 and object_type = 'event';\n# 125558 - Event Type - Event_Type__c\n# 125552 - Event Status - Event_Status__c\n\nSELECT * FROM sidekick_settings WHERE team_id = 340;\n\nSELECT * FROM crm_field_values WHERE crm_field_id in (125552);\n\nselect * from activities where crm_configuration_id = 270\nand type = 'conference' and crm_provider_id IS NOT NULL\nand actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;\n\nSELECT * FROM activities WHERE id = 20871677;\nSELECT * FROM crm_field_data WHERE activity_id = 20871677;\n\nselect * from crm_layouts where crm_configuration_id = 270;\nselect * from crm_layout_entities where crm_layout_id in (886,887);\n\nSELECT * FROM crm_configurations WHERE id = 270;\n\nselect * from playbooks where team_id = 340; # 1514\nselect * from groups where team_id = 340;\nSELECT * FROM crm_fields WHERE id IN (125393, 125401);\n\nselect g.name as 'team name', p.name as 'playbook name', f.label as 'activity type field' from groups g\njoin playbooks p on g.playbook_id = p.id\njoin crm_fields f on p.activity_field_id = f.id\nwhere g.team_id = 340;\n\nSELECT * FROM activities WHERE uuid_to_bin('0c180357-67d2-419e-a8c3-b832a3490770') = uuid; # 20448716\nselect * from crm_field_data where object_id = 20448716;\n\nselect * from activities where crm_configuration_id = 270 and provider = 'salesloft' order by id desc;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%CybSafe%'; # 343,273,12008\nselect * from opportunities where team_id = 343;\nselect * from opportunities where team_id = 343 and crm_provider_id = '18099102526';\nselect * from opportunities where team_id = 343 and account_id = 945217482;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nselect * from accounts where team_id = 343 order by name asc;\n\nselect * from stages where crm_configuration_id = 273 and type = 'opportunity';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Voyado%'; # 353,283,12143\nSELECT * FROM activities WHERE crm_configuration_id = 283 and account_id = 3777844 order by id desc;\nSELECT * FROM accounts WHERE team_id = 353 AND name LIKE '%Salesloft%';\nSELECT * FROM activities WHERE id = 20717903;\n\nselect * from participants where activity_id IN (20929172,20928605,20928468,20926272,20926271,20926270,20926269,20916499,20916454,20916436,20916435,20900015,20900014,20900013,20897312,20897243,20897241,20897237,20897232,20897229,20893648,20893231,20893230,20893229,20893228,20889784,20885039,20885038,20885037,20885036,20885035,20882728,20882708,20882703,20882702,20869828,20869811,20869806,20869801,20869799,20869798,20869796,20869795,20869794,20869761,20869760,20869759,20868688,20868687,20850340,20847195,20841710,20833967,20827021,20825307,20825305,20825297,20824615,20824400,20823927,20821760,20795588,20794233,20794057,20793710,20785811,20781789,20781394,20781307,20762651,20758453,20758282,20757323,20756643,20756636,20756629,20756627,20756606,20756605,20756604,20756603,20756602,20756600,20756599,20756598,20756595,20756594,20756589,20756587,20756577,20756573,20748918,20748386,20748385,20748384,20748383,20748382,20748381,20748380,20748379,20748377,20748375,20748373,20743301,20717905,20717904,20717903,20717901,20717899);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 353\nand sa.provider = 'salesforce';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%modern world business solutions%'; # 345,275,12016, l.atkinson@mwbsolutions.co.uk\nSELECT * FROM activities WHERE uuid_to_bin('3921d399-3fef-4609-a291-b0097a166d43') = uuid;\n# id: 20940638, user: 12022, contact: 5305871\nSELECT * FROM activity_summary_logs WHERE activity_id = 20940638;\nselect * from contacts where team_id = 345 and crm_provider_id = '30891432415' order by name asc; # 5305871\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 345\nand sa.provider = 'hubspot';\n\nselect * from users where team_id = 345 and id = 12022;\nSELECT * FROM crm_profiles WHERE user_id = 12022;\nSELECT * FROM participants WHERE activity_id = 20940638;\nSELECT * FROM users u\nJOIN crm_profiles cp ON u.id = cp.user_id\nWHERE u.team_id = 345;\n\nselect * from contacts where team_id = 345 and crm_provider_id = '30880813535' order by name desc; # 5305871\n\nselect * from team_features where team_id = 345;\nSELECT * FROM activities WHERE uuid_to_bin('11701e2d-2f82-4dab-a616-1db4fad238df') = uuid; # 21115197\nSELECT * FROM participants WHERE activity_id = 20897406;\n\n\n\nSELECT * FROM activities WHERE uuid_to_bin('63ba55cd-1abc-447d-83da-0137000005b7') = uuid; # 20953912\nSELECT * FROM activities WHERE crm_configuration_id = 275 and provider = 'ringcentral' and title like '%1252629100%';\n\n\nSELECT * FROM activities WHERE id = 20946641;\nSELECT * FROM crm_profiles WHERE user_id = 10211;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120,97,10984, triger@lunio.ai\nSELECT * FROM opportunities WHERE crm_configuration_id = 97 and crm_provider_id = '006N1000006c5PpIAI';\nselect * from stages where crm_configuration_id = 97 and type = 'opportunity';\nselect * from opportunities where team_id = 120;\n\n\nselect * from crm_configurations crm join teams t on crm.id = t.crm_id\nwhere 1=1\nAND t.current_billing_plan IS NOT NULL\nAND crm.auto_sync_activity = 0\nand crm.provider = 'hubspot';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Exclaimer%'; # 270,205,10053,james.lewendon@exclaimer.com\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 270\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('b54df794-2a9a-4957-8d80-09a600ead5f8') = uuid; # 21637956\nSELECT * FROM crm_profiles WHERE user_id = 11446;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Cygnetise%'; # 372,300,12554, alex.chikly@cygnetise.com\nselect * from playbooks where team_id = 372;\nselect * from crm_fields where crm_configuration_id = 300 and object_type = 'event'; # 141340\nSELECT * FROM crm_field_values WHERE crm_field_id = 141340;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 372\nand sa.provider = 'salesforce';\n\nselect * from crm_profiles where crm_configuration_id = 300;\nSELECT * FROM crm_configurations WHERE team_id = 372;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Planday%'; # 291,242,11501,mfa@planday.com\nSELECT * FROM opportunities WHERE team_id = 291 and crm_provider_id = '006bG000005DO86QAG'; # 3207756\nselect * from crm_field_data where object_id = 3207756;\nSELECT * FROM crm_fields WHERE id = 111834;\n\nselect f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value\nFROM crm_fields f\nJOIN crm_field_data fd ON f.id = fd.crm_field_id\nWHERE f.crm_configuration_id = 242\nAND f.object_type = 'opportunity'\nAND fd.object_id IN (3207756)\nORDER BY fd.object_id, fd.updated_at;\n\nSELECT * FROM crm_configurations WHERE auto_connect = 1;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150,salesforce-admin@tourlane.com\nselect * from group_deal_risk_types drgt join groups g on drgt.group_id = g.id\nwhere g.team_id = 187;\n\nselect * from `groups` where team_id = 187;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 187\nand sa.provider = 'salesforce';\n\n# Destination - 98870 - Destination__c\n# Stage - 79014 - StageName\n# Land Arrangement - 98856 - Land_Arrangement__c\n# Flight - 98848 - Flight__c\n# Last activity date - 98812 - LastActivityDate\n# Last modified date - 98809 - LastModifiedDate\n# Last inbound mail timestamp - 99151 - Last_Inbound_Mail_Timestamp__c\n# next call - 98864 - Next_Call__c\n\nselect * from crm_fields where crm_configuration_id = 209 and object_type = 'opportunity';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 209;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;\n\nselect * from opportunities where team_id = 187 and name LIKE'%Muriel Sal%';\nselect * from opportunities where team_id = 187 and user_id = 9951 and is_closed = 0;\nselect * from activities where opportunity_id = 3538248;\n\nSELECT * FROM crm_profiles WHERE user_id = 8150;\n\nselect * from deal_risks where opportunity_id = 3538248;\n\nselect * from teams where crm_id IS NULL;\n\nSELECT opp.id AS opportunity_id,\n u.group_id AS group_id,\n MAX(\n CASE\n WHEN a.type IN (\"sms-inbound\", \"sms-outbound\") THEN a.created_at\n ELSE a.actual_end_time\n END) as last_date\nFROM opportunities opp\nleft join activities a on a.opportunity_id = opp.id\ninner join users u on opp.user_id = u.id\nwhere opp.user_id IN (9951)\n\nAND opp.is_closed = 0\nand a.status IN ('completed', 'received', 'delivered') OR a.status IS NULL\ngroup by opp.id;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Cybsafe%'; # 343,301,12008,polly.morphew@cybsafe.com\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 301;\nSELECT * FROM contacts WHERE id = 6612363;\nSELECT * FROM accounts WHERE id = 4235676;\nSELECT * FROM opportunities WHERE crm_configuration_id = 301 and crm_provider_id = 32983784868;\nselect * from opportunity_stages where opportunity_id = 4503759;\n# SELECT * FROM opportunities WHERE id = 4569937;\n\nselect * from activities where crm_configuration_id = 301;\nSELECT * FROM activities WHERE uuid_to_bin('d3b2b28b-c3d0-4c2d-8ed0-eef42855278a') = uuid; # 26330370\nSELECT * FROM participants WHERE activity_id = 26330370;\n\nSELECT * FROM teams WHERE id = 375;\nselect * from playbooks where team_id = 375;\n\nselect * from stages where crm_configuration_id = 301 and type = 'opportunity';\n\nselect * from teams;\nselect * from contact_roles;\n\nSELECT * FROM opportunities WHERE team_id = 343 and user_id = 12871 and close_date >= '2024-11-01';\n\nselect * from users u join crm_profiles cp on cp.user_id = u.id where u.team_id = 343;\n\nSELECT * FROM crm_field_data WHERE object_id = 3771706;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_fields WHERE crm_configuration_id = 301 and object_type = 'opportunity'\nand crm_provider_id LIKE \"%traffic_light%\";\nSELECT * FROM crm_field_values WHERE crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531);\n\nSELECT fd.* FROM opportunities o\nJOIN crm_field_data fd ON o.id = fd.object_id\nWHERE o.team_id = 343\n# and o.user_id IS NOT NULL\nand fd.crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531)\nand fd.value != ''\norder by value desc\n# group by o.id\n;\n\nSELECT * FROM opportunities WHERE id = 3769843;\n\nSELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150, salesforce-admin@tourlane.com\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 209;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Funding Circle%'; # 220,177,8603,aswini.mishra@fundingcircle.com\nSELECT * FROM activities WHERE uuid_to_bin('7a40e99b-3b37-4bb1-b983-325b81801c01') = uuid; # 23139839\n\n\nSELECT * FROM opportunities WHERE id = 3855992;\n\nSELECT * FROM users WHERE name LIKE '%Angus Pollard%'; # 8988\n\nSELECT * FROM teams WHERE name LIKE '%Story Terrace%'; # 379, 307, 12894\nSELECT * FROM crm_fields WHERE crm_configuration_id = 307 and object_type != 'opportunity';\n\nselect * from contacts where team_id = 379 and name like '%bebro%'; # 5874411, crm: 77229348507\nSELECT * FROM crm_field_data WHERE object_id = 5874411;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 379\nand sa.provider = 'hubspot';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%mentio%'; # 117, 94, 6371, nikhil.kumar@mention-me.com\nSELECT * FROM activities WHERE uuid_to_bin('82939311-1af0-4506-8546-21e8d1fdf2c1') = uuid;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, salesforce-admin@tourlane.com\nSELECT * FROM opportunities WHERE team_id = 187 and crm_provider_id = '006Se000008xfvNIAQ'; # 3537793\nselect * from generic_ai_prompts where subject_id = 3537793;\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120, 97, 10984, triger@lunio.ai\nSELECT * FROM crm_configurations WHERE id = 97;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 97;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 355;\nSELECT * FROM crm_fields WHERE id = 32682;\n\nselect cfd.value, o.* from opportunities o\njoin crm_field_data cfd on o.id = cfd.object_id and cfd.crm_field_id = 32682\nwhere team_id = 120\nand cfd.value != ''\n;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 120\nand sa.provider = 'salesforce';\n\nselect * from opportunities where team_id = 120 and crm_provider_id = '006N1000007X8MAIA0';\nSELECT * FROM crm_field_data WHERE object_id = 2313439;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE id = 410;\nSELECT * FROM teams WHERE name LIKE '%Local Business Oxford%';\nselect * from scorecards where team_id = 410;\nselect * from scorecard_rules;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Funding%'; # 220, 177, 8603, aswini.mishra@fundingcircle.com\nselect * from activities a\njoin opportunities o on a.opportunity_id = o.id\njoin users u on o.user_id = u.id\nwhere a.crm_configuration_id = 177 and a.type LIKE '%email-out%'\n# and a.actual_end_time > '2024-12-16 00:00:00'\n# and o.remotely_created_at > '2024-12-01 00:00:00'\n# and u.group_id = 1014\nand u.id = 9021\norder by a.id desc;\nSELECT * FROM opportunities WHERE id in (3981384,4017346);\nSELECT * FROM users WHERE team_id = 220 and id IN (8775, 11435);\n\nselect * from users where id = 9021;\nselect * from inboxes where user_id = 9021;\n\nselect * from inbox_emails where inbox_id = 1349 and email_date > '2024-12-18 00:00:00';\n\nselect * from email_messages where team_id = 220\nand orig_date > '2024-12-16 00:00:00' and orig_date < '2024-12-19 00:00:00'\nand subject LIKE '%Personal%'\n# and 'from' = 'credit@fundingcircle.com'\n;\n\nselect * from activities a\njoin opportunities o on a.opportunity_id = o.id\nwhere a.user_id = 9021 and a.type LIKE '%email-out%'\nand a.actual_end_time > '2024-12-18 00:00:00'\nand o.user_id IS NOT NULL\nand o.remotely_created_at > '2024-12-01 00:00:00'\norder by a.id desc;\n\nSELECT * FROM opportunities WHERE team_id = 220 and name LIKE '%Right Car move Limited%' and id = 3966852;\nselect * from activities where crm_configuration_id = 177 and type LIKE '%email%' and opportunity_id = 3966852 order by id desc;\n\nselect * from team_settings where name IN ('useCloseDate');\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Hurree%'; # 104, 81, 6175, jfarrell@hurree.co\nSELECT * FROM opportunities WHERE team_id = 104 and name = 'PropOp';\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 104\nand sa.provider = 'hubspot';\n\nselect * from crm_configurations where last_synced_at > '2025-01-19 01:00:00'\nselect * from teams where crm_id IS NULL;\n\nselect t.name as 'team', u.name as 'owner', u.email, u.phone\nfrom teams t\njoin activity_providers ap on t.id = ap.team_id\njoin users u on t.owner_id = u.id\nwhere 1=1\n and t.status = 'active'\n and ap.is_enabled = 1\n# and u.status = 1\n and ap.provider = 'ms-teams';\n\nselect * from crm_configurations where provider = 'bullhorn'; # 344\nSELECT * FROM teams WHERE id = 442; # 14293\nselect * from users where team_id = 442;\nselect * from social_accounts sa where sa.sociable_id = 14293;\nselect * from invitations where team_id = 442;\n\n# ********************************************************************************************************\nSELECT * FROM users WHERE email LIKE '%nea.liikamaa@eletive.com%'; # 14022\nSELECT * FROM teams WHERE id = 429;\nselect * from opportunities where team_id = 429 and crm_provider_id IN (16157415775, 22246219645);\nselect * from activities where opportunity_id in (4340436,4353519);\n\nselect * from transcription where activity_id IN (25630961,25381771);\nselect * from generic_ai_prompts where subject_id IN (4353519);\n\nSELECT\n a.id as activity_id,\n a.opportunity_id,\n a.type as activity_type,\n a.language,\n CONCAT(a.title, a.description) AS mail_content,\n e.from AS mail_from,\n e.to AS mail_to,\n e.subject AS mail_subject,\n e.body AS mail_body,\n p.type as prompt_type,\n p.status as prompt_status,\n p.content AS prompt_content,\n a.actual_start_time as created_at\nFROM activities a\n LEFT JOIN ai_prompts p ON a.transcription_id = p.transcription_id AND p.deleted_at IS NULL\n LEFT JOIN email_messages e ON a.id = e.activity_id\nWHERE a.actual_start_time > '2024-01-01 00:00:00'\n AND a.opportunity_id IN (4353519)\n AND a.status IN ('completed', 'received', 'delivered')\n AND a.deleted_at IS NULL\n AND a.type NOT IN ('sms-inbound', 'sms-outbound')\nORDER BY a.opportunity_id ASC, a.id ASC;\n\nSELECT * FROM users WHERE name LIKE '%George Fierstone%'; # 14293\nSELECT * FROM teams WHERE id = 442;\nSELECT * FROM crm_configurations WHERE id = 344;\nselect * from team_features where team_id = 442;\nselect * from groups where team_id = 442;\nselect * from playbooks where team_id = 442;\nselect * from playbook_categories where playbook_id = 1729;\nselect * from crm_fields where crm_configuration_id = 344 and id = 172024;\nSELECT * FROM crm_field_values WHERE crm_field_id = 172024;\nselect * from crm_layouts where crm_configuration_id = 344;\nselect * from playbook_layouts where playbook_id = 1729;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 221, 9444\n\nselect s.*\n# , s.sent_at, u.name, a.*\nfrom activity_summary_logs s\ninner join activities a on a.id = s.activity_id\ninner join users u on u.id = a.user_id\nwhere a.crm_configuration_id = 356\nand s.sent_at > date_sub(now(), interval 60 day)\norder by a.actual_end_time desc;\n\nselect * from activities a\n# inner join activity_summary_logs s on s.activity_id = a.id\nwhere a.crm_configuration_id = 356 and a.actual_end_time > date_sub(now(), interval 60 day)\n# and a.crm_provider_id is not null\n# and provider <> 'ringcentral'\nand status = 'completed'\norder by a.actual_end_time desc;\n\nselect * from teams order by id desc; # 17328, 32, 17830, integration-account@jiminny.com\nSELECT * FROM users;\nSELECT * FROM users where team_id = 260 and status = 1; # 201 - 150 active\nSELECT * FROM teams WHERE id = 260;\nselect * from team_settings where team_id = 260;\nselect * from crm_configurations where team_id = 260;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 356;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1184;\n\nselect * from accounts where crm_configuration_id = 221 order by id desc; # 7000\nselect * from leads where crm_configuration_id = 221 order by id desc; # 0\nselect * from contacts where crm_configuration_id = 221 order by id desc; # 200 000\nselect * from opportunities where crm_configuration_id = 221 order by id desc; # 0\nselect * from crm_profiles where crm_configuration_id = 221 order by id desc; # 23\nselect * from crm_fields where crm_configuration_id = 221;\nselect * from crm_field_values where crm_field_id = 5302 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 221 order by id desc;\nselect * from stages where crm_configuration_id = 221 order by id desc;\n\nselect * from accounts where crm_configuration_id = 356 order by id desc; # 7000\nselect * from leads where crm_configuration_id = 356 order by id desc; # 0\nselect * from contacts where crm_configuration_id = 356 order by id desc; # 200 000\nselect * from opportunities where crm_configuration_id = 356 order by id desc; # 0\nselect * from crm_profiles where crm_configuration_id = 356 order by id desc; # 23\nselect * from crm_fields where crm_configuration_id = 356;\nselect * from crm_field_values where crm_field_id = 5302 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 356 order by id desc;\nselect * from stages where crm_configuration_id = 356 order by id desc;\n\nselect * from playbooks where team_id = 260 order by id desc; # 4 (2 deleted)\nselect * from groups where team_id = 260 order by id desc; # 27 groups, (2 deleted)\nselect * from playbook_layouts where playbook_id IN (1410,1409,1276,1254); # 4\nselect ce.* from calendars c\njoin users u on c.user_id = u.id\njoin calendar_events ce on c.id = ce.calendar_id\nwhere u.team_id = 260\nand (ce.start_time > '2025-02-21 00:00:00')\n;\n# calendar events 1207\n#\n\nselect * from opportunities where team_id = 260;\nSELECT * FROM crm_field_data WHERE object_id = 4696496;\n\nselect * from activities where crm_configuration_id = 356 and crm_provider_id IS NOT NULL;\nselect * from activities where crm_configuration_id IN (221) and provider NOT IN ('ms-teams', 'uploader', 'zoom-bot')\n# and type = 'conference' and status = 'scheduled' and activities.is_internal = 0\nand created_at > '2024-03-01 00:00:00'\norder by id desc; # 880 000, ringcentral, avaya\nSELECT * FROM participants WHERE activity_id = 26371744;\n\n# all activities 942 000 +\n# conference 7385 - scheduled 984 - external 343\n\nselect * from activities where id = 26321812;\nselect * from participants where activity_id = 26321812;\nselect * from participants where activity_id in (26414510,26414514,26414516,26414604,26414653,26414655);\nselect * from leads where id in (720428,689175,731546,645866,621037);\n\nselect * from users where id = 13841;\nselect * from opportunities where user_id = 9541;\nselect * from stages where id = 15900;\n\nselect * from accounts where\n# id IN (4160055,5053725,4965303,4896434)\nid in (4584518,3249934,3218025,3891133,3399450,4172999,4485161,3101785,4587203,3070816,2870343,2870341,3563940,4550846,3424464,3249963,2870342)\n;\n\nselect * from activities where id = 26654935;\nSELECT * FROM opportunities WHERE id = 4803458;\n\nSELECT * FROM opportunities where team_id = 260 and user_id = 13841 AND stage_id = 15900;\nSELECT id, uuid, provider, type, lead_id, account_id, contact_id, opportunity_id, stage_id, status, recording_state, title, actual_start_time, actual_end_time\nFROM activities WHERE user_id = 13841 AND opportunity_id IN (4729783, 4731717, 4731726, 4732064, 4732849, 4803458, 4813213);\n\nSELECT DISTINCT\n o.id, o.stage_id, s.name, a.title,\n a.*\nFROM activities a\n# INNER JOIN tracks t ON a.id = t.activity_id\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams team ON u.team_id = team.id\nINNER JOIN groups g ON u.group_id = g.id\nINNER JOIN opportunities o ON a.opportunity_id = o.id\nINNER JOIN stages s ON o.stage_id = s.id\nWHERE\n a.crm_configuration_id = 356\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n# and a.user_id = 13841\n AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')\n AND team.uuid = uuid_to_bin('a607fba7-452e-4683-b2af-00d6cb52c93c')\n AND g.uuid = uuid_to_bin('b5d69e40-24a0-4c16-810b-5fa462299f94')\n\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND t.type IN ('audio', 'video')\n AND (\n (a.actual_start_time BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59')\n OR\n (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59'\n )\n )\n AND (\n a.is_private = 0\n OR (\n a.is_private = 1\n AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')\n )\n )\n AND (\n# s.id = 15900\n s.uuid = uuid_to_bin('04ca1c26-c666-4268-a129-419c0acffd73')\n OR s.uuid IS NULL -- Include records without opportunity stage\n )\n\nORDER BY a.actual_end_time DESC;\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lead Forensics%'; # 190, 162, 8474, willsc@leadforensics.com\nSELECT * FROM users WHERE team_id = 190;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 190\nand sa.provider = 'hubspot';\n\nselect * from role_user where user_id = 8474;\n\nselect * from crm_configurations where provider = 'bullhorn';\n\nSELECT * FROM opportunities WHERE uuid_to_bin('94578249-65ec-4205-90f2-7d1a7d5ab64a') = uuid;\nSELECT * FROM users WHERE uuid_to_bin('26dbadeb-926f-4150-b11b-771b9d4c2f9a') = uuid;\n\nSELECT * FROM opportunities WHERE id = 4732493;\nselect * from activities where opportunity_id = 4732493;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE id = 443; # 358, 14315, andrea.romano@correrenaturale.com\nSELECT * FROM opportunities WHERE team_id = 443;\n\nSELECT a.id, a.type, a.user_id, a.status, a.deleted_at, u.name, u.email, u.team_id as activity_team_id, u.status, u.deleted_at, t.name, t.status, s.team_id as stage_team_id\nFROM activities AS a\nJOIN stages AS s ON a.stage_id = s.id\nJOIN users AS u ON u.id = a.user_id\nJOIN teams AS t ON t.id = s.team_id\nWHERE u.team_id <> s.team_id and t.id > 135;\n\n\nSELECT\n crm_configuration_id,\n crm_provider_id,\n COUNT(*) as duplicate_count,\n GROUP_CONCAT(id) as stage_ids,\n GROUP_CONCAT(name) as stage_names\nFROM stages\nGROUP BY crm_configuration_id, crm_provider_id\nHAVING COUNT(*) > 1\nORDER BY duplicate_count DESC;\n\nselect * from stages where id IN (14898,14907);\n\nselect * from business_processes;\n\nSELECT *\nFROM crm_configurations\nWHERE team_id IN (\n SELECT team_id\n FROM crm_configurations\n GROUP BY team_id\n HAVING COUNT(*) > 1\n)\nORDER BY team_id;\n\nSELECT *\nFROM teams\nWHERE crm_id IN (\n SELECT crm_id\n FROM teams\n GROUP BY crm_id\n HAVING COUNT(*) > 1\n)\nORDER BY crm_id;\n\n# ***************************************************************************\nselect * from crm_configurations where provider = 'integration-app';\nSELECT * FROM teams WHERE id = 443; # Correre Naturale 358 14315 andrea.romano@correrenaturale.com\nselect * from activities where crm_configuration_id = 358 order by actual_end_time desc;\nselect id, uuid, actual_end_time, crm_provider_id, is_internal, playbook_category_id, type, user_id, lead_id, contact_id, account_id, opportunity_id, status, title from activities where crm_configuration_id = 358 order by actual_end_time desc;\nselect * from team_features where team_id = 358;\nselect * from activity_summary_logs;\n\nselect * from teams where id = 406;\n\n# ************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Sportfive%'; # 267, 202, 14637, srv.salesforce@sportfive.com\nselect * from activities where crm_configuration_id = 202 order by actual_end_time desc;\n\nSELECT * FROM users where id = 14637;\nSELECT * FROM teams where id = 267;\nSELECT * FROM groups where id = 1118;\n\nselect g.name, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\ninner join groups g on g.id = u.group_id\nwhere a.crm_configuration_id = 202\nand a.is_internal = 0\nand (a.scheduled_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type = 'conference'\nand a.status != 'completed'\nand a.external_id is not null\norder by a.scheduled_start_time desc;\n\nSELECT * FROM activities\nWHERE crm_configuration_id = 202\n AND status IN ('completed', 'failed')\n AND recording_state != 'stopped'\n AND type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n AND (is_private = 0 OR user_id = 14637)\n AND (\n (\n actual_start_time BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n ) OR (\n actual_start_time IS NULL\n AND type IN ('sms-outbound', 'sms-inbound')\n AND created_at BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n )\n )\n AND NOT EXISTS (\n SELECT 1\n FROM tracks\n WHERE\n tracks.activity_id = activities.id\n AND tracks.type IN ('audio', 'video')\n )\nORDER BY actual_end_time DESC;\n\nSELECT DISTINCT\n a.*\nFROM activities a\nINNER JOIN tracks t ON a.id = t.activity_id\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams team ON u.team_id = team.id\nWHERE\n a.crm_configuration_id = 202\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n# and a.user_id = 14637\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND t.type IN ('audio', 'video')\n AND (\n (a.actual_start_time BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59')\n OR\n (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n )\n )\n AND (\n a.is_private = 0\n OR (\n a.is_private = 1\n AND a.user_id = 14637\n )\n )\n\nORDER BY a.actual_end_time DESC\n;\n\nSELECT DISTINCT a.*\nFROM activities a\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams t ON u.team_id = t.id\n# INNER JOIN tracks tr ON a.id = tr.activity_id\n# INNER JOIN groups g ON u.group_id = g.id\nWHERE 1=1\n AND t.id = 267\n# AND t.uuid = uuid_to_bin('aed4927b-f1ea-499e-94c3-83762fd233e8')\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND tr.type NOT IN ('audio', 'video')\n AND (\n a.is_private = 0\n OR a.user_id = 14637\n )\n AND (\n (a.actual_start_time BETWEEN '2025-03-19 00:00:00' AND '2025-03-21 23:59:59')\n OR (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-19 00:00:00' AND '2025-03-21 23:59:59'\n )\n )\n# and NOT EXISTS (\n# SELECT 1\n# FROM tracks t\n# WHERE t.activity_id = a.id\n# AND t.type IN ('audio', 'video')\n# )\n\nORDER BY a.actual_end_time DESC;\n\nSELECT * FROM tracks WHERE activity_id = 26485995;\n\nselect a.is_private, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\nwhere a.crm_configuration_id = 202\n# and a.is_internal = 0\nand (a.actual_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type IN (\"softphone\",\"softphone-inbound\",\"conference\",\"sms-inbound\")\nand a.status IN ('completed', 'failed')\n# and a.external_id is not null\norder by a.actual_end_time desc;\n\nselect * from activities a where a.crm_configuration_id = 202\nand a.actual_start_time between '2025-03-20 00:00:00' and '2025-03-21 00:00:00'\n# AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n\nselect g.name, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\ninner join groups g on g.id = u.group_id\nwhere a.crm_configuration_id = 202\nand a.is_internal = 0\nand (a.scheduled_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type = 'conference'\nand a.status != 'completed'\nand a.external_id is not null\norder by a.scheduled_start_time desc;\n\nSELECT * FROM teams WHERE name LIKE '%Tourlane%';\nSELECT * FROM crm_fields WHERE crm_configuration_id = 209 and object_type = 'opportunity';\nSELECT * FROM crm_field_data WHERE crm_field_id = 98809;\n\nselect * from users where status = 1 AND timezone = 'MDT';\n\nselect * from opportunities where id = 3769814;\nselect * from deal_risks where opportunity_id = 3769814;\n\nselect cp.* from crm_profiles cp\njoin users u on cp.user_id = u.id\njoin crm_configurations crm on cp.crm_configuration_id = crm.id\nwhere crm.provider = 'hubspot' AND u.status = 1 AND log_notes != 'none';\n\nselect * from crm_fields where id = 154575;\n\nselect * from team_features where feature = 'SUPPORTS_SYNC_MISSING_CALL_DISPOSITIONS';\nSELECT * FROM teams WHERE id = 176; # crm 148\nselect * from activities where crm_configuration_id = 148 and provider = 'hubspot' order by id desc;\n\nselect * from activity_providers where provider = 'amazon-connect';\n\nselect * from crm_fields cf\njoin crm_configurations crm on crm.id = cf.crm_configuration_id\nwhere crm.provider = 'hubspot' and cf.object_type IN ('account', 'contact');\n\n# *********************************************************************************************\nSELECT * FROM users WHERE id IN (15415, 15418);\nSELECT * FROM groups WHERE id IN (1805,1806);\nSELECT * FROM playbooks WHERE id = 1860;\nSELECT * FROM playbook_categories WHERE id = 38634;\nSELECT * FROM crm_fields WHERE id = 189962;\n\nSELECT * FROM teams WHERE name = 'Pulsar Group'; # 472, 380, 15138 raza.gilani@vuelio.com\n\nSELECT * FROM crm_profiles WHERE user_id = 15415;\nSELECT * FROM social_accounts WHERE sociable_id = 15415 and provider = 'salesforce';\n\nselect * from sidekick_settings where team_id = 472;\n\nSELECT * FROM activities WHERE uuid_to_bin('452c58c7-b87c-4fdd-953e-d7af185e9588') = uuid; # 28617536, user: 15418\nSELECT * FROM activities WHERE uuid_to_bin('399114ee-d3a8-458c-bff5-5f654658db0a') = uuid; # 28344407, user: 15415\nSELECT * FROM activities WHERE uuid_to_bin('f0aa567f-0ab1-4bbb-96aa-37dcf184676b') = uuid; # 28580288, user: 15415\nSELECT * FROM activities WHERE uuid_to_bin('50c086b1-2770-4bca-b5ae-6bac22ec426b') = uuid; # 28566069, user: 15415\n\n# *********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%TeamTailor%'; # 109, 218, 13969, salesforce-integrations@teamtailor.com\nselect * from crm_configurations where id = 218;\nSELECT * FROM activities WHERE uuid_to_bin('e39b5857-7fdb-4f5a-951a-8d3ca69bb1b0') = uuid; # 28338765\nSELECT * FROM users WHERE id IN (13232, 13230);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\n\n0057R00000EPL5HQAX Inez Ekblad\n\n1091cb81-5ea1-4951-a0ed-f00b568f0140 Triman Kaur\n\nSELECT * FROM crm_profiles WHERE user_id IN (13232, 13230);\n\n############################################################################################\nSELECT * FROM activities WHERE uuid_to_bin('675eeaeb-5681-42db-90bc-54c07a604408') = uuid; # 28655939 00UVg00000FLvnSMAT\nSELECT * FROM crm_field_data WHERE activity_id = 28655939;\nSELECT * FROM crm_fields WHERE id IN (94491,94493,94498);\nSELECT * FROM users WHERE id = 13658;\nSELECT * FROM teams WHERE id = 109;\nSELECT * FROM crm_configurations WHERE id = 218;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Strengthscope%'; # 481, 390, 15420, katy.holden@strengthscope.comk\nSELECT * FROM stages WHERE crm_configuration_id = 390;\nselect * from business_processes where team_id = 481 and crm_configuration_id = 390;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 481\nand sa.provider = 'salesforce';\n\n\nSELECT * FROM users WHERE id = 15780; # team 462\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 462\nand sa.provider = 'hubspot';\n\n\nselect * from teams where id = 495;\nSELECT * FROM users WHERE id = 15794;\nselect * from social_accounts where sociable_id = 15794;\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Flight%'; # 427, 333, 13752\nSELECT * FROM accounts WHERE team_id = 427 and crm_provider_id = '668731000183444517';\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Group GTI%'; # 495, 407, 15794\nSELECT * FROM activities WHERE crm_configuration_id = 407\nand status = 'completed' and type = 'conference'\norder by id desc;\n\nselect ru.*, pr.*, p.* from users u join role_user ru on ru.user_id = u.id\njoin permission_role pr on pr.role_id = ru.role_id\n join permissions p on p.id = pr.permission_id\nwhere team_id = 495 and p.name IN ('dial');\n\nselect * from permission_role;\n\nselect * from activities where crm_configuration_id = 407 and status = 'completed' order by id desc;\nSELECT * FROM activities WHERE id = 29512773;\nSELECT * FROM activities WHERE id IN (29042721,28991325,29002874);\n\nSELECT al.* from activity_summary_logs al join activities a on a.id = al.activity_id\nwhere a.crm_configuration_id = 407\n# and a.id IN (29042721,28991325,29002874);\n\nSELECT * FROM users WHERE id = 15794;\nSELECT * FROM users WHERE team_id = 495;\nSELECT * FROM social_accounts WHERE sociable_id = 15794;\nSELECT * FROM opportunities WHERE team_id = 495 and name like '%OC:%';\nSELECT * FROM contacts WHERE team_id = 495;\nSELECT * FROM leads WHERE team_id = 495;\nSELECT * FROM accounts WHERE team_id = 495;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 407;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 407;\nSELECT * FROM crm_configurations WHERE id = 407;\nSELECT * FROM opportunities WHERE team_id = 495 and close_date BETWEEN '2025-06-01' AND '2025-07-01'\nand user_id IS NOT NULL and is_closed = 1 and is_won = 1;\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Hamilton Court FX LLP%'; # 249, 187, 10103\nSELECT * FROM activities WHERE uuid_to_bin('4659c2bb-9a49-484e-9327-a3d66f1e028c') = uuid; # 28951064\nSELECT * FROM crm_fields WHERE crm_configuration_id = 187 and object_type IN ('tasks', 'event');\n\n# *********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Checkstep%'; # 325, 256, 11753\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 325\nand sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('7be372e2-1916-4d79-a2f3-ca3db1346db3') = uuid; # 28611085\nSELECT * FROM activities WHERE uuid_to_bin('980f0336-840b-4185-a5a9-30cf8b0749a8') = uuid; # 28719733\nSELECT * FROM activity_summary_logs where activity_id = 28719733;\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 356, 9444\nSELECT * FROM activity_summary_logs where sent_at BETWEEN '2025-06-09 11:38:00' AND '2025-06-09 11:40:00';\nSELECT * FROM leads WHERE crm_configuration_id = 356 and crm_provider_id = '230045001502770504'; # 823630\nselect * from activities where crm_configuration_id = 356 and lead_id = 841732;\n\nSELECT * from activity_summary_logs al join activities a on a.id = al.activity_id\nwhere a.crm_configuration_id = 356;\n\nselect * from activities where crm_configuration_id = 356\nand actual_end_time between '2025-06-09 11:00:00' and '2025-06-09 12:00:00'\norder by id desc;\n\nselect * from accounts where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\nselect * from leads where crm_configuration_id = 356 and crm_provider_id = '230045001514275654' order by id desc;\nselect * from contacts where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\nselect * from opportunities where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\n\nselect * from team_features where team_id = 260;\nselect * from features where id IN (1,2,4,6,18,19,20,9,10,3,23,24,25,26,27);\n\nSELECT * FROM activities WHERE uuid_to_bin('7be372e2-1916-4d79-a2f3-ca3db1346db3') = uuid;\n\nselect * from crm_fields;\nselect * from crm_layout_entities;\n\nSELECT * FROM teams WHERE name LIKE '%Optable%';\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Teamtailor%'; # 109, 218, 13969\nSELECT * FROM crm_configurations WHERE id = 218;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('675eeaeb-5681-42db-90bc-54c07a604408') = uuid; # 28655939\nSELECT * FROM crm_field_data WHERE activity_id = 28655939;\nSELECT * FROM crm_fields WHERE id in (94491,94493,94498);\n\nselect * from teams where crm_id IS NULL;\n\nSELECT * FROM activities WHERE uuid_to_bin('71aa8a0c-9652-4ff6-bee7-d98ae60abef6') = uuid;\n\n# *************************************************************************************************\nselect * from team_domains where team_id = 399;\nSELECT * FROM teams WHERE name LIKE '%Rydoo%'; # 399, 318, 13207\n\nselect * from calendar_events where id = 5163781;\nSELECT * FROM activities WHERE uuid_to_bin('be2cbc52-7fda-46a0-9ae0-25d9553eafc0') = uuid; # 29443896\nSELECT * FROM participants WHERE activity_id = 29443896;\nselect * from contacts where crm_configuration_id = 318 and email = 'marianne.westeng@strawberry.no';\nselect * from leads where crm_configuration_id = 318 and email = 'marianne.westeng@strawberry.no';\n\nselect * from activities where user_id = 14937 order by created_at ;\n\nselect * from users where id = 14937;\n\nselect * from contacts where crm_configuration_id = 318 and email LIKE '%@strawberry.se';\nselect * from opportunities where crm_configuration_id = 318 and crm_provider_id = '006Sf00000D1WOAIA3';\n\nselect * from activities a join participants p on a.id = p.activity_id\nwhere crm_configuration_id = 318 and a.updated_at > '2025-06-23T08:18:43Z';\n\n# *************************************************************************************************\nSELECT * FROM opportunities WHERE team_id = 379 and crm_provider_id = '39334518886';\nSELECT * FROM opportunities WHERE team_id = 379 order by id desc;\nSELECT * FROM teams WHERE id = 379;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 379 and sociable_id = 13852\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations WHERE id = 307;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 307;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1027;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 307\n and id IN (144750,144855,145158,155227);\n\nSELECT * FROM activities;\n\n\nselect * from activities\nwhere created_at > '2025-07-01 00:00:00'\n# and created_at < '2025-08-01 00:00:00'\nand type not in ('email-outbound', 'email-inbound')\nand account_id is null\nand contact_id is null\nand lead_id is null\nand opportunity_id is not null\n;\nSELECT * FROM activities WHERE id IN (25344155, 25344296, 25501909, 28692187);\nSELECT * FROM crm_configurations WHERE id in (335,301,200);\n\nselect * from crm_fields where crm_configuration_id = 230 and crm_provider_id = 'Age2__c';\n\nSELECT * FROM teams WHERE name LIKE '%Resights%';\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\n\nselect * from crm_configurations where provider = 'bullhorn'; # 344\nselect * from teams where id IN (442);\n\nselect * from activities\nwhere crm_configuration_id = 177\nand provider = 'amazon-connect'\n order by id desc;\n# and source <> 'gong';\n\nselect * from activity_providers where provider = 'amazon-connect';\n\nSELECT * FROM activities WHERE uuid_to_bin('cec1993b-a7e5-4164-b74d-d680ea51d2f2') = uuid;\n\n\nselect * from crm_configurations where store_transcript = 1;\nSELECT * FROM teams WHERE id IN (80);\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Sedna%'; # 277, 213, 12594\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 277\nand sa.provider = 'salesforce';\n\nselect * from activities where crm_configuration_id = 213 and account_id = 2511502;\n\nselect * from crm_configurations where id = 213;\n\nSELECT * FROM activities WHERE uuid_to_bin('35aa790a-8569-4544-8268-66f9a4a26804') = uuid; # 33981604\nSELECT * FROM participants WHERE activity_id = 33981604;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 337 and object_type = 'task';\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 431\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('b5476c7d-19a8-491b-869d-676ea1e857b6') = uuid; # 33997223\nselect * from activity_summary_logs where activity_id = 33997223;\nselect * from activity_notes where activity_id = 33997223;\n\n# ***********************************\nSELECT * FROM teams WHERE name LIKE '%Abode%';\n\n\nselect * from features;\nselect * from teams t\nwhere t.status = 'active'\nand id NOT IN (select team_id from team_features where feature_id = 9)\n;\n\n\nselect * from playbook_layouts where playbook_id = 1725;\nSELECT * FROM activities WHERE uuid_to_bin('65cc283c-4849-49e6-927f-4c281c8fea19') = uuid; # 34297473\nselect * from teams where id = 318;\nselect * from crm_configurations where team_id = 318;\nselect * from playbooks where team_id = 318;\nSELECT * FROM crm_layouts where crm_configuration_id = 381;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1259;\nSELECT * FROM crm_fields WHERE id IN (192938,192936,192939);\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1266;\nSELECT * FROM crm_fields WHERE id IN (192980,192991,192997,192998,193064,193067);\n\nSELECT * FROM activities WHERE uuid_to_bin('a902289b-285c-48eb-9cc2-6ad6c5d938f5') = uuid; # 34297533\n\n\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 927;\nSELECT * FROM crm_fields WHERE id IN (131668,131669,131670,131671,131676,131797);\n\nSELECT * FROM teams WHERE name LIKE '%Peripass%'; # 351, 281, 12124\nselect * from crm_layouts where crm_configuration_id = 281;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 927;\nselect * from crm_fields where crm_configuration_id = 281 and id in (131668,131669,131670,131671,131676,131797);\nselect * from opportunities where crm_configuration_id = 281;\n\nSELECT * FROM activities WHERE id IN (34211315, 34130075);\nSELECT * FROM crm_field_data WHERE object_id IN (34211315, 34130075);\n\nselect cf.crm_configuration_id, cle.crm_layout_id, cle.id, cf.id from crm_field_data cfd\njoin crm_layout_entities cle on cle.id = cfd.crm_layout_entity_id\njoin crm_fields cf on cle.crm_field_id = cf.id\nwhere cf.deleted_at IS NOT NULL\nGROUP BY cle.id, cf.id;\n\nselect * from crm_layouts where id IN (355);\nselect u.email, t.crm_id, t.* from teams t\njoin users u on u.id = t.owner_id\nwhere crm_id IN (97);\n\nSELECT * FROM crm_fields WHERE id = 96492;\n\nselect * from permissions;\nselect * from permission_role where permission_id = 247;\nselect * from roles;\n\nselect * from migrations;\n# *****************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('291e3c21-11cc-4728-aee7-6e4bedf86d72') = uuid; # 34262174\nSELECT * FROM crm_configurations WHERE id = 301;\nSELECT * FROM teams WHERE id = 343;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nselect * from participants where activity_id = 34262174;\n\nselect * from contacts where crm_configuration_id = 301 and id = 6976326;\nselect * from accounts where crm_configuration_id = 301 and id IN (4647626, 4815829); # 30761335403\n\nselect * from activity_summary_logs where activity_id = 34262174;\n\nselect * from users where status = 1 AND timezone = 'EST';\n\n# ****************************************************************************\nSELECT * FROM users WHERE id = 13869;\nSELECT * FROM crm_configurations WHERE id = 320;\nSELECT * FROM teams WHERE id = 401;\n\nSELECT * FROM activities WHERE uuid_to_bin('2228c16f-10be-48d5-90d4-67385219dc01') = uuid; # 29670601\n\nSELECT * FROM accounts WHERE id = 7761483;\nSELECT * FROM opportunities WHERE id = 6051814;\n\nSELECT * FROM teams WHERE name LIKE '%Seedlegals%';\n\n;select * from opportunities where updated_at > '2025-10-11' AND crm_provider_id = '34713761166';\n\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 177;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 577;\nSELECT * FROM crm_fields WHERE id IN (68458,68459,68480,68497,68524,68530,68554,68618,68662,68781,68810,68898,68981,69049,97467);\n\nSELECT t.id, crm.id, t.name, crm.sync_objects, crm.provider, crm.last_synced_at FROM crm_configurations crm join teams t on t.crm_id = crm.id\nwhere t.status = 'active' AND crm.provider = 'hubspot' AND crm.last_synced_at < '2025-10-22 00:00:00';\n\nSELECT * FROM activities WHERE uuid_to_bin('fa09449f-cba9-496a-b8f3-865cd3c72351') = uuid;\nSELECT * FROM crm_configurations where id = 184;\nSELECT * FROM teams WHERE id = 246;\nSELECT * FROM social_accounts WHERE sociable_id = 9259 and provider = 'hubspot';\n\nSELECT * FROM users WHERE email LIKE '%rhian.old@bud.co.uk%'; # 17700\nSELECT * FROM teams WHERE id = 551;\n\nSELECT * FROM crm_configurations WHERE id = 471;\nSELECT * FROM activities WHERE crm_configuration_id = 471 and crm_provider_id IS NOT NULL;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 471;\nSELECT * FROM crm_fields WHERE id = 307260;\nSELECT * FROM crm_field_values WHERE crm_field_id = 307260;\n\nselect * from crm_layouts where crm_configuration_id = 471;\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1547;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1548;\n\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 = 551 and sa.provider = 'hubspot';\n\nSELECT * FROM teams WHERE name LIKE '%$PCS%';\n\n# ********************************************************************************************************\nselect * from crm_configurations crm\njoin teams t on t.crm_id = crm.id\nwhere t.status = 'active'\nand crm.provider = 'hubspot';\n\n# $slug = 'HUBSPOT_WEBHOOK_SYNC';\n# $team = Jiminny\\Models\\Team::find(2);\n# $feature = Feature::query()->where('slug', $slug)->first();\n# TeamFeature::query()->create(['feature_id' => $feature->getId(),'team_id' => $team->getId()]);\n\n# hubspot_webhook_metrics\n\nselect * from crm_configurations where id = 331; # 416\nSELECT * FROM teams WHERE id = 416;\nSELECT * FROM opportunities WHERE team_id = 190;\n\nSELECT * FROM teams WHERE name LIKE '%Lead Forensics%';\nSELECT sa.id,\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 = 190 and sa.provider = 'hubspot';\n\n\n\nSELECT * FROM teams WHERE name LIKE '%Rapaport%'; # 431, 337\nSELECT * FROM teams where id = 431;\nSELECT * FROM crm_configurations where team_id = 431;\nSELECT * FROM activity_providers where team_id = 431;\nSELECT * FROM activities where crm_configuration_id = 337 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\nSELECT sa.id,\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 = 431 and sa.provider = 'salesforce';\n\nSELECT * FROM teams WHERE name LIKE '%BiP%'; # 401, 320\nSELECT * FROM teams where id = 401;\nSELECT * FROM crm_configurations where team_id = 401;\nSELECT * FROM activity_providers where team_id = 401;\nSELECT * FROM activities where crm_configuration_id = 320 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\nSELECT sa.id,\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 = 401 and sa.provider = 'salesforce';\n\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 307; # 379 - Story Terrace Inc , portalId: 3921157\nSELECT * FROM contacts WHERE team_id = 379 and updated_at > '2026-01-31 11:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 379 and updated_at > '2026-02-01 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 379 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\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 = 379 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 485; # 563 - LATUS Group (ad94d501-5d09-44fd-878f-ca3a9f8865c3) , portalId: 3904501\nSELECT * FROM opportunities WHERE team_id = 563 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 563 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 338; # 432 - Formalize , portalId: 9214205\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 = 432 and sa.provider = 'hubspot';\nSELECT * FROM opportunities WHERE team_id = 432 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 432 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 436; # 519 - Moxso , portalId: 25531989\nSELECT * FROM opportunities WHERE team_id = 519 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 519 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 96; # 119 - Nourish Care , portalId: 26617984\nSELECT * FROM opportunities WHERE team_id = 119 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 119 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 331; # 416 - The National College , portalId: 7213852\nSELECT * FROM opportunities WHERE team_id = 416 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 416 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 308; # 380 - Foodles , portalId: 7723616\nSELECT * FROM opportunities WHERE team_id = 380 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 380 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 379; # 471 - imat-uve , portalId: 9177354\nSELECT * FROM opportunities WHERE team_id = 471 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 471 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 465; # 545 - Spotler , portalId: 144759271\nSELECT * FROM opportunities WHERE team_id = 545 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 545 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 455; # 537 - indevis , portalId: 25666868\nSELECT * FROM opportunities WHERE team_id = 537 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 537 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 200; # 265 - Jobadder , portalId: 6426676\nSELECT * FROM opportunities WHERE team_id = 265 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 265 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 335; # 429 - Eletive , portalId: 6110563\nSELECT * FROM opportunities WHERE team_id = 429 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 429 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 363; # 456 - Global Group , portalId: 8901981\nSELECT * FROM opportunities WHERE team_id = 456 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 456 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 297; # 369 - Unbiased , portalId: 9229005\nSELECT * FROM opportunities WHERE team_id = 369 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 369 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 353; # 449 - Fuuse , portalId: 25781745\nSELECT * FROM opportunities WHERE team_id = 449 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 449 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 487; # 566 - Nimbus , portalId: 39982590\nSELECT * FROM opportunities WHERE team_id = 566 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 566 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 487;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1630;\nselect * from crm_fields where crm_configuration_id = 487 and\n(uuid_to_bin('4c6b2971-64d4-45b8-b377-427be758b5a5') = uuid or uuid_to_bin('59e368d8-65a0-4b77-b611-db37c99fbe68') = uuid);\nSELECT * FROM crm_field_values WHERE crm_field_id = 375177;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 420; # 506 - voiio , portalId: 145629154\nSELECT * FROM opportunities WHERE team_id = 506 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 506 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 479; # 558 - Momice , portalId: 535962\nSELECT * FROM opportunities WHERE team_id = 558 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 558 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 59; # 80 - Storyclash GmbH , portalId: 4268479\nSELECT * FROM opportunities WHERE team_id = 80 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 80 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 175; # 203 - Team iAM , portalId: 5534732\nSELECT * FROM opportunities WHERE team_id = 203 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 203 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 368; # 460 - OneTouch Health , portalId: 5534732183355\nSELECT * FROM opportunities WHERE team_id = 460 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 460 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\n\n\nselect * from users where id = 29643;\nSELECT * FROM crm_field_values WHERE crm_field_id = 375177;\n# ********************************************************************\nSELECT * FROM teams WHERE name LIKE '%Buynomics%'; # 462, 482, 14910\nSELECT * FROM activities WHERE crm_configuration_id = 482\nand type NOT IN ('email-inbound', 'email-outbound')\n# and description like '%The call focused on understanding Welch%'\norder by id desc;\n\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 = 462 and sa.provider = 'salesforce';\n\nselect * from contacts where crm_configuration_id = 482 and name = 'Cyndall Hill'; # 15504749\nselect * from contacts where id = 10891096; # 482\nSELECT * FROM activities WHERE crm_configuration_id = 482\nand type NOT IN ('email-inbound', 'email-outbound')\nand contact_id = 15504749\norder by id desc;\n\nselect * from activities where id = 36793003; # 96cc7bc1-8622-4d27-92f4-baf664fc1a56, 00UOf00000PDdOXMA1\nselect * from transcription where id = 7646782;\nselect * from ai_prompts where transcription_id = 7646782;\n\n# ********************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('7a8471a3-847e-4822-802b-ddf426bbc252') = uuid; # 37370018\nSELECT * FROM activity_summary_logs WHERE activity_id = 37370018;\nSELECT * FROM teams WHERE id = 555;\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 = 555 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('7c17b8aa-09df-4f85-a0f7-51f47afd712d') = uuid; # 37395250\nSELECT * FROM activities WHERE uuid_to_bin('14d60388-260d-494b-aa0d-63fdb1c78026') = uuid; # 37395250\n\nSELECT a.* FROM activities a JOIN crm_configurations c on c.id = a.crm_configuration_id\nwhere a.type IN ('softphone', 'softphone-outbound') and c.provider = 'hubspot'\nand a.provider NOT IN ('hubspot')\n# and a.provider IN ('salesloft')\n# and c.id NOT IN (70)\n# and a.duration > 30\n# and actual_start_time > '2026-02-05 00:00:00'\norder by a.id desc;\n\nSELECT * FROM activities WHERE id = 37549787;\nSELECT * FROM crm_profiles WHERE user_id = 17613;\n\nSELECT * FROM crm_configurations WHERE id = 70;\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 = 93 and sa.provider = 'hubspot';\n\nSELECT asf.activity_search_id, asf.id, asf.value\nFROM activity_search_filters asf\nWHERE asf.filter = 'group_id'\nAND asf.value IN (\n SELECT CONCAT(\n HEX(SUBSTR(uuid, 5, 4)), '-',\n HEX(SUBSTR(uuid, 3, 2)), '-',\n HEX(SUBSTR(uuid, 1, 2)), '-',\n HEX(SUBSTR(uuid, 9, 2)), '-',\n HEX(SUBSTR(uuid, 11))\n )\n FROM groups\n WHERE deleted_at IS NOT NULL\n);\n\nSELECT * FROM crm_configurations WHERE id = 373; # KPSBremen.de 465 # - no social account\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 = 465 and sa.provider = 'hubspot';\n\nselect * from crm_configurations where id = 494;\n\nSELECT * FROM teams WHERE name LIKE '%splose%'; # 572, 495, 18708\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 = 572 and sa.provider = 'pipedrive';\n\nselect * from opportunities where team_id = 572\n# and name like '%Onebright%'\n# and is_closed = 1 and is_won = 0\n order by id desc;\n\n\nselect * from users where deleted_at is null and status = 2;\n\nselect * from contacts where id = 17900517;\nselect * from accounts where id = 10109838;\nselect * from opportunities where id = 6955880;\n\nselect * from opportunity_contacts where opportunity_id = 6955880;\nselect * from opportunity_contacts where contact_id = 17900517;\n\nselect * from contact_roles cr join crm_configurations crm on cr.crm_configuration_id = crm.id\nwhere crm.provider != 'salesforce';\n\nSELECT * FROM activities WHERE uuid_to_bin('adcb8331-5988-4353-834e-383a355abba2') = uuid; # 38056424, crm 104659682404\nselect * from teams where id = 456;\nSELECT * FROM crm_configurations WHERE id = 363;\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 = 456 and sa.provider = 'hubspot';\n\nselect * from crm_layouts where crm_configuration_id = 363;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id IN (1203, 1204, 1635);\nSELECT * FROM crm_fields WHERE id IN (181536, 181538, 213455);\n\nSELECT * FROM teams WHERE name LIKE '%Electric%'; # 342, 272, 12767\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 = 342 and sa.provider = 'pipedrive';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 and name like 'NORTHUMBRIA POL%'; # and updated_at > '2025-07-01 00:00:00';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 order by remotely_created_at asc; # and updated_at > '2025-07-01 00:00:00';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 and updated_at > '2026-01-01 00:00:00';\nSELECT * FROM crm_fields WHERE crm_configuration_id = 272 and object_type = 'opportunity';\nSELECT * FROM crm_field_values WHERE crm_field_id = 127164;\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 = 342 and sa.provider = 'pipedrive';\n\nSELECT * FROM teams WHERE id = 472;\nSELECT * FROM crm_configurations WHERE id = 380;\nselect * from activities where id = 38285673; # 38285673\nSELECT * FROM users WHERE id = 16942;\nSELECT * FROM groups WHERE id = 1964;\nSELECT * FROM playbooks WHERE id = 2033;\n\nselect * from teams where created_at > '2026-03-09';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 499; # 1065\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1678;\n\nSELECT * FROM teams WHERE id = 575;\nselect * from opportunities where team_id = 575;\n\nSELECT * FROM activities WHERE uuid_to_bin('96b1261f-2357-49f9-ab38-23ce12008ea0') = uuid;\n\nselect * from contacts c\nwhere c.crm_configuration_id = 370 order by c.updated_at desc;\n\nSELECT * FROM participants where activity_id = 38833541;\nSELECT * FROM participants where activity_id = 39216301;\nSELECT * FROM activity_summary_logs where activity_id = 39216301;\nSELECT * FROM activities WHERE uuid_to_bin('c7d99fbe-1fb1-41f2-8f4d-52e2bf70e1e9') = uuid; # 38833541, crm 478116564181\nSELECT * FROM activities WHERE uuid_to_bin('2e6ff4d3-9faa-447a-a8c1-9acde4d885ae') = uuid; # 39216301, crm 480171536586\nselect * from crm_profiles where crm_configuration_id = 319 and crm_provider_id = 525785080;\nselect * from opportunities where crm_configuration_id = 319 and crm_provider_id = 410150124747;\nselect * from accounts where crm_configuration_id = 319 and crm_provider_id = 47150650569;\nselect * from contacts where crm_configuration_id = 319 and crm_provider_id IN ('665587441856', '742723347700');\n# owner 13236 525785080\n# contact 1 16779180 665587441856 - activity - Alex Howes alex@supportroom.com created 2026-01-26\n# contact 2 19247563 742723347700 - ash@supportroom.com 2026-03-24\n# company 4176133 47150650569\n# deal 7100953 410150124747\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 = 400 and sa.provider = 'hubspot';\n\nselect * from features;\nselect * from team_features where feature_id = 40;\n\nselect * from teams where id = 556; # owner: 18101, crm: 477\nselect * from crm_configurations where id = 477;\nSELECT * FROM users WHERE id = 18101;\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 = 556 and sa.provider = 'integration-app';\n\nselect * from opportunities where id = 7594349;\nselect * from opportunity_stages where opportunity_id = 7594349 order by created_at desc;\nselect * from business_processes where id = 6024;\nselect * from business_process_stages where stage_id = 16352;\nselect * from business_process_stages where business_process_id = 6024;\nselect * from stages where team_id = 459;\nselect * from teams where id = 459;\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 = 459 and sa.provider = 'hubspot';\n\nSELECT os.stage_id, s.crm_provider_id, s.name, COUNT(*) as cnt\nFROM opportunity_stages os\nJOIN stages s ON s.id = os.stage_id\nWHERE os.opportunity_id = 7594349\nGROUP BY os.stage_id, s.crm_provider_id, s.name\nORDER BY cnt DESC;\n\nSELECT s.id, s.crm_provider_id, s.name, s.team_id, s.crm_configuration_id\nFROM stages s\nJOIN business_process_stages bps ON bps.stage_id = s.id\nWHERE bps.business_process_id = 6024\nAND s.crm_provider_id = 'contractsent';\n\nselect * from stages where id IN (16352,20612,18281,7344,16378,16309,5036,15223,14535,6293,12098,11607)\n\nSELECT * FROM teams WHERE name LIKE '%Pulsar Group%'; # 472, 380, 15138, raza.gilani@vuelio.com\nselect * from playbooks where team_id = 472; # event 226147\nSELECT * FROM playbook_categories WHERE playbook_id = 2288;\nSELECT * FROM crm_fields WHERE id = 226147;\nSELECT * FROM crm_field_values WHERE crm_field_id = 226147;\n\nSELECT * FROM crm_configurations WHERE id = 380;\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 = 472 and sa.provider = 'salesforce';\n\nselect * from activities where id = 58081273;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2;\n\nSELECT * FROM users WHERE name LIKE '%Neil Hoyle%'; # 17651\nSELECT * FROM social_accounts WHERE sociable_id = 17651;\n\nSELECT * FROM activities WHERE uuid_to_bin('975c6830-7d49-4c1e-b2e9-ac80c10a738a') = uuid;\nSELECT * FROM opportunities WHERE id IN (7842553, 6211727);\nSELECT * FROM contacts WHERE id IN (10202724, 6211727);\nSELECT * FROM opportunity_stages WHERE opportunity_id = 7842553;\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 = 519 and sa.provider = 'hubspot';\n\nselect * from crm_configurations where id = 436;\nselect * from crm_profiles where crm_configuration_id = 436; # 76091797 -> 16612\n\nselect * from contact_roles where contact_id = 10202724;\n\nselect * from stages where team_id = 519; # 18778\n18775\n\nSELECT\n id,\n crm_provider_id,\n stage_id,\n is_closed,\n is_won,\n stage_updated_at,\n updated_at\nFROM opportunities\nWHERE id IN (6211727, 7842553);\n\nSELECT * FROM opportunity_contacts\nWHERE opportunity_id = 6211727 AND contact_id = 10202724;\n\nSELECT id, name, stage_id, is_closed, is_won, updated_at, remotely_created_at\nFROM opportunities\nWHERE account_id = 8179134\nORDER BY updated_at DESC;\n\n\nselect * from text_relays where created_at > '2026-01-01';\nAND id IN (691, 692);\n\nselect * from teams;\n\n# ***************\nSELECT DISTINCT u.id, u.email, u.name, u.softphone_number, COUNT(a.id) as sms_count\nFROM users u\nINNER JOIN activities a ON u.id = a.user_id\nWHERE a.type LIKE 'sms%'\nAND a.created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)\nGROUP BY u.id, u.email, u.name, u.softphone_number\nORDER BY sms_count DESC;\n\nSELECT DISTINCT u.id, u.email, u.name, u.team_id, t.name as team_name,\n t.twilio_sms_sid, t.twilio_messaging_sid\nFROM users u\nINNER JOIN teams t ON u.team_id = t.id\nWHERE (t.twilio_sms_sid IS NOT NULL OR t.twilio_messaging_sid IS NOT NULL)\nAND u.status = 1\nORDER BY t.name, u.email;\n\nSELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, salesforce-admin@tourlane.com\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 = 187 and sa.provider = 'salesforce';\n\nselect * from activities where id = 31264367;\nselect * from contacts where id = 6331639;\nselect * from accounts where id = 4156632;\nselect * from opportunities where id = 4843610;\n# update `activities` set `account_id` = 4156632, `contact_id` = 6331639, `opportunity_id` = 4843610,\n# `stage_id` = 13273, `activities`.`updated_at` = 2026-05-22 07:16:17 where `id` = 31264367)\"\n\nselect * from text_relays where created_at > '2026-05-01';\n\nselect * from activities order by id desc;\n\nselect * from users where name like '%Subra%';\n\nSELECT * FROM opportunities WHERE uuid_to_bin('04a9cfad-2c87-4453-9e72-20aeb78ccf8d') = uuid;\nselect * from teams where id = 555;\nselect * from stages where team_id = 555;\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 = 100 and sa.provider = 'hubspot';","depth":4,"on_screen":true,"value":"SELECT * FROM team_features where team_id = 1;\n\nSELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922\nSELECT * FROM users WHERE team_id = 340; # 12015\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 340\nand sa.provider = 'salesforce';\n# and sa.provider = 'salesloft';\n\nselect * from crm_fields where crm_configuration_id = 270 and object_type = 'event';\n# 125558 - Event Type - Event_Type__c\n# 125552 - Event Status - Event_Status__c\n\nSELECT * FROM sidekick_settings WHERE team_id = 340;\n\nSELECT * FROM crm_field_values WHERE crm_field_id in (125552);\n\nselect * from activities where crm_configuration_id = 270\nand type = 'conference' and crm_provider_id IS NOT NULL\nand actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;\n\nSELECT * FROM activities WHERE id = 20871677;\nSELECT * FROM crm_field_data WHERE activity_id = 20871677;\n\nselect * from crm_layouts where crm_configuration_id = 270;\nselect * from crm_layout_entities where crm_layout_id in (886,887);\n\nSELECT * FROM crm_configurations WHERE id = 270;\n\nselect * from playbooks where team_id = 340; # 1514\nselect * from groups where team_id = 340;\nSELECT * FROM crm_fields WHERE id IN (125393, 125401);\n\nselect g.name as 'team name', p.name as 'playbook name', f.label as 'activity type field' from groups g\njoin playbooks p on g.playbook_id = p.id\njoin crm_fields f on p.activity_field_id = f.id\nwhere g.team_id = 340;\n\nSELECT * FROM activities WHERE uuid_to_bin('0c180357-67d2-419e-a8c3-b832a3490770') = uuid; # 20448716\nselect * from crm_field_data where object_id = 20448716;\n\nselect * from activities where crm_configuration_id = 270 and provider = 'salesloft' order by id desc;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%CybSafe%'; # 343,273,12008\nselect * from opportunities where team_id = 343;\nselect * from opportunities where team_id = 343 and crm_provider_id = '18099102526';\nselect * from opportunities where team_id = 343 and account_id = 945217482;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nselect * from accounts where team_id = 343 order by name asc;\n\nselect * from stages where crm_configuration_id = 273 and type = 'opportunity';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Voyado%'; # 353,283,12143\nSELECT * FROM activities WHERE crm_configuration_id = 283 and account_id = 3777844 order by id desc;\nSELECT * FROM accounts WHERE team_id = 353 AND name LIKE '%Salesloft%';\nSELECT * FROM activities WHERE id = 20717903;\n\nselect * from participants where activity_id IN (20929172,20928605,20928468,20926272,20926271,20926270,20926269,20916499,20916454,20916436,20916435,20900015,20900014,20900013,20897312,20897243,20897241,20897237,20897232,20897229,20893648,20893231,20893230,20893229,20893228,20889784,20885039,20885038,20885037,20885036,20885035,20882728,20882708,20882703,20882702,20869828,20869811,20869806,20869801,20869799,20869798,20869796,20869795,20869794,20869761,20869760,20869759,20868688,20868687,20850340,20847195,20841710,20833967,20827021,20825307,20825305,20825297,20824615,20824400,20823927,20821760,20795588,20794233,20794057,20793710,20785811,20781789,20781394,20781307,20762651,20758453,20758282,20757323,20756643,20756636,20756629,20756627,20756606,20756605,20756604,20756603,20756602,20756600,20756599,20756598,20756595,20756594,20756589,20756587,20756577,20756573,20748918,20748386,20748385,20748384,20748383,20748382,20748381,20748380,20748379,20748377,20748375,20748373,20743301,20717905,20717904,20717903,20717901,20717899);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 353\nand sa.provider = 'salesforce';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%modern world business solutions%'; # 345,275,12016, l.atkinson@mwbsolutions.co.uk\nSELECT * FROM activities WHERE uuid_to_bin('3921d399-3fef-4609-a291-b0097a166d43') = uuid;\n# id: 20940638, user: 12022, contact: 5305871\nSELECT * FROM activity_summary_logs WHERE activity_id = 20940638;\nselect * from contacts where team_id = 345 and crm_provider_id = '30891432415' order by name asc; # 5305871\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 345\nand sa.provider = 'hubspot';\n\nselect * from users where team_id = 345 and id = 12022;\nSELECT * FROM crm_profiles WHERE user_id = 12022;\nSELECT * FROM participants WHERE activity_id = 20940638;\nSELECT * FROM users u\nJOIN crm_profiles cp ON u.id = cp.user_id\nWHERE u.team_id = 345;\n\nselect * from contacts where team_id = 345 and crm_provider_id = '30880813535' order by name desc; # 5305871\n\nselect * from team_features where team_id = 345;\nSELECT * FROM activities WHERE uuid_to_bin('11701e2d-2f82-4dab-a616-1db4fad238df') = uuid; # 21115197\nSELECT * FROM participants WHERE activity_id = 20897406;\n\n\n\nSELECT * FROM activities WHERE uuid_to_bin('63ba55cd-1abc-447d-83da-0137000005b7') = uuid; # 20953912\nSELECT * FROM activities WHERE crm_configuration_id = 275 and provider = 'ringcentral' and title like '%1252629100%';\n\n\nSELECT * FROM activities WHERE id = 20946641;\nSELECT * FROM crm_profiles WHERE user_id = 10211;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120,97,10984, triger@lunio.ai\nSELECT * FROM opportunities WHERE crm_configuration_id = 97 and crm_provider_id = '006N1000006c5PpIAI';\nselect * from stages where crm_configuration_id = 97 and type = 'opportunity';\nselect * from opportunities where team_id = 120;\n\n\nselect * from crm_configurations crm join teams t on crm.id = t.crm_id\nwhere 1=1\nAND t.current_billing_plan IS NOT NULL\nAND crm.auto_sync_activity = 0\nand crm.provider = 'hubspot';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Exclaimer%'; # 270,205,10053,james.lewendon@exclaimer.com\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 270\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('b54df794-2a9a-4957-8d80-09a600ead5f8') = uuid; # 21637956\nSELECT * FROM crm_profiles WHERE user_id = 11446;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Cygnetise%'; # 372,300,12554, alex.chikly@cygnetise.com\nselect * from playbooks where team_id = 372;\nselect * from crm_fields where crm_configuration_id = 300 and object_type = 'event'; # 141340\nSELECT * FROM crm_field_values WHERE crm_field_id = 141340;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 372\nand sa.provider = 'salesforce';\n\nselect * from crm_profiles where crm_configuration_id = 300;\nSELECT * FROM crm_configurations WHERE team_id = 372;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Planday%'; # 291,242,11501,mfa@planday.com\nSELECT * FROM opportunities WHERE team_id = 291 and crm_provider_id = '006bG000005DO86QAG'; # 3207756\nselect * from crm_field_data where object_id = 3207756;\nSELECT * FROM crm_fields WHERE id = 111834;\n\nselect f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value\nFROM crm_fields f\nJOIN crm_field_data fd ON f.id = fd.crm_field_id\nWHERE f.crm_configuration_id = 242\nAND f.object_type = 'opportunity'\nAND fd.object_id IN (3207756)\nORDER BY fd.object_id, fd.updated_at;\n\nSELECT * FROM crm_configurations WHERE auto_connect = 1;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150,salesforce-admin@tourlane.com\nselect * from group_deal_risk_types drgt join groups g on drgt.group_id = g.id\nwhere g.team_id = 187;\n\nselect * from `groups` where team_id = 187;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 187\nand sa.provider = 'salesforce';\n\n# Destination - 98870 - Destination__c\n# Stage - 79014 - StageName\n# Land Arrangement - 98856 - Land_Arrangement__c\n# Flight - 98848 - Flight__c\n# Last activity date - 98812 - LastActivityDate\n# Last modified date - 98809 - LastModifiedDate\n# Last inbound mail timestamp - 99151 - Last_Inbound_Mail_Timestamp__c\n# next call - 98864 - Next_Call__c\n\nselect * from crm_fields where crm_configuration_id = 209 and object_type = 'opportunity';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 209;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;\n\nselect * from opportunities where team_id = 187 and name LIKE'%Muriel Sal%';\nselect * from opportunities where team_id = 187 and user_id = 9951 and is_closed = 0;\nselect * from activities where opportunity_id = 3538248;\n\nSELECT * FROM crm_profiles WHERE user_id = 8150;\n\nselect * from deal_risks where opportunity_id = 3538248;\n\nselect * from teams where crm_id IS NULL;\n\nSELECT opp.id AS opportunity_id,\n u.group_id AS group_id,\n MAX(\n CASE\n WHEN a.type IN (\"sms-inbound\", \"sms-outbound\") THEN a.created_at\n ELSE a.actual_end_time\n END) as last_date\nFROM opportunities opp\nleft join activities a on a.opportunity_id = opp.id\ninner join users u on opp.user_id = u.id\nwhere opp.user_id IN (9951)\n\nAND opp.is_closed = 0\nand a.status IN ('completed', 'received', 'delivered') OR a.status IS NULL\ngroup by opp.id;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Cybsafe%'; # 343,301,12008,polly.morphew@cybsafe.com\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 301;\nSELECT * FROM contacts WHERE id = 6612363;\nSELECT * FROM accounts WHERE id = 4235676;\nSELECT * FROM opportunities WHERE crm_configuration_id = 301 and crm_provider_id = 32983784868;\nselect * from opportunity_stages where opportunity_id = 4503759;\n# SELECT * FROM opportunities WHERE id = 4569937;\n\nselect * from activities where crm_configuration_id = 301;\nSELECT * FROM activities WHERE uuid_to_bin('d3b2b28b-c3d0-4c2d-8ed0-eef42855278a') = uuid; # 26330370\nSELECT * FROM participants WHERE activity_id = 26330370;\n\nSELECT * FROM teams WHERE id = 375;\nselect * from playbooks where team_id = 375;\n\nselect * from stages where crm_configuration_id = 301 and type = 'opportunity';\n\nselect * from teams;\nselect * from contact_roles;\n\nSELECT * FROM opportunities WHERE team_id = 343 and user_id = 12871 and close_date >= '2024-11-01';\n\nselect * from users u join crm_profiles cp on cp.user_id = u.id where u.team_id = 343;\n\nSELECT * FROM crm_field_data WHERE object_id = 3771706;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_fields WHERE crm_configuration_id = 301 and object_type = 'opportunity'\nand crm_provider_id LIKE \"%traffic_light%\";\nSELECT * FROM crm_field_values WHERE crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531);\n\nSELECT fd.* FROM opportunities o\nJOIN crm_field_data fd ON o.id = fd.object_id\nWHERE o.team_id = 343\n# and o.user_id IS NOT NULL\nand fd.crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531)\nand fd.value != ''\norder by value desc\n# group by o.id\n;\n\nSELECT * FROM opportunities WHERE id = 3769843;\n\nSELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150, salesforce-admin@tourlane.com\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 209;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Funding Circle%'; # 220,177,8603,aswini.mishra@fundingcircle.com\nSELECT * FROM activities WHERE uuid_to_bin('7a40e99b-3b37-4bb1-b983-325b81801c01') = uuid; # 23139839\n\n\nSELECT * FROM opportunities WHERE id = 3855992;\n\nSELECT * FROM users WHERE name LIKE '%Angus Pollard%'; # 8988\n\nSELECT * FROM teams WHERE name LIKE '%Story Terrace%'; # 379, 307, 12894\nSELECT * FROM crm_fields WHERE crm_configuration_id = 307 and object_type != 'opportunity';\n\nselect * from contacts where team_id = 379 and name like '%bebro%'; # 5874411, crm: 77229348507\nSELECT * FROM crm_field_data WHERE object_id = 5874411;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 379\nand sa.provider = 'hubspot';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%mentio%'; # 117, 94, 6371, nikhil.kumar@mention-me.com\nSELECT * FROM activities WHERE uuid_to_bin('82939311-1af0-4506-8546-21e8d1fdf2c1') = uuid;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, salesforce-admin@tourlane.com\nSELECT * FROM opportunities WHERE team_id = 187 and crm_provider_id = '006Se000008xfvNIAQ'; # 3537793\nselect * from generic_ai_prompts where subject_id = 3537793;\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120, 97, 10984, triger@lunio.ai\nSELECT * FROM crm_configurations WHERE id = 97;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 97;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 355;\nSELECT * FROM crm_fields WHERE id = 32682;\n\nselect cfd.value, o.* from opportunities o\njoin crm_field_data cfd on o.id = cfd.object_id and cfd.crm_field_id = 32682\nwhere team_id = 120\nand cfd.value != ''\n;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 120\nand sa.provider = 'salesforce';\n\nselect * from opportunities where team_id = 120 and crm_provider_id = '006N1000007X8MAIA0';\nSELECT * FROM crm_field_data WHERE object_id = 2313439;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE id = 410;\nSELECT * FROM teams WHERE name LIKE '%Local Business Oxford%';\nselect * from scorecards where team_id = 410;\nselect * from scorecard_rules;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Funding%'; # 220, 177, 8603, aswini.mishra@fundingcircle.com\nselect * from activities a\njoin opportunities o on a.opportunity_id = o.id\njoin users u on o.user_id = u.id\nwhere a.crm_configuration_id = 177 and a.type LIKE '%email-out%'\n# and a.actual_end_time > '2024-12-16 00:00:00'\n# and o.remotely_created_at > '2024-12-01 00:00:00'\n# and u.group_id = 1014\nand u.id = 9021\norder by a.id desc;\nSELECT * FROM opportunities WHERE id in (3981384,4017346);\nSELECT * FROM users WHERE team_id = 220 and id IN (8775, 11435);\n\nselect * from users where id = 9021;\nselect * from inboxes where user_id = 9021;\n\nselect * from inbox_emails where inbox_id = 1349 and email_date > '2024-12-18 00:00:00';\n\nselect * from email_messages where team_id = 220\nand orig_date > '2024-12-16 00:00:00' and orig_date < '2024-12-19 00:00:00'\nand subject LIKE '%Personal%'\n# and 'from' = 'credit@fundingcircle.com'\n;\n\nselect * from activities a\njoin opportunities o on a.opportunity_id = o.id\nwhere a.user_id = 9021 and a.type LIKE '%email-out%'\nand a.actual_end_time > '2024-12-18 00:00:00'\nand o.user_id IS NOT NULL\nand o.remotely_created_at > '2024-12-01 00:00:00'\norder by a.id desc;\n\nSELECT * FROM opportunities WHERE team_id = 220 and name LIKE '%Right Car move Limited%' and id = 3966852;\nselect * from activities where crm_configuration_id = 177 and type LIKE '%email%' and opportunity_id = 3966852 order by id desc;\n\nselect * from team_settings where name IN ('useCloseDate');\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Hurree%'; # 104, 81, 6175, jfarrell@hurree.co\nSELECT * FROM opportunities WHERE team_id = 104 and name = 'PropOp';\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 104\nand sa.provider = 'hubspot';\n\nselect * from crm_configurations where last_synced_at > '2025-01-19 01:00:00'\nselect * from teams where crm_id IS NULL;\n\nselect t.name as 'team', u.name as 'owner', u.email, u.phone\nfrom teams t\njoin activity_providers ap on t.id = ap.team_id\njoin users u on t.owner_id = u.id\nwhere 1=1\n and t.status = 'active'\n and ap.is_enabled = 1\n# and u.status = 1\n and ap.provider = 'ms-teams';\n\nselect * from crm_configurations where provider = 'bullhorn'; # 344\nSELECT * FROM teams WHERE id = 442; # 14293\nselect * from users where team_id = 442;\nselect * from social_accounts sa where sa.sociable_id = 14293;\nselect * from invitations where team_id = 442;\n\n# ********************************************************************************************************\nSELECT * FROM users WHERE email LIKE '%nea.liikamaa@eletive.com%'; # 14022\nSELECT * FROM teams WHERE id = 429;\nselect * from opportunities where team_id = 429 and crm_provider_id IN (16157415775, 22246219645);\nselect * from activities where opportunity_id in (4340436,4353519);\n\nselect * from transcription where activity_id IN (25630961,25381771);\nselect * from generic_ai_prompts where subject_id IN (4353519);\n\nSELECT\n a.id as activity_id,\n a.opportunity_id,\n a.type as activity_type,\n a.language,\n CONCAT(a.title, a.description) AS mail_content,\n e.from AS mail_from,\n e.to AS mail_to,\n e.subject AS mail_subject,\n e.body AS mail_body,\n p.type as prompt_type,\n p.status as prompt_status,\n p.content AS prompt_content,\n a.actual_start_time as created_at\nFROM activities a\n LEFT JOIN ai_prompts p ON a.transcription_id = p.transcription_id AND p.deleted_at IS NULL\n LEFT JOIN email_messages e ON a.id = e.activity_id\nWHERE a.actual_start_time > '2024-01-01 00:00:00'\n AND a.opportunity_id IN (4353519)\n AND a.status IN ('completed', 'received', 'delivered')\n AND a.deleted_at IS NULL\n AND a.type NOT IN ('sms-inbound', 'sms-outbound')\nORDER BY a.opportunity_id ASC, a.id ASC;\n\nSELECT * FROM users WHERE name LIKE '%George Fierstone%'; # 14293\nSELECT * FROM teams WHERE id = 442;\nSELECT * FROM crm_configurations WHERE id = 344;\nselect * from team_features where team_id = 442;\nselect * from groups where team_id = 442;\nselect * from playbooks where team_id = 442;\nselect * from playbook_categories where playbook_id = 1729;\nselect * from crm_fields where crm_configuration_id = 344 and id = 172024;\nSELECT * FROM crm_field_values WHERE crm_field_id = 172024;\nselect * from crm_layouts where crm_configuration_id = 344;\nselect * from playbook_layouts where playbook_id = 1729;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 221, 9444\n\nselect s.*\n# , s.sent_at, u.name, a.*\nfrom activity_summary_logs s\ninner join activities a on a.id = s.activity_id\ninner join users u on u.id = a.user_id\nwhere a.crm_configuration_id = 356\nand s.sent_at > date_sub(now(), interval 60 day)\norder by a.actual_end_time desc;\n\nselect * from activities a\n# inner join activity_summary_logs s on s.activity_id = a.id\nwhere a.crm_configuration_id = 356 and a.actual_end_time > date_sub(now(), interval 60 day)\n# and a.crm_provider_id is not null\n# and provider <> 'ringcentral'\nand status = 'completed'\norder by a.actual_end_time desc;\n\nselect * from teams order by id desc; # 17328, 32, 17830, integration-account@jiminny.com\nSELECT * FROM users;\nSELECT * FROM users where team_id = 260 and status = 1; # 201 - 150 active\nSELECT * FROM teams WHERE id = 260;\nselect * from team_settings where team_id = 260;\nselect * from crm_configurations where team_id = 260;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 356;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1184;\n\nselect * from accounts where crm_configuration_id = 221 order by id desc; # 7000\nselect * from leads where crm_configuration_id = 221 order by id desc; # 0\nselect * from contacts where crm_configuration_id = 221 order by id desc; # 200 000\nselect * from opportunities where crm_configuration_id = 221 order by id desc; # 0\nselect * from crm_profiles where crm_configuration_id = 221 order by id desc; # 23\nselect * from crm_fields where crm_configuration_id = 221;\nselect * from crm_field_values where crm_field_id = 5302 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 221 order by id desc;\nselect * from stages where crm_configuration_id = 221 order by id desc;\n\nselect * from accounts where crm_configuration_id = 356 order by id desc; # 7000\nselect * from leads where crm_configuration_id = 356 order by id desc; # 0\nselect * from contacts where crm_configuration_id = 356 order by id desc; # 200 000\nselect * from opportunities where crm_configuration_id = 356 order by id desc; # 0\nselect * from crm_profiles where crm_configuration_id = 356 order by id desc; # 23\nselect * from crm_fields where crm_configuration_id = 356;\nselect * from crm_field_values where crm_field_id = 5302 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 356 order by id desc;\nselect * from stages where crm_configuration_id = 356 order by id desc;\n\nselect * from playbooks where team_id = 260 order by id desc; # 4 (2 deleted)\nselect * from groups where team_id = 260 order by id desc; # 27 groups, (2 deleted)\nselect * from playbook_layouts where playbook_id IN (1410,1409,1276,1254); # 4\nselect ce.* from calendars c\njoin users u on c.user_id = u.id\njoin calendar_events ce on c.id = ce.calendar_id\nwhere u.team_id = 260\nand (ce.start_time > '2025-02-21 00:00:00')\n;\n# calendar events 1207\n#\n\nselect * from opportunities where team_id = 260;\nSELECT * FROM crm_field_data WHERE object_id = 4696496;\n\nselect * from activities where crm_configuration_id = 356 and crm_provider_id IS NOT NULL;\nselect * from activities where crm_configuration_id IN (221) and provider NOT IN ('ms-teams', 'uploader', 'zoom-bot')\n# and type = 'conference' and status = 'scheduled' and activities.is_internal = 0\nand created_at > '2024-03-01 00:00:00'\norder by id desc; # 880 000, ringcentral, avaya\nSELECT * FROM participants WHERE activity_id = 26371744;\n\n# all activities 942 000 +\n# conference 7385 - scheduled 984 - external 343\n\nselect * from activities where id = 26321812;\nselect * from participants where activity_id = 26321812;\nselect * from participants where activity_id in (26414510,26414514,26414516,26414604,26414653,26414655);\nselect * from leads where id in (720428,689175,731546,645866,621037);\n\nselect * from users where id = 13841;\nselect * from opportunities where user_id = 9541;\nselect * from stages where id = 15900;\n\nselect * from accounts where\n# id IN (4160055,5053725,4965303,4896434)\nid in (4584518,3249934,3218025,3891133,3399450,4172999,4485161,3101785,4587203,3070816,2870343,2870341,3563940,4550846,3424464,3249963,2870342)\n;\n\nselect * from activities where id = 26654935;\nSELECT * FROM opportunities WHERE id = 4803458;\n\nSELECT * FROM opportunities where team_id = 260 and user_id = 13841 AND stage_id = 15900;\nSELECT id, uuid, provider, type, lead_id, account_id, contact_id, opportunity_id, stage_id, status, recording_state, title, actual_start_time, actual_end_time\nFROM activities WHERE user_id = 13841 AND opportunity_id IN (4729783, 4731717, 4731726, 4732064, 4732849, 4803458, 4813213);\n\nSELECT DISTINCT\n o.id, o.stage_id, s.name, a.title,\n a.*\nFROM activities a\n# INNER JOIN tracks t ON a.id = t.activity_id\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams team ON u.team_id = team.id\nINNER JOIN groups g ON u.group_id = g.id\nINNER JOIN opportunities o ON a.opportunity_id = o.id\nINNER JOIN stages s ON o.stage_id = s.id\nWHERE\n a.crm_configuration_id = 356\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n# and a.user_id = 13841\n AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')\n AND team.uuid = uuid_to_bin('a607fba7-452e-4683-b2af-00d6cb52c93c')\n AND g.uuid = uuid_to_bin('b5d69e40-24a0-4c16-810b-5fa462299f94')\n\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND t.type IN ('audio', 'video')\n AND (\n (a.actual_start_time BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59')\n OR\n (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59'\n )\n )\n AND (\n a.is_private = 0\n OR (\n a.is_private = 1\n AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')\n )\n )\n AND (\n# s.id = 15900\n s.uuid = uuid_to_bin('04ca1c26-c666-4268-a129-419c0acffd73')\n OR s.uuid IS NULL -- Include records without opportunity stage\n )\n\nORDER BY a.actual_end_time DESC;\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lead Forensics%'; # 190, 162, 8474, willsc@leadforensics.com\nSELECT * FROM users WHERE team_id = 190;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 190\nand sa.provider = 'hubspot';\n\nselect * from role_user where user_id = 8474;\n\nselect * from crm_configurations where provider = 'bullhorn';\n\nSELECT * FROM opportunities WHERE uuid_to_bin('94578249-65ec-4205-90f2-7d1a7d5ab64a') = uuid;\nSELECT * FROM users WHERE uuid_to_bin('26dbadeb-926f-4150-b11b-771b9d4c2f9a') = uuid;\n\nSELECT * FROM opportunities WHERE id = 4732493;\nselect * from activities where opportunity_id = 4732493;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE id = 443; # 358, 14315, andrea.romano@correrenaturale.com\nSELECT * FROM opportunities WHERE team_id = 443;\n\nSELECT a.id, a.type, a.user_id, a.status, a.deleted_at, u.name, u.email, u.team_id as activity_team_id, u.status, u.deleted_at, t.name, t.status, s.team_id as stage_team_id\nFROM activities AS a\nJOIN stages AS s ON a.stage_id = s.id\nJOIN users AS u ON u.id = a.user_id\nJOIN teams AS t ON t.id = s.team_id\nWHERE u.team_id <> s.team_id and t.id > 135;\n\n\nSELECT\n crm_configuration_id,\n crm_provider_id,\n COUNT(*) as duplicate_count,\n GROUP_CONCAT(id) as stage_ids,\n GROUP_CONCAT(name) as stage_names\nFROM stages\nGROUP BY crm_configuration_id, crm_provider_id\nHAVING COUNT(*) > 1\nORDER BY duplicate_count DESC;\n\nselect * from stages where id IN (14898,14907);\n\nselect * from business_processes;\n\nSELECT *\nFROM crm_configurations\nWHERE team_id IN (\n SELECT team_id\n FROM crm_configurations\n GROUP BY team_id\n HAVING COUNT(*) > 1\n)\nORDER BY team_id;\n\nSELECT *\nFROM teams\nWHERE crm_id IN (\n SELECT crm_id\n FROM teams\n GROUP BY crm_id\n HAVING COUNT(*) > 1\n)\nORDER BY crm_id;\n\n# ***************************************************************************\nselect * from crm_configurations where provider = 'integration-app';\nSELECT * FROM teams WHERE id = 443; # Correre Naturale 358 14315 andrea.romano@correrenaturale.com\nselect * from activities where crm_configuration_id = 358 order by actual_end_time desc;\nselect id, uuid, actual_end_time, crm_provider_id, is_internal, playbook_category_id, type, user_id, lead_id, contact_id, account_id, opportunity_id, status, title from activities where crm_configuration_id = 358 order by actual_end_time desc;\nselect * from team_features where team_id = 358;\nselect * from activity_summary_logs;\n\nselect * from teams where id = 406;\n\n# ************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Sportfive%'; # 267, 202, 14637, srv.salesforce@sportfive.com\nselect * from activities where crm_configuration_id = 202 order by actual_end_time desc;\n\nSELECT * FROM users where id = 14637;\nSELECT * FROM teams where id = 267;\nSELECT * FROM groups where id = 1118;\n\nselect g.name, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\ninner join groups g on g.id = u.group_id\nwhere a.crm_configuration_id = 202\nand a.is_internal = 0\nand (a.scheduled_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type = 'conference'\nand a.status != 'completed'\nand a.external_id is not null\norder by a.scheduled_start_time desc;\n\nSELECT * FROM activities\nWHERE crm_configuration_id = 202\n AND status IN ('completed', 'failed')\n AND recording_state != 'stopped'\n AND type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n AND (is_private = 0 OR user_id = 14637)\n AND (\n (\n actual_start_time BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n ) OR (\n actual_start_time IS NULL\n AND type IN ('sms-outbound', 'sms-inbound')\n AND created_at BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n )\n )\n AND NOT EXISTS (\n SELECT 1\n FROM tracks\n WHERE\n tracks.activity_id = activities.id\n AND tracks.type IN ('audio', 'video')\n )\nORDER BY actual_end_time DESC;\n\nSELECT DISTINCT\n a.*\nFROM activities a\nINNER JOIN tracks t ON a.id = t.activity_id\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams team ON u.team_id = team.id\nWHERE\n a.crm_configuration_id = 202\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n# and a.user_id = 14637\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND t.type IN ('audio', 'video')\n AND (\n (a.actual_start_time BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59')\n OR\n (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n )\n )\n AND (\n a.is_private = 0\n OR (\n a.is_private = 1\n AND a.user_id = 14637\n )\n )\n\nORDER BY a.actual_end_time DESC\n;\n\nSELECT DISTINCT a.*\nFROM activities a\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams t ON u.team_id = t.id\n# INNER JOIN tracks tr ON a.id = tr.activity_id\n# INNER JOIN groups g ON u.group_id = g.id\nWHERE 1=1\n AND t.id = 267\n# AND t.uuid = uuid_to_bin('aed4927b-f1ea-499e-94c3-83762fd233e8')\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND tr.type NOT IN ('audio', 'video')\n AND (\n a.is_private = 0\n OR a.user_id = 14637\n )\n AND (\n (a.actual_start_time BETWEEN '2025-03-19 00:00:00' AND '2025-03-21 23:59:59')\n OR (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-19 00:00:00' AND '2025-03-21 23:59:59'\n )\n )\n# and NOT EXISTS (\n# SELECT 1\n# FROM tracks t\n# WHERE t.activity_id = a.id\n# AND t.type IN ('audio', 'video')\n# )\n\nORDER BY a.actual_end_time DESC;\n\nSELECT * FROM tracks WHERE activity_id = 26485995;\n\nselect a.is_private, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\nwhere a.crm_configuration_id = 202\n# and a.is_internal = 0\nand (a.actual_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type IN (\"softphone\",\"softphone-inbound\",\"conference\",\"sms-inbound\")\nand a.status IN ('completed', 'failed')\n# and a.external_id is not null\norder by a.actual_end_time desc;\n\nselect * from activities a where a.crm_configuration_id = 202\nand a.actual_start_time between '2025-03-20 00:00:00' and '2025-03-21 00:00:00'\n# AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n\nselect g.name, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\ninner join groups g on g.id = u.group_id\nwhere a.crm_configuration_id = 202\nand a.is_internal = 0\nand (a.scheduled_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type = 'conference'\nand a.status != 'completed'\nand a.external_id is not null\norder by a.scheduled_start_time desc;\n\nSELECT * FROM teams WHERE name LIKE '%Tourlane%';\nSELECT * FROM crm_fields WHERE crm_configuration_id = 209 and object_type = 'opportunity';\nSELECT * FROM crm_field_data WHERE crm_field_id = 98809;\n\nselect * from users where status = 1 AND timezone = 'MDT';\n\nselect * from opportunities where id = 3769814;\nselect * from deal_risks where opportunity_id = 3769814;\n\nselect cp.* from crm_profiles cp\njoin users u on cp.user_id = u.id\njoin crm_configurations crm on cp.crm_configuration_id = crm.id\nwhere crm.provider = 'hubspot' AND u.status = 1 AND log_notes != 'none';\n\nselect * from crm_fields where id = 154575;\n\nselect * from team_features where feature = 'SUPPORTS_SYNC_MISSING_CALL_DISPOSITIONS';\nSELECT * FROM teams WHERE id = 176; # crm 148\nselect * from activities where crm_configuration_id = 148 and provider = 'hubspot' order by id desc;\n\nselect * from activity_providers where provider = 'amazon-connect';\n\nselect * from crm_fields cf\njoin crm_configurations crm on crm.id = cf.crm_configuration_id\nwhere crm.provider = 'hubspot' and cf.object_type IN ('account', 'contact');\n\n# *********************************************************************************************\nSELECT * FROM users WHERE id IN (15415, 15418);\nSELECT * FROM groups WHERE id IN (1805,1806);\nSELECT * FROM playbooks WHERE id = 1860;\nSELECT * FROM playbook_categories WHERE id = 38634;\nSELECT * FROM crm_fields WHERE id = 189962;\n\nSELECT * FROM teams WHERE name = 'Pulsar Group'; # 472, 380, 15138 raza.gilani@vuelio.com\n\nSELECT * FROM crm_profiles WHERE user_id = 15415;\nSELECT * FROM social_accounts WHERE sociable_id = 15415 and provider = 'salesforce';\n\nselect * from sidekick_settings where team_id = 472;\n\nSELECT * FROM activities WHERE uuid_to_bin('452c58c7-b87c-4fdd-953e-d7af185e9588') = uuid; # 28617536, user: 15418\nSELECT * FROM activities WHERE uuid_to_bin('399114ee-d3a8-458c-bff5-5f654658db0a') = uuid; # 28344407, user: 15415\nSELECT * FROM activities WHERE uuid_to_bin('f0aa567f-0ab1-4bbb-96aa-37dcf184676b') = uuid; # 28580288, user: 15415\nSELECT * FROM activities WHERE uuid_to_bin('50c086b1-2770-4bca-b5ae-6bac22ec426b') = uuid; # 28566069, user: 15415\n\n# *********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%TeamTailor%'; # 109, 218, 13969, salesforce-integrations@teamtailor.com\nselect * from crm_configurations where id = 218;\nSELECT * FROM activities WHERE uuid_to_bin('e39b5857-7fdb-4f5a-951a-8d3ca69bb1b0') = uuid; # 28338765\nSELECT * FROM users WHERE id IN (13232, 13230);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\n\n0057R00000EPL5HQAX Inez Ekblad\n\n1091cb81-5ea1-4951-a0ed-f00b568f0140 Triman Kaur\n\nSELECT * FROM crm_profiles WHERE user_id IN (13232, 13230);\n\n############################################################################################\nSELECT * FROM activities WHERE uuid_to_bin('675eeaeb-5681-42db-90bc-54c07a604408') = uuid; # 28655939 00UVg00000FLvnSMAT\nSELECT * FROM crm_field_data WHERE activity_id = 28655939;\nSELECT * FROM crm_fields WHERE id IN (94491,94493,94498);\nSELECT * FROM users WHERE id = 13658;\nSELECT * FROM teams WHERE id = 109;\nSELECT * FROM crm_configurations WHERE id = 218;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Strengthscope%'; # 481, 390, 15420, katy.holden@strengthscope.comk\nSELECT * FROM stages WHERE crm_configuration_id = 390;\nselect * from business_processes where team_id = 481 and crm_configuration_id = 390;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 481\nand sa.provider = 'salesforce';\n\n\nSELECT * FROM users WHERE id = 15780; # team 462\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 462\nand sa.provider = 'hubspot';\n\n\nselect * from teams where id = 495;\nSELECT * FROM users WHERE id = 15794;\nselect * from social_accounts where sociable_id = 15794;\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Flight%'; # 427, 333, 13752\nSELECT * FROM accounts WHERE team_id = 427 and crm_provider_id = '668731000183444517';\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Group GTI%'; # 495, 407, 15794\nSELECT * FROM activities WHERE crm_configuration_id = 407\nand status = 'completed' and type = 'conference'\norder by id desc;\n\nselect ru.*, pr.*, p.* from users u join role_user ru on ru.user_id = u.id\njoin permission_role pr on pr.role_id = ru.role_id\n join permissions p on p.id = pr.permission_id\nwhere team_id = 495 and p.name IN ('dial');\n\nselect * from permission_role;\n\nselect * from activities where crm_configuration_id = 407 and status = 'completed' order by id desc;\nSELECT * FROM activities WHERE id = 29512773;\nSELECT * FROM activities WHERE id IN (29042721,28991325,29002874);\n\nSELECT al.* from activity_summary_logs al join activities a on a.id = al.activity_id\nwhere a.crm_configuration_id = 407\n# and a.id IN (29042721,28991325,29002874);\n\nSELECT * FROM users WHERE id = 15794;\nSELECT * FROM users WHERE team_id = 495;\nSELECT * FROM social_accounts WHERE sociable_id = 15794;\nSELECT * FROM opportunities WHERE team_id = 495 and name like '%OC:%';\nSELECT * FROM contacts WHERE team_id = 495;\nSELECT * FROM leads WHERE team_id = 495;\nSELECT * FROM accounts WHERE team_id = 495;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 407;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 407;\nSELECT * FROM crm_configurations WHERE id = 407;\nSELECT * FROM opportunities WHERE team_id = 495 and close_date BETWEEN '2025-06-01' AND '2025-07-01'\nand user_id IS NOT NULL and is_closed = 1 and is_won = 1;\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Hamilton Court FX LLP%'; # 249, 187, 10103\nSELECT * FROM activities WHERE uuid_to_bin('4659c2bb-9a49-484e-9327-a3d66f1e028c') = uuid; # 28951064\nSELECT * FROM crm_fields WHERE crm_configuration_id = 187 and object_type IN ('tasks', 'event');\n\n# *********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Checkstep%'; # 325, 256, 11753\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 325\nand sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('7be372e2-1916-4d79-a2f3-ca3db1346db3') = uuid; # 28611085\nSELECT * FROM activities WHERE uuid_to_bin('980f0336-840b-4185-a5a9-30cf8b0749a8') = uuid; # 28719733\nSELECT * FROM activity_summary_logs where activity_id = 28719733;\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 356, 9444\nSELECT * FROM activity_summary_logs where sent_at BETWEEN '2025-06-09 11:38:00' AND '2025-06-09 11:40:00';\nSELECT * FROM leads WHERE crm_configuration_id = 356 and crm_provider_id = '230045001502770504'; # 823630\nselect * from activities where crm_configuration_id = 356 and lead_id = 841732;\n\nSELECT * from activity_summary_logs al join activities a on a.id = al.activity_id\nwhere a.crm_configuration_id = 356;\n\nselect * from activities where crm_configuration_id = 356\nand actual_end_time between '2025-06-09 11:00:00' and '2025-06-09 12:00:00'\norder by id desc;\n\nselect * from accounts where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\nselect * from leads where crm_configuration_id = 356 and crm_provider_id = '230045001514275654' order by id desc;\nselect * from contacts where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\nselect * from opportunities where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\n\nselect * from team_features where team_id = 260;\nselect * from features where id IN (1,2,4,6,18,19,20,9,10,3,23,24,25,26,27);\n\nSELECT * FROM activities WHERE uuid_to_bin('7be372e2-1916-4d79-a2f3-ca3db1346db3') = uuid;\n\nselect * from crm_fields;\nselect * from crm_layout_entities;\n\nSELECT * FROM teams WHERE name LIKE '%Optable%';\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Teamtailor%'; # 109, 218, 13969\nSELECT * FROM crm_configurations WHERE id = 218;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('675eeaeb-5681-42db-90bc-54c07a604408') = uuid; # 28655939\nSELECT * FROM crm_field_data WHERE activity_id = 28655939;\nSELECT * FROM crm_fields WHERE id in (94491,94493,94498);\n\nselect * from teams where crm_id IS NULL;\n\nSELECT * FROM activities WHERE uuid_to_bin('71aa8a0c-9652-4ff6-bee7-d98ae60abef6') = uuid;\n\n# *************************************************************************************************\nselect * from team_domains where team_id = 399;\nSELECT * FROM teams WHERE name LIKE '%Rydoo%'; # 399, 318, 13207\n\nselect * from calendar_events where id = 5163781;\nSELECT * FROM activities WHERE uuid_to_bin('be2cbc52-7fda-46a0-9ae0-25d9553eafc0') = uuid; # 29443896\nSELECT * FROM participants WHERE activity_id = 29443896;\nselect * from contacts where crm_configuration_id = 318 and email = 'marianne.westeng@strawberry.no';\nselect * from leads where crm_configuration_id = 318 and email = 'marianne.westeng@strawberry.no';\n\nselect * from activities where user_id = 14937 order by created_at ;\n\nselect * from users where id = 14937;\n\nselect * from contacts where crm_configuration_id = 318 and email LIKE '%@strawberry.se';\nselect * from opportunities where crm_configuration_id = 318 and crm_provider_id = '006Sf00000D1WOAIA3';\n\nselect * from activities a join participants p on a.id = p.activity_id\nwhere crm_configuration_id = 318 and a.updated_at > '2025-06-23T08:18:43Z';\n\n# *************************************************************************************************\nSELECT * FROM opportunities WHERE team_id = 379 and crm_provider_id = '39334518886';\nSELECT * FROM opportunities WHERE team_id = 379 order by id desc;\nSELECT * FROM teams WHERE id = 379;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 379 and sociable_id = 13852\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations WHERE id = 307;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 307;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1027;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 307\n and id IN (144750,144855,145158,155227);\n\nSELECT * FROM activities;\n\n\nselect * from activities\nwhere created_at > '2025-07-01 00:00:00'\n# and created_at < '2025-08-01 00:00:00'\nand type not in ('email-outbound', 'email-inbound')\nand account_id is null\nand contact_id is null\nand lead_id is null\nand opportunity_id is not null\n;\nSELECT * FROM activities WHERE id IN (25344155, 25344296, 25501909, 28692187);\nSELECT * FROM crm_configurations WHERE id in (335,301,200);\n\nselect * from crm_fields where crm_configuration_id = 230 and crm_provider_id = 'Age2__c';\n\nSELECT * FROM teams WHERE name LIKE '%Resights%';\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\n\nselect * from crm_configurations where provider = 'bullhorn'; # 344\nselect * from teams where id IN (442);\n\nselect * from activities\nwhere crm_configuration_id = 177\nand provider = 'amazon-connect'\n order by id desc;\n# and source <> 'gong';\n\nselect * from activity_providers where provider = 'amazon-connect';\n\nSELECT * FROM activities WHERE uuid_to_bin('cec1993b-a7e5-4164-b74d-d680ea51d2f2') = uuid;\n\n\nselect * from crm_configurations where store_transcript = 1;\nSELECT * FROM teams WHERE id IN (80);\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Sedna%'; # 277, 213, 12594\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 277\nand sa.provider = 'salesforce';\n\nselect * from activities where crm_configuration_id = 213 and account_id = 2511502;\n\nselect * from crm_configurations where id = 213;\n\nSELECT * FROM activities WHERE uuid_to_bin('35aa790a-8569-4544-8268-66f9a4a26804') = uuid; # 33981604\nSELECT * FROM participants WHERE activity_id = 33981604;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 337 and object_type = 'task';\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 431\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('b5476c7d-19a8-491b-869d-676ea1e857b6') = uuid; # 33997223\nselect * from activity_summary_logs where activity_id = 33997223;\nselect * from activity_notes where activity_id = 33997223;\n\n# ***********************************\nSELECT * FROM teams WHERE name LIKE '%Abode%';\n\n\nselect * from features;\nselect * from teams t\nwhere t.status = 'active'\nand id NOT IN (select team_id from team_features where feature_id = 9)\n;\n\n\nselect * from playbook_layouts where playbook_id = 1725;\nSELECT * FROM activities WHERE uuid_to_bin('65cc283c-4849-49e6-927f-4c281c8fea19') = uuid; # 34297473\nselect * from teams where id = 318;\nselect * from crm_configurations where team_id = 318;\nselect * from playbooks where team_id = 318;\nSELECT * FROM crm_layouts where crm_configuration_id = 381;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1259;\nSELECT * FROM crm_fields WHERE id IN (192938,192936,192939);\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1266;\nSELECT * FROM crm_fields WHERE id IN (192980,192991,192997,192998,193064,193067);\n\nSELECT * FROM activities WHERE uuid_to_bin('a902289b-285c-48eb-9cc2-6ad6c5d938f5') = uuid; # 34297533\n\n\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 927;\nSELECT * FROM crm_fields WHERE id IN (131668,131669,131670,131671,131676,131797);\n\nSELECT * FROM teams WHERE name LIKE '%Peripass%'; # 351, 281, 12124\nselect * from crm_layouts where crm_configuration_id = 281;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 927;\nselect * from crm_fields where crm_configuration_id = 281 and id in (131668,131669,131670,131671,131676,131797);\nselect * from opportunities where crm_configuration_id = 281;\n\nSELECT * FROM activities WHERE id IN (34211315, 34130075);\nSELECT * FROM crm_field_data WHERE object_id IN (34211315, 34130075);\n\nselect cf.crm_configuration_id, cle.crm_layout_id, cle.id, cf.id from crm_field_data cfd\njoin crm_layout_entities cle on cle.id = cfd.crm_layout_entity_id\njoin crm_fields cf on cle.crm_field_id = cf.id\nwhere cf.deleted_at IS NOT NULL\nGROUP BY cle.id, cf.id;\n\nselect * from crm_layouts where id IN (355);\nselect u.email, t.crm_id, t.* from teams t\njoin users u on u.id = t.owner_id\nwhere crm_id IN (97);\n\nSELECT * FROM crm_fields WHERE id = 96492;\n\nselect * from permissions;\nselect * from permission_role where permission_id = 247;\nselect * from roles;\n\nselect * from migrations;\n# *****************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('291e3c21-11cc-4728-aee7-6e4bedf86d72') = uuid; # 34262174\nSELECT * FROM crm_configurations WHERE id = 301;\nSELECT * FROM teams WHERE id = 343;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nselect * from participants where activity_id = 34262174;\n\nselect * from contacts where crm_configuration_id = 301 and id = 6976326;\nselect * from accounts where crm_configuration_id = 301 and id IN (4647626, 4815829); # 30761335403\n\nselect * from activity_summary_logs where activity_id = 34262174;\n\nselect * from users where status = 1 AND timezone = 'EST';\n\n# ****************************************************************************\nSELECT * FROM users WHERE id = 13869;\nSELECT * FROM crm_configurations WHERE id = 320;\nSELECT * FROM teams WHERE id = 401;\n\nSELECT * FROM activities WHERE uuid_to_bin('2228c16f-10be-48d5-90d4-67385219dc01') = uuid; # 29670601\n\nSELECT * FROM accounts WHERE id = 7761483;\nSELECT * FROM opportunities WHERE id = 6051814;\n\nSELECT * FROM teams WHERE name LIKE '%Seedlegals%';\n\n;select * from opportunities where updated_at > '2025-10-11' AND crm_provider_id = '34713761166';\n\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 177;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 577;\nSELECT * FROM crm_fields WHERE id IN (68458,68459,68480,68497,68524,68530,68554,68618,68662,68781,68810,68898,68981,69049,97467);\n\nSELECT t.id, crm.id, t.name, crm.sync_objects, crm.provider, crm.last_synced_at FROM crm_configurations crm join teams t on t.crm_id = crm.id\nwhere t.status = 'active' AND crm.provider = 'hubspot' AND crm.last_synced_at < '2025-10-22 00:00:00';\n\nSELECT * FROM activities WHERE uuid_to_bin('fa09449f-cba9-496a-b8f3-865cd3c72351') = uuid;\nSELECT * FROM crm_configurations where id = 184;\nSELECT * FROM teams WHERE id = 246;\nSELECT * FROM social_accounts WHERE sociable_id = 9259 and provider = 'hubspot';\n\nSELECT * FROM users WHERE email LIKE '%rhian.old@bud.co.uk%'; # 17700\nSELECT * FROM teams WHERE id = 551;\n\nSELECT * FROM crm_configurations WHERE id = 471;\nSELECT * FROM activities WHERE crm_configuration_id = 471 and crm_provider_id IS NOT NULL;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 471;\nSELECT * FROM crm_fields WHERE id = 307260;\nSELECT * FROM crm_field_values WHERE crm_field_id = 307260;\n\nselect * from crm_layouts where crm_configuration_id = 471;\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1547;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1548;\n\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 = 551 and sa.provider = 'hubspot';\n\nSELECT * FROM teams WHERE name LIKE '%$PCS%';\n\n# ********************************************************************************************************\nselect * from crm_configurations crm\njoin teams t on t.crm_id = crm.id\nwhere t.status = 'active'\nand crm.provider = 'hubspot';\n\n# $slug = 'HUBSPOT_WEBHOOK_SYNC';\n# $team = Jiminny\\Models\\Team::find(2);\n# $feature = Feature::query()->where('slug', $slug)->first();\n# TeamFeature::query()->create(['feature_id' => $feature->getId(),'team_id' => $team->getId()]);\n\n# hubspot_webhook_metrics\n\nselect * from crm_configurations where id = 331; # 416\nSELECT * FROM teams WHERE id = 416;\nSELECT * FROM opportunities WHERE team_id = 190;\n\nSELECT * FROM teams WHERE name LIKE '%Lead Forensics%';\nSELECT sa.id,\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 = 190 and sa.provider = 'hubspot';\n\n\n\nSELECT * FROM teams WHERE name LIKE '%Rapaport%'; # 431, 337\nSELECT * FROM teams where id = 431;\nSELECT * FROM crm_configurations where team_id = 431;\nSELECT * FROM activity_providers where team_id = 431;\nSELECT * FROM activities where crm_configuration_id = 337 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\nSELECT sa.id,\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 = 431 and sa.provider = 'salesforce';\n\nSELECT * FROM teams WHERE name LIKE '%BiP%'; # 401, 320\nSELECT * FROM teams where id = 401;\nSELECT * FROM crm_configurations where team_id = 401;\nSELECT * FROM activity_providers where team_id = 401;\nSELECT * FROM activities where crm_configuration_id = 320 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\nSELECT sa.id,\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 = 401 and sa.provider = 'salesforce';\n\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 307; # 379 - Story Terrace Inc , portalId: 3921157\nSELECT * FROM contacts WHERE team_id = 379 and updated_at > '2026-01-31 11:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 379 and updated_at > '2026-02-01 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 379 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\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 = 379 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 485; # 563 - LATUS Group (ad94d501-5d09-44fd-878f-ca3a9f8865c3) , portalId: 3904501\nSELECT * FROM opportunities WHERE team_id = 563 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 563 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 338; # 432 - Formalize , portalId: 9214205\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 = 432 and sa.provider = 'hubspot';\nSELECT * FROM opportunities WHERE team_id = 432 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 432 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 436; # 519 - Moxso , portalId: 25531989\nSELECT * FROM opportunities WHERE team_id = 519 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 519 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 96; # 119 - Nourish Care , portalId: 26617984\nSELECT * FROM opportunities WHERE team_id = 119 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 119 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 331; # 416 - The National College , portalId: 7213852\nSELECT * FROM opportunities WHERE team_id = 416 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 416 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 308; # 380 - Foodles , portalId: 7723616\nSELECT * FROM opportunities WHERE team_id = 380 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 380 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 379; # 471 - imat-uve , portalId: 9177354\nSELECT * FROM opportunities WHERE team_id = 471 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 471 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 465; # 545 - Spotler , portalId: 144759271\nSELECT * FROM opportunities WHERE team_id = 545 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 545 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 455; # 537 - indevis , portalId: 25666868\nSELECT * FROM opportunities WHERE team_id = 537 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 537 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 200; # 265 - Jobadder , portalId: 6426676\nSELECT * FROM opportunities WHERE team_id = 265 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 265 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 335; # 429 - Eletive , portalId: 6110563\nSELECT * FROM opportunities WHERE team_id = 429 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 429 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 363; # 456 - Global Group , portalId: 8901981\nSELECT * FROM opportunities WHERE team_id = 456 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 456 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 297; # 369 - Unbiased , portalId: 9229005\nSELECT * FROM opportunities WHERE team_id = 369 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 369 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 353; # 449 - Fuuse , portalId: 25781745\nSELECT * FROM opportunities WHERE team_id = 449 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 449 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 487; # 566 - Nimbus , portalId: 39982590\nSELECT * FROM opportunities WHERE team_id = 566 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 566 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 487;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1630;\nselect * from crm_fields where crm_configuration_id = 487 and\n(uuid_to_bin('4c6b2971-64d4-45b8-b377-427be758b5a5') = uuid or uuid_to_bin('59e368d8-65a0-4b77-b611-db37c99fbe68') = uuid);\nSELECT * FROM crm_field_values WHERE crm_field_id = 375177;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 420; # 506 - voiio , portalId: 145629154\nSELECT * FROM opportunities WHERE team_id = 506 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 506 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 479; # 558 - Momice , portalId: 535962\nSELECT * FROM opportunities WHERE team_id = 558 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 558 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 59; # 80 - Storyclash GmbH , portalId: 4268479\nSELECT * FROM opportunities WHERE team_id = 80 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 80 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 175; # 203 - Team iAM , portalId: 5534732\nSELECT * FROM opportunities WHERE team_id = 203 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 203 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 368; # 460 - OneTouch Health , portalId: 5534732183355\nSELECT * FROM opportunities WHERE team_id = 460 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 460 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\n\n\nselect * from users where id = 29643;\nSELECT * FROM crm_field_values WHERE crm_field_id = 375177;\n# ********************************************************************\nSELECT * FROM teams WHERE name LIKE '%Buynomics%'; # 462, 482, 14910\nSELECT * FROM activities WHERE crm_configuration_id = 482\nand type NOT IN ('email-inbound', 'email-outbound')\n# and description like '%The call focused on understanding Welch%'\norder by id desc;\n\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 = 462 and sa.provider = 'salesforce';\n\nselect * from contacts where crm_configuration_id = 482 and name = 'Cyndall Hill'; # 15504749\nselect * from contacts where id = 10891096; # 482\nSELECT * FROM activities WHERE crm_configuration_id = 482\nand type NOT IN ('email-inbound', 'email-outbound')\nand contact_id = 15504749\norder by id desc;\n\nselect * from activities where id = 36793003; # 96cc7bc1-8622-4d27-92f4-baf664fc1a56, 00UOf00000PDdOXMA1\nselect * from transcription where id = 7646782;\nselect * from ai_prompts where transcription_id = 7646782;\n\n# ********************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('7a8471a3-847e-4822-802b-ddf426bbc252') = uuid; # 37370018\nSELECT * FROM activity_summary_logs WHERE activity_id = 37370018;\nSELECT * FROM teams WHERE id = 555;\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 = 555 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('7c17b8aa-09df-4f85-a0f7-51f47afd712d') = uuid; # 37395250\nSELECT * FROM activities WHERE uuid_to_bin('14d60388-260d-494b-aa0d-63fdb1c78026') = uuid; # 37395250\n\nSELECT a.* FROM activities a JOIN crm_configurations c on c.id = a.crm_configuration_id\nwhere a.type IN ('softphone', 'softphone-outbound') and c.provider = 'hubspot'\nand a.provider NOT IN ('hubspot')\n# and a.provider IN ('salesloft')\n# and c.id NOT IN (70)\n# and a.duration > 30\n# and actual_start_time > '2026-02-05 00:00:00'\norder by a.id desc;\n\nSELECT * FROM activities WHERE id = 37549787;\nSELECT * FROM crm_profiles WHERE user_id = 17613;\n\nSELECT * FROM crm_configurations WHERE id = 70;\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 = 93 and sa.provider = 'hubspot';\n\nSELECT asf.activity_search_id, asf.id, asf.value\nFROM activity_search_filters asf\nWHERE asf.filter = 'group_id'\nAND asf.value IN (\n SELECT CONCAT(\n HEX(SUBSTR(uuid, 5, 4)), '-',\n HEX(SUBSTR(uuid, 3, 2)), '-',\n HEX(SUBSTR(uuid, 1, 2)), '-',\n HEX(SUBSTR(uuid, 9, 2)), '-',\n HEX(SUBSTR(uuid, 11))\n )\n FROM groups\n WHERE deleted_at IS NOT NULL\n);\n\nSELECT * FROM crm_configurations WHERE id = 373; # KPSBremen.de 465 # - no social account\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 = 465 and sa.provider = 'hubspot';\n\nselect * from crm_configurations where id = 494;\n\nSELECT * FROM teams WHERE name LIKE '%splose%'; # 572, 495, 18708\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 = 572 and sa.provider = 'pipedrive';\n\nselect * from opportunities where team_id = 572\n# and name like '%Onebright%'\n# and is_closed = 1 and is_won = 0\n order by id desc;\n\n\nselect * from users where deleted_at is null and status = 2;\n\nselect * from contacts where id = 17900517;\nselect * from accounts where id = 10109838;\nselect * from opportunities where id = 6955880;\n\nselect * from opportunity_contacts where opportunity_id = 6955880;\nselect * from opportunity_contacts where contact_id = 17900517;\n\nselect * from contact_roles cr join crm_configurations crm on cr.crm_configuration_id = crm.id\nwhere crm.provider != 'salesforce';\n\nSELECT * FROM activities WHERE uuid_to_bin('adcb8331-5988-4353-834e-383a355abba2') = uuid; # 38056424, crm 104659682404\nselect * from teams where id = 456;\nSELECT * FROM crm_configurations WHERE id = 363;\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 = 456 and sa.provider = 'hubspot';\n\nselect * from crm_layouts where crm_configuration_id = 363;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id IN (1203, 1204, 1635);\nSELECT * FROM crm_fields WHERE id IN (181536, 181538, 213455);\n\nSELECT * FROM teams WHERE name LIKE '%Electric%'; # 342, 272, 12767\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 = 342 and sa.provider = 'pipedrive';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 and name like 'NORTHUMBRIA POL%'; # and updated_at > '2025-07-01 00:00:00';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 order by remotely_created_at asc; # and updated_at > '2025-07-01 00:00:00';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 and updated_at > '2026-01-01 00:00:00';\nSELECT * FROM crm_fields WHERE crm_configuration_id = 272 and object_type = 'opportunity';\nSELECT * FROM crm_field_values WHERE crm_field_id = 127164;\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 = 342 and sa.provider = 'pipedrive';\n\nSELECT * FROM teams WHERE id = 472;\nSELECT * FROM crm_configurations WHERE id = 380;\nselect * from activities where id = 38285673; # 38285673\nSELECT * FROM users WHERE id = 16942;\nSELECT * FROM groups WHERE id = 1964;\nSELECT * FROM playbooks WHERE id = 2033;\n\nselect * from teams where created_at > '2026-03-09';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 499; # 1065\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1678;\n\nSELECT * FROM teams WHERE id = 575;\nselect * from opportunities where team_id = 575;\n\nSELECT * FROM activities WHERE uuid_to_bin('96b1261f-2357-49f9-ab38-23ce12008ea0') = uuid;\n\nselect * from contacts c\nwhere c.crm_configuration_id = 370 order by c.updated_at desc;\n\nSELECT * FROM participants where activity_id = 38833541;\nSELECT * FROM participants where activity_id = 39216301;\nSELECT * FROM activity_summary_logs where activity_id = 39216301;\nSELECT * FROM activities WHERE uuid_to_bin('c7d99fbe-1fb1-41f2-8f4d-52e2bf70e1e9') = uuid; # 38833541, crm 478116564181\nSELECT * FROM activities WHERE uuid_to_bin('2e6ff4d3-9faa-447a-a8c1-9acde4d885ae') = uuid; # 39216301, crm 480171536586\nselect * from crm_profiles where crm_configuration_id = 319 and crm_provider_id = 525785080;\nselect * from opportunities where crm_configuration_id = 319 and crm_provider_id = 410150124747;\nselect * from accounts where crm_configuration_id = 319 and crm_provider_id = 47150650569;\nselect * from contacts where crm_configuration_id = 319 and crm_provider_id IN ('665587441856', '742723347700');\n# owner 13236 525785080\n# contact 1 16779180 665587441856 - activity - Alex Howes alex@supportroom.com created 2026-01-26\n# contact 2 19247563 742723347700 - ash@supportroom.com 2026-03-24\n# company 4176133 47150650569\n# deal 7100953 410150124747\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 = 400 and sa.provider = 'hubspot';\n\nselect * from features;\nselect * from team_features where feature_id = 40;\n\nselect * from teams where id = 556; # owner: 18101, crm: 477\nselect * from crm_configurations where id = 477;\nSELECT * FROM users WHERE id = 18101;\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 = 556 and sa.provider = 'integration-app';\n\nselect * from opportunities where id = 7594349;\nselect * from opportunity_stages where opportunity_id = 7594349 order by created_at desc;\nselect * from business_processes where id = 6024;\nselect * from business_process_stages where stage_id = 16352;\nselect * from business_process_stages where business_process_id = 6024;\nselect * from stages where team_id = 459;\nselect * from teams where id = 459;\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 = 459 and sa.provider = 'hubspot';\n\nSELECT os.stage_id, s.crm_provider_id, s.name, COUNT(*) as cnt\nFROM opportunity_stages os\nJOIN stages s ON s.id = os.stage_id\nWHERE os.opportunity_id = 7594349\nGROUP BY os.stage_id, s.crm_provider_id, s.name\nORDER BY cnt DESC;\n\nSELECT s.id, s.crm_provider_id, s.name, s.team_id, s.crm_configuration_id\nFROM stages s\nJOIN business_process_stages bps ON bps.stage_id = s.id\nWHERE bps.business_process_id = 6024\nAND s.crm_provider_id = 'contractsent';\n\nselect * from stages where id IN (16352,20612,18281,7344,16378,16309,5036,15223,14535,6293,12098,11607)\n\nSELECT * FROM teams WHERE name LIKE '%Pulsar Group%'; # 472, 380, 15138, raza.gilani@vuelio.com\nselect * from playbooks where team_id = 472; # event 226147\nSELECT * FROM playbook_categories WHERE playbook_id = 2288;\nSELECT * FROM crm_fields WHERE id = 226147;\nSELECT * FROM crm_field_values WHERE crm_field_id = 226147;\n\nSELECT * FROM crm_configurations WHERE id = 380;\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 = 472 and sa.provider = 'salesforce';\n\nselect * from activities where id = 58081273;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2;\n\nSELECT * FROM users WHERE name LIKE '%Neil Hoyle%'; # 17651\nSELECT * FROM social_accounts WHERE sociable_id = 17651;\n\nSELECT * FROM activities WHERE uuid_to_bin('975c6830-7d49-4c1e-b2e9-ac80c10a738a') = uuid;\nSELECT * FROM opportunities WHERE id IN (7842553, 6211727);\nSELECT * FROM contacts WHERE id IN (10202724, 6211727);\nSELECT * FROM opportunity_stages WHERE opportunity_id = 7842553;\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 = 519 and sa.provider = 'hubspot';\n\nselect * from crm_configurations where id = 436;\nselect * from crm_profiles where crm_configuration_id = 436; # 76091797 -> 16612\n\nselect * from contact_roles where contact_id = 10202724;\n\nselect * from stages where team_id = 519; # 18778\n18775\n\nSELECT\n id,\n crm_provider_id,\n stage_id,\n is_closed,\n is_won,\n stage_updated_at,\n updated_at\nFROM opportunities\nWHERE id IN (6211727, 7842553);\n\nSELECT * FROM opportunity_contacts\nWHERE opportunity_id = 6211727 AND contact_id = 10202724;\n\nSELECT id, name, stage_id, is_closed, is_won, updated_at, remotely_created_at\nFROM opportunities\nWHERE account_id = 8179134\nORDER BY updated_at DESC;\n\n\nselect * from text_relays where created_at > '2026-01-01';\nAND id IN (691, 692);\n\nselect * from teams;\n\n# ***************\nSELECT DISTINCT u.id, u.email, u.name, u.softphone_number, COUNT(a.id) as sms_count\nFROM users u\nINNER JOIN activities a ON u.id = a.user_id\nWHERE a.type LIKE 'sms%'\nAND a.created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)\nGROUP BY u.id, u.email, u.name, u.softphone_number\nORDER BY sms_count DESC;\n\nSELECT DISTINCT u.id, u.email, u.name, u.team_id, t.name as team_name,\n t.twilio_sms_sid, t.twilio_messaging_sid\nFROM users u\nINNER JOIN teams t ON u.team_id = t.id\nWHERE (t.twilio_sms_sid IS NOT NULL OR t.twilio_messaging_sid IS NOT NULL)\nAND u.status = 1\nORDER BY t.name, u.email;\n\nSELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, salesforce-admin@tourlane.com\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 = 187 and sa.provider = 'salesforce';\n\nselect * from activities where id = 31264367;\nselect * from contacts where id = 6331639;\nselect * from accounts where id = 4156632;\nselect * from opportunities where id = 4843610;\n# update `activities` set `account_id` = 4156632, `contact_id` = 6331639, `opportunity_id` = 4843610,\n# `stage_id` = 13273, `activities`.`updated_at` = 2026-05-22 07:16:17 where `id` = 31264367)\"\n\nselect * from text_relays where created_at > '2026-05-01';\n\nselect * from activities order by id desc;\n\nselect * from users where name like '%Subra%';\n\nSELECT * FROM opportunities WHERE uuid_to_bin('04a9cfad-2c87-4453-9e72-20aeb78ccf8d') = uuid;\nselect * from teams where id = 555;\nselect * from stages where team_id = 555;\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 = 100 and sa.provider = 'hubspot';","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.011968086,"top":0.047885075,"width":0.024268618,"height":0.024740623},"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}]...
|
6342989898062187878
|
2074961217668396653
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Code changed:
Hide
Sync Changes
Hide This Notification
31
9
29
3
109
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM team_features where team_id = 1;
SELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922
SELECT * FROM users WHERE team_id = 340; # 12015
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 340
and sa.provider = 'salesforce';
# and sa.provider = 'salesloft';
select * from crm_fields where crm_configuration_id = 270 and object_type = 'event';
# 125558 - Event Type - Event_Type__c
# 125552 - Event Status - Event_Status__c
SELECT * FROM sidekick_settings WHERE team_id = 340;
SELECT * FROM crm_field_values WHERE crm_field_id in (125552);
select * from activities where crm_configuration_id = 270
and type = 'conference' and crm_provider_id IS NOT NULL
and actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;
SELECT * FROM activities WHERE id = 20871677;
SELECT * FROM crm_field_data WHERE activity_id = 20871677;
select * from crm_layouts where crm_configuration_id = 270;
select * from crm_layout_entities where crm_layout_id in (886,887);
SELECT * FROM crm_configurations WHERE id = 270;
select * from playbooks where team_id = 340; # 1514
select * from groups where team_id = 340;
SELECT * FROM crm_fields WHERE id IN (125393, 125401);
select g.name as 'team name', p.name as 'playbook name', f.label as 'activity type field' from groups g
join playbooks p on g.playbook_id = p.id
join crm_fields f on p.activity_field_id = f.id
where g.team_id = 340;
SELECT * FROM activities WHERE uuid_to_bin('0c180357-67d2-419e-a8c3-b832a3490770') = uuid; # 20448716
select * from crm_field_data where object_id = 20448716;
select * from activities where crm_configuration_id = 270 and provider = 'salesloft' order by id desc;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%CybSafe%'; # 343,273,12008
select * from opportunities where team_id = 343;
select * from opportunities where team_id = 343 and crm_provider_id = '18099102526';
select * from opportunities where team_id = 343 and account_id = 945217482;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
select * from accounts where team_id = 343 order by name asc;
select * from stages where crm_configuration_id = 273 and type = 'opportunity';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Voyado%'; # 353,283,12143
SELECT * FROM activities WHERE crm_configuration_id = 283 and account_id = 3777844 order by id desc;
SELECT * FROM accounts WHERE team_id = 353 AND name LIKE '%Salesloft%';
SELECT * FROM activities WHERE id = 20717903;
select * from participants where activity_id IN (20929172,20928605,20928468,20926272,20926271,20926270,20926269,20916499,20916454,20916436,20916435,20900015,20900014,20900013,20897312,20897243,20897241,20897237,20897232,20897229,20893648,20893231,20893230,20893229,20893228,20889784,20885039,20885038,20885037,20885036,20885035,20882728,20882708,20882703,20882702,20869828,20869811,20869806,20869801,20869799,20869798,20869796,20869795,20869794,20869761,20869760,20869759,20868688,20868687,20850340,20847195,20841710,20833967,20827021,20825307,20825305,20825297,20824615,20824400,20823927,20821760,20795588,20794233,20794057,20793710,20785811,20781789,20781394,20781307,20762651,20758453,20758282,20757323,20756643,20756636,20756629,20756627,20756606,20756605,20756604,20756603,20756602,20756600,20756599,20756598,20756595,20756594,20756589,20756587,20756577,20756573,20748918,20748386,20748385,20748384,20748383,20748382,20748381,20748380,20748379,20748377,20748375,20748373,20743301,20717905,20717904,20717903,20717901,20717899);
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 353
and sa.provider = 'salesforce';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%modern world business solutions%'; # 345,275,12016, [EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('3921d399-3fef-4609-a291-b0097a166d43') = uuid;
# id: 20940638, user: 12022, contact: 5305871
SELECT * FROM activity_summary_logs WHERE activity_id = 20940638;
select * from contacts where team_id = 345 and crm_provider_id = '30891432415' order by name asc; # 5305871
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 345
and sa.provider = 'hubspot';
select * from users where team_id = 345 and id = 12022;
SELECT * FROM crm_profiles WHERE user_id = 12022;
SELECT * FROM participants WHERE activity_id = 20940638;
SELECT * FROM users u
JOIN crm_profiles cp ON u.id = cp.user_id
WHERE u.team_id = 345;
select * from contacts where team_id = 345 and crm_provider_id = '30880813535' order by name desc; # 5305871
select * from team_features where team_id = 345;
SELECT * FROM activities WHERE uuid_to_bin('11701e2d-2f82-4dab-a616-1db4fad238df') = uuid; # 21115197
SELECT * FROM participants WHERE activity_id = 20897406;
SELECT * FROM activities WHERE uuid_to_bin('63ba55cd-1abc-447d-83da-0137000005b7') = uuid; # 20953912
SELECT * FROM activities WHERE crm_configuration_id = 275 and provider = 'ringcentral' and title like '%1252629100%';
SELECT * FROM activities WHERE id = 20946641;
SELECT * FROM crm_profiles WHERE user_id = 10211;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120,97,10984, [EMAIL]
SELECT * FROM opportunities WHERE crm_configuration_id = 97 and crm_provider_id = '006N1000006c5PpIAI';
select * from stages where crm_configuration_id = 97 and type = 'opportunity';
select * from opportunities where team_id = 120;
select * from crm_configurations crm join teams t on crm.id = t.crm_id
where 1=1
AND t.current_billing_plan IS NOT NULL
AND crm.auto_sync_activity = 0
and crm.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Exclaimer%'; # 270,205,10053,[EMAIL]
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 270
and sa.provider = 'salesforce';
SELECT * FROM activities WHERE uuid_to_bin('b54df794-2a9a-4957-8d80-09a600ead5f8') = uuid; # 21637956
SELECT * FROM crm_profiles WHERE user_id = 11446;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Cygnetise%'; # 372,300,12554, [EMAIL]
select * from playbooks where team_id = 372;
select * from crm_fields where crm_configuration_id = 300 and object_type = 'event'; # 141340
SELECT * FROM crm_field_values WHERE crm_field_id = 141340;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 372
and sa.provider = 'salesforce';
select * from crm_profiles where crm_configuration_id = 300;
SELECT * FROM crm_configurations WHERE team_id = 372;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Planday%'; # 291,242,11501,[EMAIL]
SELECT * FROM opportunities WHERE team_id = 291 and crm_provider_id = '006bG000005DO86QAG'; # 3207756
select * from crm_field_data where object_id = 3207756;
SELECT * FROM crm_fields WHERE id = 111834;
select f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value
FROM crm_fields f
JOIN crm_field_data fd ON f.id = fd.crm_field_id
WHERE f.crm_configuration_id = 242
AND f.object_type = 'opportunity'
AND fd.object_id IN (3207756)
ORDER BY fd.object_id, fd.updated_at;
SELECT * FROM crm_configurations WHERE auto_connect = 1;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150,[EMAIL]
select * from group_deal_risk_types drgt join groups g on drgt.group_id = g.id
where g.team_id = 187;
select * from `groups` where team_id = 187;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 187
and sa.provider = 'salesforce';
# Destination - 98870 - Destination__c
# Stage - 79014 - StageName
# Land Arrangement - 98856 - Land_Arrangement__c
# Flight - 98848 - Flight__c
# Last activity date - 98812 - LastActivityDate
# Last modified date - 98809 - LastModifiedDate
# Last inbound mail timestamp - 99151 - Last_Inbound_Mail_Timestamp__c
# next call - 98864 - Next_Call__c
select * from crm_fields where crm_configuration_id = 209 and object_type = 'opportunity';
SELECT * FROM crm_layouts WHERE crm_configuration_id = 209;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;
select * from opportunities where team_id = 187 and name LIKE'%Muriel Sal%';
select * from opportunities where team_id = 187 and user_id = 9951 and is_closed = 0;
select * from activities where opportunity_id = 3538248;
SELECT * FROM crm_profiles WHERE user_id = 8150;
select * from deal_risks where opportunity_id = 3538248;
select * from teams where crm_id IS NULL;
SELECT opp.id AS opportunity_id,
u.group_id AS group_id,
MAX(
CASE
WHEN a.type IN ("sms-inbound", "sms-outbound") THEN a.created_at
ELSE a.actual_end_time
END) as last_date
FROM opportunities opp
left join activities a on a.opportunity_id = opp.id
inner join users u on opp.user_id = u.id
where opp.user_id IN (9951)
AND opp.is_closed = 0
and a.status IN ('completed', 'received', 'delivered') OR a.status IS NULL
group by opp.id;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Cybsafe%'; # 343,301,12008,[EMAIL]
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
SELECT * FROM crm_profiles WHERE crm_configuration_id = 301;
SELECT * FROM contacts WHERE id = 6612363;
SELECT * FROM accounts WHERE id = 4235676;
SELECT * FROM opportunities WHERE crm_configuration_id = 301 and crm_provider_id = 32983784868;
select * from opportunity_stages where opportunity_id = 4503759;
# SELECT * FROM opportunities WHERE id = 4569937;
select * from activities where crm_configuration_id = 301;
SELECT * FROM activities WHERE uuid_to_bin('d3b2b28b-c3d0-4c2d-8ed0-eef42855278a') = uuid; # 26330370
SELECT * FROM participants WHERE activity_id = 26330370;
SELECT * FROM teams WHERE id = 375;
select * from playbooks where team_id = 375;
select * from stages where crm_configuration_id = 301 and type = 'opportunity';
select * from teams;
select * from contact_roles;
SELECT * FROM opportunities WHERE team_id = 343 and user_id = 12871 and close_date >= '2024-11-01';
select * from users u join crm_profiles cp on cp.user_id = u.id where u.team_id = 343;
SELECT * FROM crm_field_data WHERE object_id = 3771706;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
SELECT * FROM crm_fields WHERE crm_configuration_id = 301 and object_type = 'opportunity'
and crm_provider_id LIKE "%traffic_light%";
SELECT * FROM crm_field_values WHERE crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531);
SELECT fd.* FROM opportunities o
JOIN crm_field_data fd ON o.id = fd.object_id
WHERE o.team_id = 343
# and o.user_id IS NOT NULL
and fd.crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531)
and fd.value != ''
order by value desc
# group by o.id
;
SELECT * FROM opportunities WHERE id = 3769843;
SELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150, [EMAIL]
SELECT * FROM crm_layouts WHERE crm_configuration_id = 209;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Funding Circle%'; # 220,177,8603,[EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('7a40e99b-3b37-4bb1-b983-325b81801c01') = uuid; # 23139839
SELECT * FROM opportunities WHERE id = 3855992;
SELECT * FROM users WHERE name LIKE '%Angus Pollard%'; # 8988
SELECT * FROM teams WHERE name LIKE '%Story Terrace%'; # 379, 307, 12894
SELECT * FROM crm_fields WHERE crm_configuration_id = 307 and object_type != 'opportunity';
select * from contacts where team_id = 379 and name like '%bebro%'; # 5874411, crm: 77229348507
SELECT * FROM crm_field_data WHERE object_id = 5874411;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 379
and sa.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%mentio%'; # 117, 94, 6371, [EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('82939311-1af0-4506-8546-21e8d1fdf2c1') = uuid;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, [EMAIL]
SELECT * FROM opportunities WHERE team_id = 187 and crm_provider_id = '006Se000008xfvNIAQ'; # 3537793
select * from generic_ai_prompts where subject_id = 3537793;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120, 97, 10984, [EMAIL]
SELECT * FROM crm_configurations WHERE id = 97;
SELECT * FROM crm_layouts WHERE crm_configuration_id = 97;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 355;
SELECT * FROM crm_fields WHERE id = 32682;
select cfd.value, o.* from opportunities o
join crm_field_data cfd on o.id = cfd.object_id and cfd.crm_field_id = 32682
where team_id = 120
and cfd.value != ''
;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 120
and sa.provider = 'salesforce';
select * from opportunities where team_id = 120 and crm_provider_id = '006N1000007X8MAIA0';
SELECT * FROM crm_field_data WHERE object_id = 2313439;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE id = 410;
SELECT * FROM teams WHERE name LIKE '%Local Business Oxford%';
select * from scorecards where team_id = 410;
select * from scorecard_rules;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Funding%'; # 220, 177, 8603, [EMAIL]
select * from activities a
join opportunities o on a.opportunity_id = o.id
join users u on o.user_id = u.id
where a.crm_configuration_id = 177 and a.type LIKE '%email-out%'
# and a.actual_end_time > '2024-12-16 00:00:00'
# and o.remotely_created_at > '2024-12-01 00:00:00'
# and u.group_id = 1014
and u.id = 9021
order by a.id desc;
SELECT * FROM opportunities WHERE id in (3981384,4017346);
SELECT * FROM users WHERE team_id = 220 and id IN (8775, 11435);
select * from users where id = 9021;
select * from inboxes where user_id = 9021;
select * from inbox_emails where inbox_id = 1349 and email_date > '2024-12-18 00:00:00';
select * from email_messages where team_id = 220
and orig_date > '2024-12-16 00:00:00' and orig_date < '2024-12-19 00:00:00'
and subject LIKE '%Personal%'
# and 'from' = '[EMAIL]'
;
select * from activities a
join opportunities o on a.opportunity_id = o.id
where a.user_id = 9021 and a.type LIKE '%email-out%'
and a.actual_end_time > '2024-12-18 00:00:00'
and o.user_id IS NOT NULL
and o.remotely_created_at > '2024-12-01 00:00:00'
order by a.id desc;
SELECT * FROM opportunities WHERE team_id = 220 and name LIKE '%Right Car move Limited%' and id = 3966852;
select * from activities where crm_configuration_id = 177 and type LIKE '%email%' and opportunity_id = 3966852 order by id desc;
select * from team_settings where name IN ('useCloseDate');
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Hurree%'; # 104, 81, 6175, [EMAIL]
SELECT * FROM opportunities WHERE team_id = 104 and name = 'PropOp';
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 104
and sa.provider = 'hubspot';
select * from crm_configurations where last_synced_at > '2025-01-19 01:00:00'
select * from teams where crm_id IS NULL;
select t.name as 'team', u.name as 'owner', u.email, u.phone
from teams t
join activity_providers ap on t.id = ap.team_id
join users u on t.owner_id = u.id
where 1=1
and t.status = 'active'
and ap.is_enabled = 1
# and u.status = 1
and ap.provider = 'ms-teams';
select * from crm_configurations where provider = 'bullhorn'; # 344
SELECT * FROM teams WHERE id = 442; # 14293
select * from users where team_id = 442;
select * from social_accounts sa where sa.sociable_id = 14293;
select * from invitations where team_id = 442;
# [PASSWORD_DOTS]
SELECT * FROM users WHERE email LIKE '%[EMAIL]%'; # 14022
SELECT * FROM teams WHERE id = 429;
select * from opportunities where team_id = 429 and crm_provider_id IN (16157415775, 22246219645);
select * from activities where opportunity_id in (4340436,4353519);
select * from transcription where activity_id IN (25630961,25381771);
select * from generic_ai_prompts where subject_id IN (4353519);
SELECT
a.id as activity_id,
a.opportunity_id,
a.type as activity_type,
a.language,
CONCAT(a.title, a.description) AS mail_content,
e.from AS mail_from,
e.to AS mail_to,
e.subject AS mail_subject,
e.body AS mail_body,
p.type as prompt_type,
p.status as prompt_status,
p.content AS prompt_content,
a.actual_start_time as created_at
FROM activities a
LEFT JOIN ai_prompts p ON a.transcription_id = p.transcription_id AND p.deleted_at IS NULL
LEFT JOIN email_messages e ON a.id = e.activity_id
WHERE a.actual_start_time > '2024-01-01 00:00:00'
AND a.opportunity_id IN (4353519)
AND a.status IN ('completed', 'received', 'delivered')
AND a.deleted_at IS NULL
AND a.type NOT IN ('sms-inbound', 'sms-outbound')
ORDER BY a.opportunity_id ASC, a.id ASC;
SELECT * FROM users WHERE name LIKE '%George Fierstone%'; # 14293
SELECT * FROM teams WHERE id = 442;
SELECT * FROM crm_configurations WHERE id = 344;
select * from team_features where team_id = 442;
select * from groups where team_id = 442;
select * from playbooks where team_id = 442;
select * from playbook_categories where playbook_id = 1729;
select * from crm_fields where crm_configuration_id = 344 and id = 172024;
SELECT * FROM crm_field_values WHERE crm_field_id = 172024;
select * from crm_layouts where crm_configuration_id = 344;
select * from playbook_layouts where playbook_id = 1729;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 221, 9444
select s.*
# , s.sent_at, u.name, a.*
from activity_summary_logs s
inner join activities a on a.id = s.activity_id
inner join users u on u.id = a.user_id
where a.crm_configuration_id = 356
and s.sent_at > date_sub(now(), interval 60 day)
order by a.actual_end_time desc;
select * from activities a
# inner join activity_summary_logs s on s.activity_id = a.id
where a.crm_configuration_id = 356 and a.actual_end_time > date_sub(now(), interval 60 day)
# and a.crm_provider_id is not null
# and provider <> 'ringcentral'
and status = 'completed'
order by a.actual_end_time desc;
select * from teams order by id desc; # 17328, 32, 17830, [EMAIL]
SELECT * FROM users;
SELECT * FROM users where team_id = 260 and status = 1; # 201 - 150 active
SELECT * FROM teams WHERE id = 260;
select * from team_settings where team_id = 260;
select * from crm_configurations where team_id = 260;
SELECT * FROM crm_layouts WHERE crm_configuration_id = 356;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1184;
select * from accounts where crm_configuration_id = 221 order by id desc; # 7000
select * from leads where crm_configuration_id = 221 order by id desc; # 0
select * from contacts where crm_configuration_id = 221 order by id desc; # 200 000
select * from opportunities where crm_configuration_id = 221 order by id desc; # 0
select * from crm_profiles where crm_configuration_id = 221 order by id desc; # 23
select * from crm_fields where crm_configuration_id = 221;
select * from crm_field_values where crm_field_id = 5302 order by id desc;
select * from crm_layouts where crm_configuration_id = 221 order by id desc;
select * from stages where crm_configuration_id = 221 order by id desc;
select * from accounts where crm_configuration_id = 356 order by id desc; # 7000
select * from leads where crm_configuration_id = 356 order by id desc; # 0
select * from contacts where crm_configuration_id = 356 order by id desc; # 200 000
select * from opportunities where crm_configuration_id = 356 order by id desc; # 0
select * from crm_profiles where crm_configuration_id = 356 order by id desc; # 23
select * from crm_fields where crm_configuration_id = 356;
select * from crm_field_values where crm_field_id = 5302 order by id desc;
select * from crm_layouts where crm_configuration_id = 356 order by id desc;
select * from stages where crm_configuration_id = 356 order by id desc;
select * from playbooks where team_id = 260 order by id desc; # 4 (2 deleted)
select * from groups where team_id = 260 order by id desc; # 27 groups, (2 deleted)
select * from playbook_layouts where playbook_id IN (1410,1409,1276,1254); # 4
select ce.* from calendars c
join users u on c.user_id = u.id
join calendar_events ce on c.id = ce.calendar_id
where u.team_id = 260
and (ce.start_time > '2025-02-21 00:00:00')
;
# calendar events 1207
#
select * from opportunities where team_id = 260;
SELECT * FROM crm_field_data WHERE object_id = 4696496;
select * from activities where crm_configuration_id = 356 and crm_provider_id IS NOT NULL;
select * from activities where crm_configuration_id IN (221) and provider NOT IN ('ms-teams', 'uploader', 'zoom-bot')
# and type = 'conference' and status = 'scheduled' and activities.is_internal = 0
and created_at > '2024-03-01 00:00:00'
order by id desc; # 880 000, ringcentral, avaya
SELECT * FROM participants WHERE activity_id = 26371744;
# all activities 942 000 +
# conference 7385 - scheduled 984 - external 343
select * from activities where id = 26321812;
select * from participants where activity_id = 26321812;
select * from participants where activity_id in (26414510,26414514,26414516,26414604,26414653,26414655);
select * from leads where id in (720428,689175,731546,645866,621037);
select * from users where id = 13841;
select * from opportunities where user_id = 9541;
select * from stages where id = 15900;
select * from accounts where
# id IN (4160055,5053725,4965303,4896434)
id in (4584518,3249934,3218025,3891133,3399450,4172999,4485161,3101785,4587203,3070816,2870343,2870341,3563940,4550846,3424464,3249963,2870342)
;
select * from activities where id = 26654935;
SELECT * FROM opportunities WHERE id = 4803458;
SELECT * FROM opportunities where team_id = 260 and user_id = 13841 AND stage_id = 15900;
SELECT id, uuid, provider, type, lead_id, account_id, contact_id, opportunity_id, stage_id, status, recording_state, title, actual_start_time, actual_end_time
FROM activities WHERE user_id = 13841 AND opportunity_id IN (4729783, 4731717, 4731726, 4732064, 4732849, 4803458, 4813213);
SELECT DISTINCT
o.id, o.stage_id, s.name, a.title,
a.*
FROM activities a
# INNER JOIN tracks t ON a.id = t.activity_id
INNER JOIN users u ON a.user_id = u.id
INNER JOIN teams team ON u.team_id = team.id
INNER JOIN groups g ON u.group_id = g.id
INNER JOIN opportunities o ON a.opportunity_id = o.id
INNER JOIN stages s ON o.stage_id = s.id
WHERE
a.crm_configuration_id = 356
AND a.status IN ('completed', 'failed')
AND a.recording_state != 'stopped'
# and a.user_id = 13841
AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')
AND team.uuid = uuid_to_bin('a607fba7-452e-4683-b2af-00d6cb52c93c')
AND g.uuid = uuid_to_bin('b5d69e40-24a0-4c16-810b-5fa462299f94')
AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')
# AND t.type IN ('audio', 'video')
AND (
(a.actual_start_time BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59')
OR
(
a.actual_start_time IS NULL
AND a.type IN ('sms-outbound', 'sms-inbound')
AND a.created_at BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59'
)
)
AND (
a.is_private = 0
OR (
a.is_private = 1
AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')
)
)
AND (
# s.id = 15900
s.uuid = uuid_to_bin('04ca1c26-c666-4268-a129-419c0acffd73')
OR s.uuid IS NULL -- Include records without opportunity stage
)
ORDER BY a.actual_end_time DESC;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lead Forensics%'; # 190, 162, 8474, [EMAIL]
SELECT * FROM users WHERE team_id = 190;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 190
and sa.provider = 'hubspot';
select * from role_user where user_id = 8474;
select * from crm_configurations where provider = 'bullhorn';
SELECT * FROM opportunities WHERE uuid_to_bin('94578249-65ec-4205-90f2-7d1a7d5ab64a') = uuid;
SELECT * FROM users WHERE uuid_to_bin('26dbadeb-926f-4150-b11b-771b9d4c2f9a') = uuid;
SELECT * FROM opportunities ...
|
87829
|
NULL
|
NULL
|
NULL
|
|
87829
|
3001
|
3
|
2026-05-28T16:25:27.449194+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985527449_m2.jpg...
|
PhpStorm
|
faVsco.js – console [EU]
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Execute
Explain Plan...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"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,"bounds":{"left":0.36635637,"top":0.17478053,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","depth":4,"bounds":{"left":0.37632978,"top":0.17478053,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.3879654,"top":0.17318435,"width":0.00731383,"height":0.018355945},"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.39527926,"top":0.17318435,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.4039229,"top":0.09896249,"width":0.008643617,"height":0.01915403},"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.41256648,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
4589348572896545516
|
1349907989169126020
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Execute
Explain Plan...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87828
|
3001
|
2
|
2026-05-28T16:25:17.341954+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985517341_m2.jpg...
|
PhpStorm
|
faVsco.js – console [EU]
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Code changed:
Hide
Sync Changes
Hide This Notification
31
9
29
3
109
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM team_features where team_id = 1;
SELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922
SELECT * FROM users WHERE team_id = 340; # 12015
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 340
and sa.provider = 'salesforce';
# and sa.provider = 'salesloft';
select * from crm_fields where crm_configuration_id = 270 and object_type = 'event';
# 125558 - Event Type - Event_Type__c
# 125552 - Event Status - Event_Status__c
SELECT * FROM sidekick_settings WHERE team_id = 340;
SELECT * FROM crm_field_values WHERE crm_field_id in (125552);
select * from activities where crm_configuration_id = 270
and type = 'conference' and crm_provider_id IS NOT NULL
and actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;
SELECT * FROM activities WHERE id = 20871677;
SELECT * FROM crm_field_data WHERE activity_id = 20871677;
select * from crm_layouts where crm_configuration_id = 270;
select * from crm_layout_entities where crm_layout_id in (886,887);
SELECT * FROM crm_configurations WHERE id = 270;
select * from playbooks where team_id = 340; # 1514
select * from groups where team_id = 340;
SELECT * FROM crm_fields WHERE id IN (125393, 125401);
select g.name as 'team name', p.name as 'playbook name', f.label as 'activity type field' from groups g
join playbooks p on g.playbook_id = p.id
join crm_fields f on p.activity_field_id = f.id
where g.team_id = 340;
SELECT * FROM activities WHERE uuid_to_bin('0c180357-67d2-419e-a8c3-b832a3490770') = uuid; # 20448716
select * from crm_field_data where object_id = 20448716;
select * from activities where crm_configuration_id = 270 and provider = 'salesloft' order by id desc;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%CybSafe%'; # 343,273,12008
select * from opportunities where team_id = 343;
select * from opportunities where team_id = 343 and crm_provider_id = '18099102526';
select * from opportunities where team_id = 343 and account_id = 945217482;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
select * from accounts where team_id = 343 order by name asc;
select * from stages where crm_configuration_id = 273 and type = 'opportunity';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Voyado%'; # 353,283,12143
SELECT * FROM activities WHERE crm_configuration_id = 283 and account_id = 3777844 order by id desc;
SELECT * FROM accounts WHERE team_id = 353 AND name LIKE '%Salesloft%';
SELECT * FROM activities WHERE id = 20717903;
select * from participants where activity_id IN (20929172,20928605,20928468,20926272,20926271,20926270,20926269,20916499,20916454,20916436,20916435,20900015,20900014,20900013,20897312,20897243,20897241,20897237,20897232,20897229,20893648,20893231,20893230,20893229,20893228,20889784,20885039,20885038,20885037,20885036,20885035,20882728,20882708,20882703,20882702,20869828,20869811,20869806,20869801,20869799,20869798,20869796,20869795,20869794,20869761,20869760,20869759,20868688,20868687,20850340,20847195,20841710,20833967,20827021,20825307,20825305,20825297,20824615,20824400,20823927,20821760,20795588,20794233,20794057,20793710,20785811,20781789,20781394,20781307,20762651,20758453,20758282,20757323,20756643,20756636,20756629,20756627,20756606,20756605,20756604,20756603,20756602,20756600,20756599,20756598,20756595,20756594,20756589,20756587,20756577,20756573,20748918,20748386,20748385,20748384,20748383,20748382,20748381,20748380,20748379,20748377,20748375,20748373,20743301,20717905,20717904,20717903,20717901,20717899);
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 353
and sa.provider = 'salesforce';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%modern world business solutions%'; # 345,275,12016, [EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('3921d399-3fef-4609-a291-b0097a166d43') = uuid;
# id: 20940638, user: 12022, contact: 5305871
SELECT * FROM activity_summary_logs WHERE activity_id = 20940638;
select * from contacts where team_id = 345 and crm_provider_id = '30891432415' order by name asc; # 5305871
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 345
and sa.provider = 'hubspot';
select * from users where team_id = 345 and id = 12022;
SELECT * FROM crm_profiles WHERE user_id = 12022;
SELECT * FROM participants WHERE activity_id = 20940638;
SELECT * FROM users u
JOIN crm_profiles cp ON u.id = cp.user_id
WHERE u.team_id = 345;
select * from contacts where team_id = 345 and crm_provider_id = '30880813535' order by name desc; # 5305871
select * from team_features where team_id = 345;
SELECT * FROM activities WHERE uuid_to_bin('11701e2d-2f82-4dab-a616-1db4fad238df') = uuid; # 21115197
SELECT * FROM participants WHERE activity_id = 20897406;
SELECT * FROM activities WHERE uuid_to_bin('63ba55cd-1abc-447d-83da-0137000005b7') = uuid; # 20953912
SELECT * FROM activities WHERE crm_configuration_id = 275 and provider = 'ringcentral' and title like '%1252629100%';
SELECT * FROM activities WHERE id = 20946641;
SELECT * FROM crm_profiles WHERE user_id = 10211;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120,97,10984, [EMAIL]
SELECT * FROM opportunities WHERE crm_configuration_id = 97 and crm_provider_id = '006N1000006c5PpIAI';
select * from stages where crm_configuration_id = 97 and type = 'opportunity';
select * from opportunities where team_id = 120;
select * from crm_configurations crm join teams t on crm.id = t.crm_id
where 1=1
AND t.current_billing_plan IS NOT NULL
AND crm.auto_sync_activity = 0
and crm.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Exclaimer%'; # 270,205,10053,[EMAIL]
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 270
and sa.provider = 'salesforce';
SELECT * FROM activities WHERE uuid_to_bin('b54df794-2a9a-4957-8d80-09a600ead5f8') = uuid; # 21637956
SELECT * FROM crm_profiles WHERE user_id = 11446;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Cygnetise%'; # 372,300,12554, [EMAIL]
select * from playbooks where team_id = 372;
select * from crm_fields where crm_configuration_id = 300 and object_type = 'event'; # 141340
SELECT * FROM crm_field_values WHERE crm_field_id = 141340;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 372
and sa.provider = 'salesforce';
select * from crm_profiles where crm_configuration_id = 300;
SELECT * FROM crm_configurations WHERE team_id = 372;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Planday%'; # 291,242,11501,[EMAIL]
SELECT * FROM opportunities WHERE team_id = 291 and crm_provider_id = '006bG000005DO86QAG'; # 3207756
select * from crm_field_data where object_id = 3207756;
SELECT * FROM crm_fields WHERE id = 111834;
select f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value
FROM crm_fields f
JOIN crm_field_data fd ON f.id = fd.crm_field_id
WHERE f.crm_configuration_id = 242
AND f.object_type = 'opportunity'
AND fd.object_id IN (3207756)
ORDER BY fd.object_id, fd.updated_at;
SELECT * FROM crm_configurations WHERE auto_connect = 1;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150,[EMAIL]
select * from group_deal_risk_types drgt join groups g on drgt.group_id = g.id
where g.team_id = 187;
select * from `groups` where team_id = 187;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 187
and sa.provider = 'salesforce';
# Destination - 98870 - Destination__c
# Stage - 79014 - StageName
# Land Arrangement - 98856 - Land_Arrangement__c
# Flight - 98848 - Flight__c
# Last activity date - 98812 - LastActivityDate
# Last modified date - 98809 - LastModifiedDate
# Last inbound mail timestamp - 99151 - Last_Inbound_Mail_Timestamp__c
# next call - 98864 - Next_Call__c
select * from crm_fields where crm_configuration_id = 209 and object_type = 'opportunity';
SELECT * FROM crm_layouts WHERE crm_configuration_id = 209;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;
select * from opportunities where team_id = 187 and name LIKE'%Muriel Sal%';
select * from opportunities where team_id = 187 and user_id = 9951 and is_closed = 0;
select * from activities where opportunity_id = 3538248;
SELECT * FROM crm_profiles WHERE user_id = 8150;
select * from deal_risks where opportunity_id = 3538248;
select * from teams where crm_id IS NULL;
SELECT opp.id AS opportunity_id,
u.group_id AS group_id,
MAX(
CASE
WHEN a.type IN ("sms-inbound", "sms-outbound") THEN a.created_at
ELSE a.actual_end_time
END) as last_date
FROM opportunities opp
left join activities a on a.opportunity_id = opp.id
inner join users u on opp.user_id = u.id
where opp.user_id IN (9951)
AND opp.is_closed = 0
and a.status IN ('completed', 'received', 'delivered') OR a.status IS NULL
group by opp.id;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Cybsafe%'; # 343,301,12008,[EMAIL]
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
SELECT * FROM crm_profiles WHERE crm_configuration_id = 301;
SELECT * FROM contacts WHERE id = 6612363;
SELECT * FROM accounts WHERE id = 4235676;
SELECT * FROM opportunities WHERE crm_configuration_id = 301 and crm_provider_id = 32983784868;
select * from opportunity_stages where opportunity_id = 4503759;
# SELECT * FROM opportunities WHERE id = 4569937;
select * from activities where crm_configuration_id = 301;
SELECT * FROM activities WHERE uuid_to_bin('d3b2b28b-c3d0-4c2d-8ed0-eef42855278a') = uuid; # 26330370
SELECT * FROM participants WHERE activity_id = 26330370;
SELECT * FROM teams WHERE id = 375;
select * from playbooks where team_id = 375;
select * from stages where crm_configuration_id = 301 and type = 'opportunity';
select * from teams;
select * from contact_roles;
SELECT * FROM opportunities WHERE team_id = 343 and user_id = 12871 and close_date >= '2024-11-01';
select * from users u join crm_profiles cp on cp.user_id = u.id where u.team_id = 343;
SELECT * FROM crm_field_data WHERE object_id = 3771706;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
SELECT * FROM crm_fields WHERE crm_configuration_id = 301 and object_type = 'opportunity'
and crm_provider_id LIKE "%traffic_light%";
SELECT * FROM crm_field_values WHERE crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531);
SELECT fd.* FROM opportunities o
JOIN crm_field_data fd ON o.id = fd.object_id
WHERE o.team_id = 343
# and o.user_id IS NOT NULL
and fd.crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531)
and fd.value != ''
order by value desc
# group by o.id
;
SELECT * FROM opportunities WHERE id = 3769843;
SELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150, [EMAIL]
SELECT * FROM crm_layouts WHERE crm_configuration_id = 209;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Funding Circle%'; # 220,177,8603,[EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('7a40e99b-3b37-4bb1-b983-325b81801c01') = uuid; # 23139839
SELECT * FROM opportunities WHERE id = 3855992;
SELECT * FROM users WHERE name LIKE '%Angus Pollard%'; # 8988
SELECT * FROM teams WHERE name LIKE '%Story Terrace%'; # 379, 307, 12894
SELECT * FROM crm_fields WHERE crm_configuration_id = 307 and object_type != 'opportunity';
select * from contacts where team_id = 379 and name like '%bebro%'; # 5874411, crm: 77229348507
SELECT * FROM crm_field_data WHERE object_id = 5874411;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 379
and sa.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%mentio%'; # 117, 94, 6371, [EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('82939311-1af0-4506-8546-21e8d1fdf2c1') = uuid;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, [EMAIL]
SELECT * FROM opportunities WHERE team_id = 187 and crm_provider_id = '006Se000008xfvNIAQ'; # 3537793
select * from generic_ai_prompts where subject_id = 3537793;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120, 97, 10984, [EMAIL]
SELECT * FROM crm_configurations WHERE id = 97;
SELECT * FROM crm_layouts WHERE crm_configuration_id = 97;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 355;
SELECT * FROM crm_fields WHERE id = 32682;
select cfd.value, o.* from opportunities o
join crm_field_data cfd on o.id = cfd.object_id and cfd.crm_field_id = 32682
where team_id = 120
and cfd.value != ''
;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 120
and sa.provider = 'salesforce';
select * from opportunities where team_id = 120 and crm_provider_id = '006N1000007X8MAIA0';
SELECT * FROM crm_field_data WHERE object_id = 2313439;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE id = 410;
SELECT * FROM teams WHERE name LIKE '%Local Business Oxford%';
select * from scorecards where team_id = 410;
select * from scorecard_rules;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Funding%'; # 220, 177, 8603, [EMAIL]
select * from activities a
join opportunities o on a.opportunity_id = o.id
join users u on o.user_id = u.id
where a.crm_configuration_id = 177 and a.type LIKE '%email-out%'
# and a.actual_end_time > '2024-12-16 00:00:00'
# and o.remotely_created_at > '2024-12-01 00:00:00'
# and u.group_id = 1014
and u.id = 9021
order by a.id desc;
SELECT * FROM opportunities WHERE id in (3981384,4017346);
SELECT * FROM users WHERE team_id = 220 and id IN (8775, 11435);
select * from users where id = 9021;
select * from inboxes where user_id = 9021;
select * from inbox_emails where inbox_id = 1349 and email_date > '2024-12-18 00:00:00';
select * from email_messages where team_id = 220
and orig_date > '2024-12-16 00:00:00' and orig_date < '2024-12-19 00:00:00'
and subject LIKE '%Personal%'
# and 'from' = '[EMAIL]'
;
select * from activities a
join opportunities o on a.opportunity_id = o.id
where a.user_id = 9021 and a.type LIKE '%email-out%'
and a.actual_end_time > '2024-12-18 00:00:00'
and o.user_id IS NOT NULL
and o.remotely_created_at > '2024-12-01 00:00:00'
order by a.id desc;
SELECT * FROM opportunities WHERE team_id = 220 and name LIKE '%Right Car move Limited%' and id = 3966852;
select * from activities where crm_configuration_id = 177 and type LIKE '%email%' and opportunity_id = 3966852 order by id desc;
select * from team_settings where name IN ('useCloseDate');
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Hurree%'; # 104, 81, 6175, [EMAIL]
SELECT * FROM opportunities WHERE team_id = 104 and name = 'PropOp';
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 104
and sa.provider = 'hubspot';
select * from crm_configurations where last_synced_at > '2025-01-19 01:00:00'
select * from teams where crm_id IS NULL;
select t.name as 'team', u.name as 'owner', u.email, u.phone
from teams t
join activity_providers ap on t.id = ap.team_id
join users u on t.owner_id = u.id
where 1=1
and t.status = 'active'
and ap.is_enabled = 1
# and u.status = 1
and ap.provider = 'ms-teams';
select * from crm_configurations where provider = 'bullhorn'; # 344
SELECT * FROM teams WHERE id = 442; # 14293
select * from users where team_id = 442;
select * from social_accounts sa where sa.sociable_id = 14293;
select * from invitations where team_id = 442;
# [PASSWORD_DOTS]
SELECT * FROM users WHERE email LIKE '%[EMAIL]%'; # 14022
SELECT * FROM teams WHERE id = 429;
select * from opportunities where team_id = 429 and crm_provider_id IN (16157415775, 22246219645);
select * from activities where opportunity_id in (4340436,4353519);
select * from transcription where activity_id IN (25630961,25381771);
select * from generic_ai_prompts where subject_id IN (4353519);
SELECT
a.id as activity_id,
a.opportunity_id,
a.type as activity_type,
a.language,
CONCAT(a.title, a.description) AS mail_content,
e.from AS mail_from,
e.to AS mail_to,
e.subject AS mail_subject,
e.body AS mail_body,
p.type as prompt_type,
p.status as prompt_status,
p.content AS prompt_content,
a.actual_start_time as created_at
FROM activities a
LEFT JOIN ai_prompts p ON a.transcription_id = p.transcription_id AND p.deleted_at IS NULL
LEFT JOIN email_messages e ON a.id = e.activity_id
WHERE a.actual_start_time > '2024-01-01 00:00:00'
AND a.opportunity_id IN (4353519)
AND a.status IN ('completed', 'received', 'delivered')
AND a.deleted_at IS NULL
AND a.type NOT IN ('sms-inbound', 'sms-outbound')
ORDER BY a.opportunity_id ASC, a.id ASC;
SELECT * FROM users WHERE name LIKE '%George Fierstone%'; # 14293
SELECT * FROM teams WHERE id = 442;
SELECT * FROM crm_configurations WHERE id = 344;
select * from team_features where team_id = 442;
select * from groups where team_id = 442;
select * from playbooks where team_id = 442;
select * from playbook_categories where playbook_id = 1729;
select * from crm_fields where crm_configuration_id = 344 and id = 172024;
SELECT * FROM crm_field_values WHERE crm_field_id = 172024;
select * from crm_layouts where crm_configuration_id = 344;
select * from playbook_layouts where playbook_id = 1729;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 221, 9444
select s.*
# , s.sent_at, u.name, a.*
from activity_summary_logs s
inner join activities a on a.id = s.activity_id
inner join users u on u.id = a.user_id
where a.crm_configuration_id = 356
and s.sent_at > date_sub(now(), interval 60 day)
order by a.actual_end_time desc;
select * from activities a
# inner join activity_summary_logs s on s.activity_id = a.id
where a.crm_configuration_id = 356 and a.actual_end_time > date_sub(now(), interval 60 day)
# and a.crm_provider_id is not null
# and provider <> 'ringcentral'
and status = 'completed'
order by a.actual_end_time desc;
select * from teams order by id desc; # 17328, 32, 17830, [EMAIL]
SELECT * FROM users;
SELECT * FROM users where team_id = 260 and status = 1; # 201 - 150 active
SELECT * FROM teams WHERE id = 260;
select * from team_settings where team_id = 260;
select * from crm_configurations where team_id = 260;
SELECT * FROM crm_layouts WHERE crm_configuration_id = 356;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1184;
select * from accounts where crm_configuration_id = 221 order by id desc; # 7000
select * from leads where crm_configuration_id = 221 order by id desc; # 0
select * from contacts where crm_configuration_id = 221 order by id desc; # 200 000
select * from opportunities where crm_configuration_id = 221 order by id desc; # 0
select * from crm_profiles where crm_configuration_id = 221 order by id desc; # 23
select * from crm_fields where crm_configuration_id = 221;
select * from crm_field_values where crm_field_id = 5302 order by id desc;
select * from crm_layouts where crm_configuration_id = 221 order by id desc;
select * from stages where crm_configuration_id = 221 order by id desc;
select * from accounts where crm_configuration_id = 356 order by id desc; # 7000
select * from leads where crm_configuration_id = 356 order by id desc; # 0
select * from contacts where crm_configuration_id = 356 order by id desc; # 200 000
select * from opportunities where crm_configuration_id = 356 order by id desc; # 0
select * from crm_profiles where crm_configuration_id = 356 order by id desc; # 23
select * from crm_fields where crm_configuration_id = 356;
select * from crm_field_values where crm_field_id = 5302 order by id desc;
select * from crm_layouts where crm_configuration_id = 356 order by id desc;
select * from stages where crm_configuration_id = 356 order by id desc;
select * from playbooks where team_id = 260 order by id desc; # 4 (2 deleted)
select * from groups where team_id = 260 order by id desc; # 27 groups, (2 deleted)
select * from playbook_layouts where playbook_id IN (1410,1409,1276,1254); # 4
select ce.* from calendars c
join users u on c.user_id = u.id
join calendar_events ce on c.id = ce.calendar_id
where u.team_id = 260
and (ce.start_time > '2025-02-21 00:00:00')
;
# calendar events 1207
#
select * from opportunities where team_id = 260;
SELECT * FROM crm_field_data WHERE object_id = 4696496;
select * from activities where crm_configuration_id = 356 and crm_provider_id IS NOT NULL;
select * from activities where crm_configuration_id IN (221) and provider NOT IN ('ms-teams', 'uploader', 'zoom-bot')
# and type = 'conference' and status = 'scheduled' and activities.is_internal = 0
and created_at > '2024-03-01 00:00:00'
order by id desc; # 880 000, ringcentral, avaya
SELECT * FROM participants WHERE activity_id = 26371744;
# all activities 942 000 +
# conference 7385 - scheduled 984 - external 343
select * from activities where id = 26321812;
select * from participants where activity_id = 26321812;
select * from participants where activity_id in (26414510,26414514,26414516,26414604,26414653,26414655);
select * from leads where id in (720428,689175,731546,645866,621037);
select * from users where id = 13841;
select * from opportunities where user_id = 9541;
select * from stages where id = 15900;
select * from accounts where
# id IN (4160055,5053725,4965303,4896434)
id in (4584518,3249934,3218025,3891133,3399450,4172999,4485161,3101785,4587203,3070816,2870343,2870341,3563940,4550846,3424464,3249963,2870342)
;
select * from activities where id = 26654935;
SELECT * FROM opportunities WHERE id = 4803458;
SELECT * FROM opportunities where team_id = 260 and user_id = 13841 AND stage_id = 15900;
SELECT id, uuid, provider, type, lead_id, account_id, contact_id, opportunity_id, stage_id, status, recording_state, title, actual_start_time, actual_end_time
FROM activities WHERE user_id = 13841 AND opportunity_id IN (4729783, 4731717, 4731726, 4732064, 4732849, 4803458, 4813213);
SELECT DISTINCT
o.id, o.stage_id, s.name, a.title,
a.*
FROM activities a
# INNER JOIN tracks t ON a.id = t.activity_id
INNER JOIN users u ON a.user_id = u.id
INNER JOIN teams team ON u.team_id = team.id
INNER JOIN groups g ON u.group_id = g.id
INNER JOIN opportunities o ON a.opportunity_id = o.id
INNER JOIN stages s ON o.stage_id = s.id
WHERE
a.crm_configuration_id = 356
AND a.status IN ('completed', 'failed')
AND a.recording_state != 'stopped'
# and a.user_id = 13841
AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')
AND team.uuid = uuid_to_bin('a607fba7-452e-4683-b2af-00d6cb52c93c')
AND g.uuid = uuid_to_bin('b5d69e40-24a0-4c16-810b-5fa462299f94')
AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')
# AND t.type IN ('audio', 'video')
AND (
(a.actual_start_time BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59')
OR
(
a.actual_start_time IS NULL
AND a.type IN ('sms-outbound', 'sms-inbound')
AND a.created_at BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59'
)
)
AND (
a.is_private = 0
OR (
a.is_private = 1
AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')
)
)
AND (
# s.id = 15900
s.uuid = uuid_to_bin('04ca1c26-c666-4268-a129-419c0acffd73')
OR s.uuid IS NULL -- Include records without opportunity stage
)
ORDER BY a.actual_end_time DESC;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lead Forensics%'; # 190, 162, 8474, [EMAIL]
SELECT * FROM users WHERE team_id = 190;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 190
and sa.provider = 'hubspot';
select * from role_user where user_id = 8474;
select * from crm_configurations where provider = 'bullhorn';
SELECT * FROM opportunities WHERE uuid_to_bin('94578249-65ec-4205-90f2-7d1a7d5ab64a') = uuid;
SELECT * FROM users WHERE uuid_to_bin('26dbadeb-926f-4150-b11b-771b9d4c2f9a') = uuid;
SELECT * FROM opportunities ...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"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,"bounds":{"left":0.36635637,"top":0.17478053,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","depth":4,"bounds":{"left":0.37632978,"top":0.17478053,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.3879654,"top":0.17318435,"width":0.00731383,"height":0.018355945},"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.39527926,"top":0.17318435,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.4039229,"top":0.09896249,"width":0.008643617,"height":0.01915403},"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.41256648,"top":0.09896249,"width":0.008643617,"height":0.01915403},"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,"bounds":{"left":0.42353722,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"bounds":{"left":0.43218085,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"bounds":{"left":0.44082448,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"bounds":{"left":0.45179522,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"bounds":{"left":0.46276596,"top":0.09896249,"width":0.024268618,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"bounds":{"left":0.4893617,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"bounds":{"left":0.5003325,"top":0.09896249,"width":0.029587766,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.64261967,"top":0.09896249,"width":0.02825798,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"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":"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":"AXStaticText","text":"31","depth":4,"bounds":{"left":0.60039896,"top":0.123703115,"width":0.009640957,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"9","depth":4,"bounds":{"left":0.61203456,"top":0.123703115,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"29","depth":4,"bounds":{"left":0.62200797,"top":0.123703115,"width":0.010305851,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.6343085,"top":0.123703115,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"109","depth":4,"bounds":{"left":0.6442819,"top":0.123703115,"width":0.011968086,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.65791225,"top":0.12210695,"width":0.00731383,"height":0.018355945},"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.66522604,"top":0.12210695,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT * FROM team_features where team_id = 1;\n\nSELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922\nSELECT * FROM users WHERE team_id = 340; # 12015\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 340\nand sa.provider = 'salesforce';\n# and sa.provider = 'salesloft';\n\nselect * from crm_fields where crm_configuration_id = 270 and object_type = 'event';\n# 125558 - Event Type - Event_Type__c\n# 125552 - Event Status - Event_Status__c\n\nSELECT * FROM sidekick_settings WHERE team_id = 340;\n\nSELECT * FROM crm_field_values WHERE crm_field_id in (125552);\n\nselect * from activities where crm_configuration_id = 270\nand type = 'conference' and crm_provider_id IS NOT NULL\nand actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;\n\nSELECT * FROM activities WHERE id = 20871677;\nSELECT * FROM crm_field_data WHERE activity_id = 20871677;\n\nselect * from crm_layouts where crm_configuration_id = 270;\nselect * from crm_layout_entities where crm_layout_id in (886,887);\n\nSELECT * FROM crm_configurations WHERE id = 270;\n\nselect * from playbooks where team_id = 340; # 1514\nselect * from groups where team_id = 340;\nSELECT * FROM crm_fields WHERE id IN (125393, 125401);\n\nselect g.name as 'team name', p.name as 'playbook name', f.label as 'activity type field' from groups g\njoin playbooks p on g.playbook_id = p.id\njoin crm_fields f on p.activity_field_id = f.id\nwhere g.team_id = 340;\n\nSELECT * FROM activities WHERE uuid_to_bin('0c180357-67d2-419e-a8c3-b832a3490770') = uuid; # 20448716\nselect * from crm_field_data where object_id = 20448716;\n\nselect * from activities where crm_configuration_id = 270 and provider = 'salesloft' order by id desc;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%CybSafe%'; # 343,273,12008\nselect * from opportunities where team_id = 343;\nselect * from opportunities where team_id = 343 and crm_provider_id = '18099102526';\nselect * from opportunities where team_id = 343 and account_id = 945217482;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nselect * from accounts where team_id = 343 order by name asc;\n\nselect * from stages where crm_configuration_id = 273 and type = 'opportunity';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Voyado%'; # 353,283,12143\nSELECT * FROM activities WHERE crm_configuration_id = 283 and account_id = 3777844 order by id desc;\nSELECT * FROM accounts WHERE team_id = 353 AND name LIKE '%Salesloft%';\nSELECT * FROM activities WHERE id = 20717903;\n\nselect * from participants where activity_id IN (20929172,20928605,20928468,20926272,20926271,20926270,20926269,20916499,20916454,20916436,20916435,20900015,20900014,20900013,20897312,20897243,20897241,20897237,20897232,20897229,20893648,20893231,20893230,20893229,20893228,20889784,20885039,20885038,20885037,20885036,20885035,20882728,20882708,20882703,20882702,20869828,20869811,20869806,20869801,20869799,20869798,20869796,20869795,20869794,20869761,20869760,20869759,20868688,20868687,20850340,20847195,20841710,20833967,20827021,20825307,20825305,20825297,20824615,20824400,20823927,20821760,20795588,20794233,20794057,20793710,20785811,20781789,20781394,20781307,20762651,20758453,20758282,20757323,20756643,20756636,20756629,20756627,20756606,20756605,20756604,20756603,20756602,20756600,20756599,20756598,20756595,20756594,20756589,20756587,20756577,20756573,20748918,20748386,20748385,20748384,20748383,20748382,20748381,20748380,20748379,20748377,20748375,20748373,20743301,20717905,20717904,20717903,20717901,20717899);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 353\nand sa.provider = 'salesforce';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%modern world business solutions%'; # 345,275,12016, l.atkinson@mwbsolutions.co.uk\nSELECT * FROM activities WHERE uuid_to_bin('3921d399-3fef-4609-a291-b0097a166d43') = uuid;\n# id: 20940638, user: 12022, contact: 5305871\nSELECT * FROM activity_summary_logs WHERE activity_id = 20940638;\nselect * from contacts where team_id = 345 and crm_provider_id = '30891432415' order by name asc; # 5305871\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 345\nand sa.provider = 'hubspot';\n\nselect * from users where team_id = 345 and id = 12022;\nSELECT * FROM crm_profiles WHERE user_id = 12022;\nSELECT * FROM participants WHERE activity_id = 20940638;\nSELECT * FROM users u\nJOIN crm_profiles cp ON u.id = cp.user_id\nWHERE u.team_id = 345;\n\nselect * from contacts where team_id = 345 and crm_provider_id = '30880813535' order by name desc; # 5305871\n\nselect * from team_features where team_id = 345;\nSELECT * FROM activities WHERE uuid_to_bin('11701e2d-2f82-4dab-a616-1db4fad238df') = uuid; # 21115197\nSELECT * FROM participants WHERE activity_id = 20897406;\n\n\n\nSELECT * FROM activities WHERE uuid_to_bin('63ba55cd-1abc-447d-83da-0137000005b7') = uuid; # 20953912\nSELECT * FROM activities WHERE crm_configuration_id = 275 and provider = 'ringcentral' and title like '%1252629100%';\n\n\nSELECT * FROM activities WHERE id = 20946641;\nSELECT * FROM crm_profiles WHERE user_id = 10211;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120,97,10984, triger@lunio.ai\nSELECT * FROM opportunities WHERE crm_configuration_id = 97 and crm_provider_id = '006N1000006c5PpIAI';\nselect * from stages where crm_configuration_id = 97 and type = 'opportunity';\nselect * from opportunities where team_id = 120;\n\n\nselect * from crm_configurations crm join teams t on crm.id = t.crm_id\nwhere 1=1\nAND t.current_billing_plan IS NOT NULL\nAND crm.auto_sync_activity = 0\nand crm.provider = 'hubspot';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Exclaimer%'; # 270,205,10053,james.lewendon@exclaimer.com\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 270\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('b54df794-2a9a-4957-8d80-09a600ead5f8') = uuid; # 21637956\nSELECT * FROM crm_profiles WHERE user_id = 11446;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Cygnetise%'; # 372,300,12554, alex.chikly@cygnetise.com\nselect * from playbooks where team_id = 372;\nselect * from crm_fields where crm_configuration_id = 300 and object_type = 'event'; # 141340\nSELECT * FROM crm_field_values WHERE crm_field_id = 141340;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 372\nand sa.provider = 'salesforce';\n\nselect * from crm_profiles where crm_configuration_id = 300;\nSELECT * FROM crm_configurations WHERE team_id = 372;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Planday%'; # 291,242,11501,mfa@planday.com\nSELECT * FROM opportunities WHERE team_id = 291 and crm_provider_id = '006bG000005DO86QAG'; # 3207756\nselect * from crm_field_data where object_id = 3207756;\nSELECT * FROM crm_fields WHERE id = 111834;\n\nselect f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value\nFROM crm_fields f\nJOIN crm_field_data fd ON f.id = fd.crm_field_id\nWHERE f.crm_configuration_id = 242\nAND f.object_type = 'opportunity'\nAND fd.object_id IN (3207756)\nORDER BY fd.object_id, fd.updated_at;\n\nSELECT * FROM crm_configurations WHERE auto_connect = 1;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150,salesforce-admin@tourlane.com\nselect * from group_deal_risk_types drgt join groups g on drgt.group_id = g.id\nwhere g.team_id = 187;\n\nselect * from `groups` where team_id = 187;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 187\nand sa.provider = 'salesforce';\n\n# Destination - 98870 - Destination__c\n# Stage - 79014 - StageName\n# Land Arrangement - 98856 - Land_Arrangement__c\n# Flight - 98848 - Flight__c\n# Last activity date - 98812 - LastActivityDate\n# Last modified date - 98809 - LastModifiedDate\n# Last inbound mail timestamp - 99151 - Last_Inbound_Mail_Timestamp__c\n# next call - 98864 - Next_Call__c\n\nselect * from crm_fields where crm_configuration_id = 209 and object_type = 'opportunity';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 209;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;\n\nselect * from opportunities where team_id = 187 and name LIKE'%Muriel Sal%';\nselect * from opportunities where team_id = 187 and user_id = 9951 and is_closed = 0;\nselect * from activities where opportunity_id = 3538248;\n\nSELECT * FROM crm_profiles WHERE user_id = 8150;\n\nselect * from deal_risks where opportunity_id = 3538248;\n\nselect * from teams where crm_id IS NULL;\n\nSELECT opp.id AS opportunity_id,\n u.group_id AS group_id,\n MAX(\n CASE\n WHEN a.type IN (\"sms-inbound\", \"sms-outbound\") THEN a.created_at\n ELSE a.actual_end_time\n END) as last_date\nFROM opportunities opp\nleft join activities a on a.opportunity_id = opp.id\ninner join users u on opp.user_id = u.id\nwhere opp.user_id IN (9951)\n\nAND opp.is_closed = 0\nand a.status IN ('completed', 'received', 'delivered') OR a.status IS NULL\ngroup by opp.id;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Cybsafe%'; # 343,301,12008,polly.morphew@cybsafe.com\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 301;\nSELECT * FROM contacts WHERE id = 6612363;\nSELECT * FROM accounts WHERE id = 4235676;\nSELECT * FROM opportunities WHERE crm_configuration_id = 301 and crm_provider_id = 32983784868;\nselect * from opportunity_stages where opportunity_id = 4503759;\n# SELECT * FROM opportunities WHERE id = 4569937;\n\nselect * from activities where crm_configuration_id = 301;\nSELECT * FROM activities WHERE uuid_to_bin('d3b2b28b-c3d0-4c2d-8ed0-eef42855278a') = uuid; # 26330370\nSELECT * FROM participants WHERE activity_id = 26330370;\n\nSELECT * FROM teams WHERE id = 375;\nselect * from playbooks where team_id = 375;\n\nselect * from stages where crm_configuration_id = 301 and type = 'opportunity';\n\nselect * from teams;\nselect * from contact_roles;\n\nSELECT * FROM opportunities WHERE team_id = 343 and user_id = 12871 and close_date >= '2024-11-01';\n\nselect * from users u join crm_profiles cp on cp.user_id = u.id where u.team_id = 343;\n\nSELECT * FROM crm_field_data WHERE object_id = 3771706;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_fields WHERE crm_configuration_id = 301 and object_type = 'opportunity'\nand crm_provider_id LIKE \"%traffic_light%\";\nSELECT * FROM crm_field_values WHERE crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531);\n\nSELECT fd.* FROM opportunities o\nJOIN crm_field_data fd ON o.id = fd.object_id\nWHERE o.team_id = 343\n# and o.user_id IS NOT NULL\nand fd.crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531)\nand fd.value != ''\norder by value desc\n# group by o.id\n;\n\nSELECT * FROM opportunities WHERE id = 3769843;\n\nSELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150, salesforce-admin@tourlane.com\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 209;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Funding Circle%'; # 220,177,8603,aswini.mishra@fundingcircle.com\nSELECT * FROM activities WHERE uuid_to_bin('7a40e99b-3b37-4bb1-b983-325b81801c01') = uuid; # 23139839\n\n\nSELECT * FROM opportunities WHERE id = 3855992;\n\nSELECT * FROM users WHERE name LIKE '%Angus Pollard%'; # 8988\n\nSELECT * FROM teams WHERE name LIKE '%Story Terrace%'; # 379, 307, 12894\nSELECT * FROM crm_fields WHERE crm_configuration_id = 307 and object_type != 'opportunity';\n\nselect * from contacts where team_id = 379 and name like '%bebro%'; # 5874411, crm: 77229348507\nSELECT * FROM crm_field_data WHERE object_id = 5874411;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 379\nand sa.provider = 'hubspot';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%mentio%'; # 117, 94, 6371, nikhil.kumar@mention-me.com\nSELECT * FROM activities WHERE uuid_to_bin('82939311-1af0-4506-8546-21e8d1fdf2c1') = uuid;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, salesforce-admin@tourlane.com\nSELECT * FROM opportunities WHERE team_id = 187 and crm_provider_id = '006Se000008xfvNIAQ'; # 3537793\nselect * from generic_ai_prompts where subject_id = 3537793;\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120, 97, 10984, triger@lunio.ai\nSELECT * FROM crm_configurations WHERE id = 97;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 97;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 355;\nSELECT * FROM crm_fields WHERE id = 32682;\n\nselect cfd.value, o.* from opportunities o\njoin crm_field_data cfd on o.id = cfd.object_id and cfd.crm_field_id = 32682\nwhere team_id = 120\nand cfd.value != ''\n;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 120\nand sa.provider = 'salesforce';\n\nselect * from opportunities where team_id = 120 and crm_provider_id = '006N1000007X8MAIA0';\nSELECT * FROM crm_field_data WHERE object_id = 2313439;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE id = 410;\nSELECT * FROM teams WHERE name LIKE '%Local Business Oxford%';\nselect * from scorecards where team_id = 410;\nselect * from scorecard_rules;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Funding%'; # 220, 177, 8603, aswini.mishra@fundingcircle.com\nselect * from activities a\njoin opportunities o on a.opportunity_id = o.id\njoin users u on o.user_id = u.id\nwhere a.crm_configuration_id = 177 and a.type LIKE '%email-out%'\n# and a.actual_end_time > '2024-12-16 00:00:00'\n# and o.remotely_created_at > '2024-12-01 00:00:00'\n# and u.group_id = 1014\nand u.id = 9021\norder by a.id desc;\nSELECT * FROM opportunities WHERE id in (3981384,4017346);\nSELECT * FROM users WHERE team_id = 220 and id IN (8775, 11435);\n\nselect * from users where id = 9021;\nselect * from inboxes where user_id = 9021;\n\nselect * from inbox_emails where inbox_id = 1349 and email_date > '2024-12-18 00:00:00';\n\nselect * from email_messages where team_id = 220\nand orig_date > '2024-12-16 00:00:00' and orig_date < '2024-12-19 00:00:00'\nand subject LIKE '%Personal%'\n# and 'from' = 'credit@fundingcircle.com'\n;\n\nselect * from activities a\njoin opportunities o on a.opportunity_id = o.id\nwhere a.user_id = 9021 and a.type LIKE '%email-out%'\nand a.actual_end_time > '2024-12-18 00:00:00'\nand o.user_id IS NOT NULL\nand o.remotely_created_at > '2024-12-01 00:00:00'\norder by a.id desc;\n\nSELECT * FROM opportunities WHERE team_id = 220 and name LIKE '%Right Car move Limited%' and id = 3966852;\nselect * from activities where crm_configuration_id = 177 and type LIKE '%email%' and opportunity_id = 3966852 order by id desc;\n\nselect * from team_settings where name IN ('useCloseDate');\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Hurree%'; # 104, 81, 6175, jfarrell@hurree.co\nSELECT * FROM opportunities WHERE team_id = 104 and name = 'PropOp';\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 104\nand sa.provider = 'hubspot';\n\nselect * from crm_configurations where last_synced_at > '2025-01-19 01:00:00'\nselect * from teams where crm_id IS NULL;\n\nselect t.name as 'team', u.name as 'owner', u.email, u.phone\nfrom teams t\njoin activity_providers ap on t.id = ap.team_id\njoin users u on t.owner_id = u.id\nwhere 1=1\n and t.status = 'active'\n and ap.is_enabled = 1\n# and u.status = 1\n and ap.provider = 'ms-teams';\n\nselect * from crm_configurations where provider = 'bullhorn'; # 344\nSELECT * FROM teams WHERE id = 442; # 14293\nselect * from users where team_id = 442;\nselect * from social_accounts sa where sa.sociable_id = 14293;\nselect * from invitations where team_id = 442;\n\n# ********************************************************************************************************\nSELECT * FROM users WHERE email LIKE '%nea.liikamaa@eletive.com%'; # 14022\nSELECT * FROM teams WHERE id = 429;\nselect * from opportunities where team_id = 429 and crm_provider_id IN (16157415775, 22246219645);\nselect * from activities where opportunity_id in (4340436,4353519);\n\nselect * from transcription where activity_id IN (25630961,25381771);\nselect * from generic_ai_prompts where subject_id IN (4353519);\n\nSELECT\n a.id as activity_id,\n a.opportunity_id,\n a.type as activity_type,\n a.language,\n CONCAT(a.title, a.description) AS mail_content,\n e.from AS mail_from,\n e.to AS mail_to,\n e.subject AS mail_subject,\n e.body AS mail_body,\n p.type as prompt_type,\n p.status as prompt_status,\n p.content AS prompt_content,\n a.actual_start_time as created_at\nFROM activities a\n LEFT JOIN ai_prompts p ON a.transcription_id = p.transcription_id AND p.deleted_at IS NULL\n LEFT JOIN email_messages e ON a.id = e.activity_id\nWHERE a.actual_start_time > '2024-01-01 00:00:00'\n AND a.opportunity_id IN (4353519)\n AND a.status IN ('completed', 'received', 'delivered')\n AND a.deleted_at IS NULL\n AND a.type NOT IN ('sms-inbound', 'sms-outbound')\nORDER BY a.opportunity_id ASC, a.id ASC;\n\nSELECT * FROM users WHERE name LIKE '%George Fierstone%'; # 14293\nSELECT * FROM teams WHERE id = 442;\nSELECT * FROM crm_configurations WHERE id = 344;\nselect * from team_features where team_id = 442;\nselect * from groups where team_id = 442;\nselect * from playbooks where team_id = 442;\nselect * from playbook_categories where playbook_id = 1729;\nselect * from crm_fields where crm_configuration_id = 344 and id = 172024;\nSELECT * FROM crm_field_values WHERE crm_field_id = 172024;\nselect * from crm_layouts where crm_configuration_id = 344;\nselect * from playbook_layouts where playbook_id = 1729;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 221, 9444\n\nselect s.*\n# , s.sent_at, u.name, a.*\nfrom activity_summary_logs s\ninner join activities a on a.id = s.activity_id\ninner join users u on u.id = a.user_id\nwhere a.crm_configuration_id = 356\nand s.sent_at > date_sub(now(), interval 60 day)\norder by a.actual_end_time desc;\n\nselect * from activities a\n# inner join activity_summary_logs s on s.activity_id = a.id\nwhere a.crm_configuration_id = 356 and a.actual_end_time > date_sub(now(), interval 60 day)\n# and a.crm_provider_id is not null\n# and provider <> 'ringcentral'\nand status = 'completed'\norder by a.actual_end_time desc;\n\nselect * from teams order by id desc; # 17328, 32, 17830, integration-account@jiminny.com\nSELECT * FROM users;\nSELECT * FROM users where team_id = 260 and status = 1; # 201 - 150 active\nSELECT * FROM teams WHERE id = 260;\nselect * from team_settings where team_id = 260;\nselect * from crm_configurations where team_id = 260;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 356;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1184;\n\nselect * from accounts where crm_configuration_id = 221 order by id desc; # 7000\nselect * from leads where crm_configuration_id = 221 order by id desc; # 0\nselect * from contacts where crm_configuration_id = 221 order by id desc; # 200 000\nselect * from opportunities where crm_configuration_id = 221 order by id desc; # 0\nselect * from crm_profiles where crm_configuration_id = 221 order by id desc; # 23\nselect * from crm_fields where crm_configuration_id = 221;\nselect * from crm_field_values where crm_field_id = 5302 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 221 order by id desc;\nselect * from stages where crm_configuration_id = 221 order by id desc;\n\nselect * from accounts where crm_configuration_id = 356 order by id desc; # 7000\nselect * from leads where crm_configuration_id = 356 order by id desc; # 0\nselect * from contacts where crm_configuration_id = 356 order by id desc; # 200 000\nselect * from opportunities where crm_configuration_id = 356 order by id desc; # 0\nselect * from crm_profiles where crm_configuration_id = 356 order by id desc; # 23\nselect * from crm_fields where crm_configuration_id = 356;\nselect * from crm_field_values where crm_field_id = 5302 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 356 order by id desc;\nselect * from stages where crm_configuration_id = 356 order by id desc;\n\nselect * from playbooks where team_id = 260 order by id desc; # 4 (2 deleted)\nselect * from groups where team_id = 260 order by id desc; # 27 groups, (2 deleted)\nselect * from playbook_layouts where playbook_id IN (1410,1409,1276,1254); # 4\nselect ce.* from calendars c\njoin users u on c.user_id = u.id\njoin calendar_events ce on c.id = ce.calendar_id\nwhere u.team_id = 260\nand (ce.start_time > '2025-02-21 00:00:00')\n;\n# calendar events 1207\n#\n\nselect * from opportunities where team_id = 260;\nSELECT * FROM crm_field_data WHERE object_id = 4696496;\n\nselect * from activities where crm_configuration_id = 356 and crm_provider_id IS NOT NULL;\nselect * from activities where crm_configuration_id IN (221) and provider NOT IN ('ms-teams', 'uploader', 'zoom-bot')\n# and type = 'conference' and status = 'scheduled' and activities.is_internal = 0\nand created_at > '2024-03-01 00:00:00'\norder by id desc; # 880 000, ringcentral, avaya\nSELECT * FROM participants WHERE activity_id = 26371744;\n\n# all activities 942 000 +\n# conference 7385 - scheduled 984 - external 343\n\nselect * from activities where id = 26321812;\nselect * from participants where activity_id = 26321812;\nselect * from participants where activity_id in (26414510,26414514,26414516,26414604,26414653,26414655);\nselect * from leads where id in (720428,689175,731546,645866,621037);\n\nselect * from users where id = 13841;\nselect * from opportunities where user_id = 9541;\nselect * from stages where id = 15900;\n\nselect * from accounts where\n# id IN (4160055,5053725,4965303,4896434)\nid in (4584518,3249934,3218025,3891133,3399450,4172999,4485161,3101785,4587203,3070816,2870343,2870341,3563940,4550846,3424464,3249963,2870342)\n;\n\nselect * from activities where id = 26654935;\nSELECT * FROM opportunities WHERE id = 4803458;\n\nSELECT * FROM opportunities where team_id = 260 and user_id = 13841 AND stage_id = 15900;\nSELECT id, uuid, provider, type, lead_id, account_id, contact_id, opportunity_id, stage_id, status, recording_state, title, actual_start_time, actual_end_time\nFROM activities WHERE user_id = 13841 AND opportunity_id IN (4729783, 4731717, 4731726, 4732064, 4732849, 4803458, 4813213);\n\nSELECT DISTINCT\n o.id, o.stage_id, s.name, a.title,\n a.*\nFROM activities a\n# INNER JOIN tracks t ON a.id = t.activity_id\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams team ON u.team_id = team.id\nINNER JOIN groups g ON u.group_id = g.id\nINNER JOIN opportunities o ON a.opportunity_id = o.id\nINNER JOIN stages s ON o.stage_id = s.id\nWHERE\n a.crm_configuration_id = 356\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n# and a.user_id = 13841\n AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')\n AND team.uuid = uuid_to_bin('a607fba7-452e-4683-b2af-00d6cb52c93c')\n AND g.uuid = uuid_to_bin('b5d69e40-24a0-4c16-810b-5fa462299f94')\n\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND t.type IN ('audio', 'video')\n AND (\n (a.actual_start_time BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59')\n OR\n (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59'\n )\n )\n AND (\n a.is_private = 0\n OR (\n a.is_private = 1\n AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')\n )\n )\n AND (\n# s.id = 15900\n s.uuid = uuid_to_bin('04ca1c26-c666-4268-a129-419c0acffd73')\n OR s.uuid IS NULL -- Include records without opportunity stage\n )\n\nORDER BY a.actual_end_time DESC;\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lead Forensics%'; # 190, 162, 8474, willsc@leadforensics.com\nSELECT * FROM users WHERE team_id = 190;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 190\nand sa.provider = 'hubspot';\n\nselect * from role_user where user_id = 8474;\n\nselect * from crm_configurations where provider = 'bullhorn';\n\nSELECT * FROM opportunities WHERE uuid_to_bin('94578249-65ec-4205-90f2-7d1a7d5ab64a') = uuid;\nSELECT * FROM users WHERE uuid_to_bin('26dbadeb-926f-4150-b11b-771b9d4c2f9a') = uuid;\n\nSELECT * FROM opportunities WHERE id = 4732493;\nselect * from activities where opportunity_id = 4732493;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE id = 443; # 358, 14315, andrea.romano@correrenaturale.com\nSELECT * FROM opportunities WHERE team_id = 443;\n\nSELECT a.id, a.type, a.user_id, a.status, a.deleted_at, u.name, u.email, u.team_id as activity_team_id, u.status, u.deleted_at, t.name, t.status, s.team_id as stage_team_id\nFROM activities AS a\nJOIN stages AS s ON a.stage_id = s.id\nJOIN users AS u ON u.id = a.user_id\nJOIN teams AS t ON t.id = s.team_id\nWHERE u.team_id <> s.team_id and t.id > 135;\n\n\nSELECT\n crm_configuration_id,\n crm_provider_id,\n COUNT(*) as duplicate_count,\n GROUP_CONCAT(id) as stage_ids,\n GROUP_CONCAT(name) as stage_names\nFROM stages\nGROUP BY crm_configuration_id, crm_provider_id\nHAVING COUNT(*) > 1\nORDER BY duplicate_count DESC;\n\nselect * from stages where id IN (14898,14907);\n\nselect * from business_processes;\n\nSELECT *\nFROM crm_configurations\nWHERE team_id IN (\n SELECT team_id\n FROM crm_configurations\n GROUP BY team_id\n HAVING COUNT(*) > 1\n)\nORDER BY team_id;\n\nSELECT *\nFROM teams\nWHERE crm_id IN (\n SELECT crm_id\n FROM teams\n GROUP BY crm_id\n HAVING COUNT(*) > 1\n)\nORDER BY crm_id;\n\n# ***************************************************************************\nselect * from crm_configurations where provider = 'integration-app';\nSELECT * FROM teams WHERE id = 443; # Correre Naturale 358 14315 andrea.romano@correrenaturale.com\nselect * from activities where crm_configuration_id = 358 order by actual_end_time desc;\nselect id, uuid, actual_end_time, crm_provider_id, is_internal, playbook_category_id, type, user_id, lead_id, contact_id, account_id, opportunity_id, status, title from activities where crm_configuration_id = 358 order by actual_end_time desc;\nselect * from team_features where team_id = 358;\nselect * from activity_summary_logs;\n\nselect * from teams where id = 406;\n\n# ************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Sportfive%'; # 267, 202, 14637, srv.salesforce@sportfive.com\nselect * from activities where crm_configuration_id = 202 order by actual_end_time desc;\n\nSELECT * FROM users where id = 14637;\nSELECT * FROM teams where id = 267;\nSELECT * FROM groups where id = 1118;\n\nselect g.name, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\ninner join groups g on g.id = u.group_id\nwhere a.crm_configuration_id = 202\nand a.is_internal = 0\nand (a.scheduled_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type = 'conference'\nand a.status != 'completed'\nand a.external_id is not null\norder by a.scheduled_start_time desc;\n\nSELECT * FROM activities\nWHERE crm_configuration_id = 202\n AND status IN ('completed', 'failed')\n AND recording_state != 'stopped'\n AND type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n AND (is_private = 0 OR user_id = 14637)\n AND (\n (\n actual_start_time BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n ) OR (\n actual_start_time IS NULL\n AND type IN ('sms-outbound', 'sms-inbound')\n AND created_at BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n )\n )\n AND NOT EXISTS (\n SELECT 1\n FROM tracks\n WHERE\n tracks.activity_id = activities.id\n AND tracks.type IN ('audio', 'video')\n )\nORDER BY actual_end_time DESC;\n\nSELECT DISTINCT\n a.*\nFROM activities a\nINNER JOIN tracks t ON a.id = t.activity_id\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams team ON u.team_id = team.id\nWHERE\n a.crm_configuration_id = 202\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n# and a.user_id = 14637\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND t.type IN ('audio', 'video')\n AND (\n (a.actual_start_time BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59')\n OR\n (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n )\n )\n AND (\n a.is_private = 0\n OR (\n a.is_private = 1\n AND a.user_id = 14637\n )\n )\n\nORDER BY a.actual_end_time DESC\n;\n\nSELECT DISTINCT a.*\nFROM activities a\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams t ON u.team_id = t.id\n# INNER JOIN tracks tr ON a.id = tr.activity_id\n# INNER JOIN groups g ON u.group_id = g.id\nWHERE 1=1\n AND t.id = 267\n# AND t.uuid = uuid_to_bin('aed4927b-f1ea-499e-94c3-83762fd233e8')\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND tr.type NOT IN ('audio', 'video')\n AND (\n a.is_private = 0\n OR a.user_id = 14637\n )\n AND (\n (a.actual_start_time BETWEEN '2025-03-19 00:00:00' AND '2025-03-21 23:59:59')\n OR (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-19 00:00:00' AND '2025-03-21 23:59:59'\n )\n )\n# and NOT EXISTS (\n# SELECT 1\n# FROM tracks t\n# WHERE t.activity_id = a.id\n# AND t.type IN ('audio', 'video')\n# )\n\nORDER BY a.actual_end_time DESC;\n\nSELECT * FROM tracks WHERE activity_id = 26485995;\n\nselect a.is_private, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\nwhere a.crm_configuration_id = 202\n# and a.is_internal = 0\nand (a.actual_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type IN (\"softphone\",\"softphone-inbound\",\"conference\",\"sms-inbound\")\nand a.status IN ('completed', 'failed')\n# and a.external_id is not null\norder by a.actual_end_time desc;\n\nselect * from activities a where a.crm_configuration_id = 202\nand a.actual_start_time between '2025-03-20 00:00:00' and '2025-03-21 00:00:00'\n# AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n\nselect g.name, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\ninner join groups g on g.id = u.group_id\nwhere a.crm_configuration_id = 202\nand a.is_internal = 0\nand (a.scheduled_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type = 'conference'\nand a.status != 'completed'\nand a.external_id is not null\norder by a.scheduled_start_time desc;\n\nSELECT * FROM teams WHERE name LIKE '%Tourlane%';\nSELECT * FROM crm_fields WHERE crm_configuration_id = 209 and object_type = 'opportunity';\nSELECT * FROM crm_field_data WHERE crm_field_id = 98809;\n\nselect * from users where status = 1 AND timezone = 'MDT';\n\nselect * from opportunities where id = 3769814;\nselect * from deal_risks where opportunity_id = 3769814;\n\nselect cp.* from crm_profiles cp\njoin users u on cp.user_id = u.id\njoin crm_configurations crm on cp.crm_configuration_id = crm.id\nwhere crm.provider = 'hubspot' AND u.status = 1 AND log_notes != 'none';\n\nselect * from crm_fields where id = 154575;\n\nselect * from team_features where feature = 'SUPPORTS_SYNC_MISSING_CALL_DISPOSITIONS';\nSELECT * FROM teams WHERE id = 176; # crm 148\nselect * from activities where crm_configuration_id = 148 and provider = 'hubspot' order by id desc;\n\nselect * from activity_providers where provider = 'amazon-connect';\n\nselect * from crm_fields cf\njoin crm_configurations crm on crm.id = cf.crm_configuration_id\nwhere crm.provider = 'hubspot' and cf.object_type IN ('account', 'contact');\n\n# *********************************************************************************************\nSELECT * FROM users WHERE id IN (15415, 15418);\nSELECT * FROM groups WHERE id IN (1805,1806);\nSELECT * FROM playbooks WHERE id = 1860;\nSELECT * FROM playbook_categories WHERE id = 38634;\nSELECT * FROM crm_fields WHERE id = 189962;\n\nSELECT * FROM teams WHERE name = 'Pulsar Group'; # 472, 380, 15138 raza.gilani@vuelio.com\n\nSELECT * FROM crm_profiles WHERE user_id = 15415;\nSELECT * FROM social_accounts WHERE sociable_id = 15415 and provider = 'salesforce';\n\nselect * from sidekick_settings where team_id = 472;\n\nSELECT * FROM activities WHERE uuid_to_bin('452c58c7-b87c-4fdd-953e-d7af185e9588') = uuid; # 28617536, user: 15418\nSELECT * FROM activities WHERE uuid_to_bin('399114ee-d3a8-458c-bff5-5f654658db0a') = uuid; # 28344407, user: 15415\nSELECT * FROM activities WHERE uuid_to_bin('f0aa567f-0ab1-4bbb-96aa-37dcf184676b') = uuid; # 28580288, user: 15415\nSELECT * FROM activities WHERE uuid_to_bin('50c086b1-2770-4bca-b5ae-6bac22ec426b') = uuid; # 28566069, user: 15415\n\n# *********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%TeamTailor%'; # 109, 218, 13969, salesforce-integrations@teamtailor.com\nselect * from crm_configurations where id = 218;\nSELECT * FROM activities WHERE uuid_to_bin('e39b5857-7fdb-4f5a-951a-8d3ca69bb1b0') = uuid; # 28338765\nSELECT * FROM users WHERE id IN (13232, 13230);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\n\n0057R00000EPL5HQAX Inez Ekblad\n\n1091cb81-5ea1-4951-a0ed-f00b568f0140 Triman Kaur\n\nSELECT * FROM crm_profiles WHERE user_id IN (13232, 13230);\n\n############################################################################################\nSELECT * FROM activities WHERE uuid_to_bin('675eeaeb-5681-42db-90bc-54c07a604408') = uuid; # 28655939 00UVg00000FLvnSMAT\nSELECT * FROM crm_field_data WHERE activity_id = 28655939;\nSELECT * FROM crm_fields WHERE id IN (94491,94493,94498);\nSELECT * FROM users WHERE id = 13658;\nSELECT * FROM teams WHERE id = 109;\nSELECT * FROM crm_configurations WHERE id = 218;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Strengthscope%'; # 481, 390, 15420, katy.holden@strengthscope.comk\nSELECT * FROM stages WHERE crm_configuration_id = 390;\nselect * from business_processes where team_id = 481 and crm_configuration_id = 390;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 481\nand sa.provider = 'salesforce';\n\n\nSELECT * FROM users WHERE id = 15780; # team 462\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 462\nand sa.provider = 'hubspot';\n\n\nselect * from teams where id = 495;\nSELECT * FROM users WHERE id = 15794;\nselect * from social_accounts where sociable_id = 15794;\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Flight%'; # 427, 333, 13752\nSELECT * FROM accounts WHERE team_id = 427 and crm_provider_id = '668731000183444517';\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Group GTI%'; # 495, 407, 15794\nSELECT * FROM activities WHERE crm_configuration_id = 407\nand status = 'completed' and type = 'conference'\norder by id desc;\n\nselect ru.*, pr.*, p.* from users u join role_user ru on ru.user_id = u.id\njoin permission_role pr on pr.role_id = ru.role_id\n join permissions p on p.id = pr.permission_id\nwhere team_id = 495 and p.name IN ('dial');\n\nselect * from permission_role;\n\nselect * from activities where crm_configuration_id = 407 and status = 'completed' order by id desc;\nSELECT * FROM activities WHERE id = 29512773;\nSELECT * FROM activities WHERE id IN (29042721,28991325,29002874);\n\nSELECT al.* from activity_summary_logs al join activities a on a.id = al.activity_id\nwhere a.crm_configuration_id = 407\n# and a.id IN (29042721,28991325,29002874);\n\nSELECT * FROM users WHERE id = 15794;\nSELECT * FROM users WHERE team_id = 495;\nSELECT * FROM social_accounts WHERE sociable_id = 15794;\nSELECT * FROM opportunities WHERE team_id = 495 and name like '%OC:%';\nSELECT * FROM contacts WHERE team_id = 495;\nSELECT * FROM leads WHERE team_id = 495;\nSELECT * FROM accounts WHERE team_id = 495;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 407;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 407;\nSELECT * FROM crm_configurations WHERE id = 407;\nSELECT * FROM opportunities WHERE team_id = 495 and close_date BETWEEN '2025-06-01' AND '2025-07-01'\nand user_id IS NOT NULL and is_closed = 1 and is_won = 1;\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Hamilton Court FX LLP%'; # 249, 187, 10103\nSELECT * FROM activities WHERE uuid_to_bin('4659c2bb-9a49-484e-9327-a3d66f1e028c') = uuid; # 28951064\nSELECT * FROM crm_fields WHERE crm_configuration_id = 187 and object_type IN ('tasks', 'event');\n\n# *********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Checkstep%'; # 325, 256, 11753\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 325\nand sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('7be372e2-1916-4d79-a2f3-ca3db1346db3') = uuid; # 28611085\nSELECT * FROM activities WHERE uuid_to_bin('980f0336-840b-4185-a5a9-30cf8b0749a8') = uuid; # 28719733\nSELECT * FROM activity_summary_logs where activity_id = 28719733;\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 356, 9444\nSELECT * FROM activity_summary_logs where sent_at BETWEEN '2025-06-09 11:38:00' AND '2025-06-09 11:40:00';\nSELECT * FROM leads WHERE crm_configuration_id = 356 and crm_provider_id = '230045001502770504'; # 823630\nselect * from activities where crm_configuration_id = 356 and lead_id = 841732;\n\nSELECT * from activity_summary_logs al join activities a on a.id = al.activity_id\nwhere a.crm_configuration_id = 356;\n\nselect * from activities where crm_configuration_id = 356\nand actual_end_time between '2025-06-09 11:00:00' and '2025-06-09 12:00:00'\norder by id desc;\n\nselect * from accounts where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\nselect * from leads where crm_configuration_id = 356 and crm_provider_id = '230045001514275654' order by id desc;\nselect * from contacts where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\nselect * from opportunities where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\n\nselect * from team_features where team_id = 260;\nselect * from features where id IN (1,2,4,6,18,19,20,9,10,3,23,24,25,26,27);\n\nSELECT * FROM activities WHERE uuid_to_bin('7be372e2-1916-4d79-a2f3-ca3db1346db3') = uuid;\n\nselect * from crm_fields;\nselect * from crm_layout_entities;\n\nSELECT * FROM teams WHERE name LIKE '%Optable%';\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Teamtailor%'; # 109, 218, 13969\nSELECT * FROM crm_configurations WHERE id = 218;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('675eeaeb-5681-42db-90bc-54c07a604408') = uuid; # 28655939\nSELECT * FROM crm_field_data WHERE activity_id = 28655939;\nSELECT * FROM crm_fields WHERE id in (94491,94493,94498);\n\nselect * from teams where crm_id IS NULL;\n\nSELECT * FROM activities WHERE uuid_to_bin('71aa8a0c-9652-4ff6-bee7-d98ae60abef6') = uuid;\n\n# *************************************************************************************************\nselect * from team_domains where team_id = 399;\nSELECT * FROM teams WHERE name LIKE '%Rydoo%'; # 399, 318, 13207\n\nselect * from calendar_events where id = 5163781;\nSELECT * FROM activities WHERE uuid_to_bin('be2cbc52-7fda-46a0-9ae0-25d9553eafc0') = uuid; # 29443896\nSELECT * FROM participants WHERE activity_id = 29443896;\nselect * from contacts where crm_configuration_id = 318 and email = 'marianne.westeng@strawberry.no';\nselect * from leads where crm_configuration_id = 318 and email = 'marianne.westeng@strawberry.no';\n\nselect * from activities where user_id = 14937 order by created_at ;\n\nselect * from users where id = 14937;\n\nselect * from contacts where crm_configuration_id = 318 and email LIKE '%@strawberry.se';\nselect * from opportunities where crm_configuration_id = 318 and crm_provider_id = '006Sf00000D1WOAIA3';\n\nselect * from activities a join participants p on a.id = p.activity_id\nwhere crm_configuration_id = 318 and a.updated_at > '2025-06-23T08:18:43Z';\n\n# *************************************************************************************************\nSELECT * FROM opportunities WHERE team_id = 379 and crm_provider_id = '39334518886';\nSELECT * FROM opportunities WHERE team_id = 379 order by id desc;\nSELECT * FROM teams WHERE id = 379;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 379 and sociable_id = 13852\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations WHERE id = 307;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 307;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1027;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 307\n and id IN (144750,144855,145158,155227);\n\nSELECT * FROM activities;\n\n\nselect * from activities\nwhere created_at > '2025-07-01 00:00:00'\n# and created_at < '2025-08-01 00:00:00'\nand type not in ('email-outbound', 'email-inbound')\nand account_id is null\nand contact_id is null\nand lead_id is null\nand opportunity_id is not null\n;\nSELECT * FROM activities WHERE id IN (25344155, 25344296, 25501909, 28692187);\nSELECT * FROM crm_configurations WHERE id in (335,301,200);\n\nselect * from crm_fields where crm_configuration_id = 230 and crm_provider_id = 'Age2__c';\n\nSELECT * FROM teams WHERE name LIKE '%Resights%';\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\n\nselect * from crm_configurations where provider = 'bullhorn'; # 344\nselect * from teams where id IN (442);\n\nselect * from activities\nwhere crm_configuration_id = 177\nand provider = 'amazon-connect'\n order by id desc;\n# and source <> 'gong';\n\nselect * from activity_providers where provider = 'amazon-connect';\n\nSELECT * FROM activities WHERE uuid_to_bin('cec1993b-a7e5-4164-b74d-d680ea51d2f2') = uuid;\n\n\nselect * from crm_configurations where store_transcript = 1;\nSELECT * FROM teams WHERE id IN (80);\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Sedna%'; # 277, 213, 12594\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 277\nand sa.provider = 'salesforce';\n\nselect * from activities where crm_configuration_id = 213 and account_id = 2511502;\n\nselect * from crm_configurations where id = 213;\n\nSELECT * FROM activities WHERE uuid_to_bin('35aa790a-8569-4544-8268-66f9a4a26804') = uuid; # 33981604\nSELECT * FROM participants WHERE activity_id = 33981604;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 337 and object_type = 'task';\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 431\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('b5476c7d-19a8-491b-869d-676ea1e857b6') = uuid; # 33997223\nselect * from activity_summary_logs where activity_id = 33997223;\nselect * from activity_notes where activity_id = 33997223;\n\n# ***********************************\nSELECT * FROM teams WHERE name LIKE '%Abode%';\n\n\nselect * from features;\nselect * from teams t\nwhere t.status = 'active'\nand id NOT IN (select team_id from team_features where feature_id = 9)\n;\n\n\nselect * from playbook_layouts where playbook_id = 1725;\nSELECT * FROM activities WHERE uuid_to_bin('65cc283c-4849-49e6-927f-4c281c8fea19') = uuid; # 34297473\nselect * from teams where id = 318;\nselect * from crm_configurations where team_id = 318;\nselect * from playbooks where team_id = 318;\nSELECT * FROM crm_layouts where crm_configuration_id = 381;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1259;\nSELECT * FROM crm_fields WHERE id IN (192938,192936,192939);\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1266;\nSELECT * FROM crm_fields WHERE id IN (192980,192991,192997,192998,193064,193067);\n\nSELECT * FROM activities WHERE uuid_to_bin('a902289b-285c-48eb-9cc2-6ad6c5d938f5') = uuid; # 34297533\n\n\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 927;\nSELECT * FROM crm_fields WHERE id IN (131668,131669,131670,131671,131676,131797);\n\nSELECT * FROM teams WHERE name LIKE '%Peripass%'; # 351, 281, 12124\nselect * from crm_layouts where crm_configuration_id = 281;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 927;\nselect * from crm_fields where crm_configuration_id = 281 and id in (131668,131669,131670,131671,131676,131797);\nselect * from opportunities where crm_configuration_id = 281;\n\nSELECT * FROM activities WHERE id IN (34211315, 34130075);\nSELECT * FROM crm_field_data WHERE object_id IN (34211315, 34130075);\n\nselect cf.crm_configuration_id, cle.crm_layout_id, cle.id, cf.id from crm_field_data cfd\njoin crm_layout_entities cle on cle.id = cfd.crm_layout_entity_id\njoin crm_fields cf on cle.crm_field_id = cf.id\nwhere cf.deleted_at IS NOT NULL\nGROUP BY cle.id, cf.id;\n\nselect * from crm_layouts where id IN (355);\nselect u.email, t.crm_id, t.* from teams t\njoin users u on u.id = t.owner_id\nwhere crm_id IN (97);\n\nSELECT * FROM crm_fields WHERE id = 96492;\n\nselect * from permissions;\nselect * from permission_role where permission_id = 247;\nselect * from roles;\n\nselect * from migrations;\n# *****************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('291e3c21-11cc-4728-aee7-6e4bedf86d72') = uuid; # 34262174\nSELECT * FROM crm_configurations WHERE id = 301;\nSELECT * FROM teams WHERE id = 343;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nselect * from participants where activity_id = 34262174;\n\nselect * from contacts where crm_configuration_id = 301 and id = 6976326;\nselect * from accounts where crm_configuration_id = 301 and id IN (4647626, 4815829); # 30761335403\n\nselect * from activity_summary_logs where activity_id = 34262174;\n\nselect * from users where status = 1 AND timezone = 'EST';\n\n# ****************************************************************************\nSELECT * FROM users WHERE id = 13869;\nSELECT * FROM crm_configurations WHERE id = 320;\nSELECT * FROM teams WHERE id = 401;\n\nSELECT * FROM activities WHERE uuid_to_bin('2228c16f-10be-48d5-90d4-67385219dc01') = uuid; # 29670601\n\nSELECT * FROM accounts WHERE id = 7761483;\nSELECT * FROM opportunities WHERE id = 6051814;\n\nSELECT * FROM teams WHERE name LIKE '%Seedlegals%';\n\n;select * from opportunities where updated_at > '2025-10-11' AND crm_provider_id = '34713761166';\n\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 177;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 577;\nSELECT * FROM crm_fields WHERE id IN (68458,68459,68480,68497,68524,68530,68554,68618,68662,68781,68810,68898,68981,69049,97467);\n\nSELECT t.id, crm.id, t.name, crm.sync_objects, crm.provider, crm.last_synced_at FROM crm_configurations crm join teams t on t.crm_id = crm.id\nwhere t.status = 'active' AND crm.provider = 'hubspot' AND crm.last_synced_at < '2025-10-22 00:00:00';\n\nSELECT * FROM activities WHERE uuid_to_bin('fa09449f-cba9-496a-b8f3-865cd3c72351') = uuid;\nSELECT * FROM crm_configurations where id = 184;\nSELECT * FROM teams WHERE id = 246;\nSELECT * FROM social_accounts WHERE sociable_id = 9259 and provider = 'hubspot';\n\nSELECT * FROM users WHERE email LIKE '%rhian.old@bud.co.uk%'; # 17700\nSELECT * FROM teams WHERE id = 551;\n\nSELECT * FROM crm_configurations WHERE id = 471;\nSELECT * FROM activities WHERE crm_configuration_id = 471 and crm_provider_id IS NOT NULL;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 471;\nSELECT * FROM crm_fields WHERE id = 307260;\nSELECT * FROM crm_field_values WHERE crm_field_id = 307260;\n\nselect * from crm_layouts where crm_configuration_id = 471;\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1547;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1548;\n\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 = 551 and sa.provider = 'hubspot';\n\nSELECT * FROM teams WHERE name LIKE '%$PCS%';\n\n# ********************************************************************************************************\nselect * from crm_configurations crm\njoin teams t on t.crm_id = crm.id\nwhere t.status = 'active'\nand crm.provider = 'hubspot';\n\n# $slug = 'HUBSPOT_WEBHOOK_SYNC';\n# $team = Jiminny\\Models\\Team::find(2);\n# $feature = Feature::query()->where('slug', $slug)->first();\n# TeamFeature::query()->create(['feature_id' => $feature->getId(),'team_id' => $team->getId()]);\n\n# hubspot_webhook_metrics\n\nselect * from crm_configurations where id = 331; # 416\nSELECT * FROM teams WHERE id = 416;\nSELECT * FROM opportunities WHERE team_id = 190;\n\nSELECT * FROM teams WHERE name LIKE '%Lead Forensics%';\nSELECT sa.id,\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 = 190 and sa.provider = 'hubspot';\n\n\n\nSELECT * FROM teams WHERE name LIKE '%Rapaport%'; # 431, 337\nSELECT * FROM teams where id = 431;\nSELECT * FROM crm_configurations where team_id = 431;\nSELECT * FROM activity_providers where team_id = 431;\nSELECT * FROM activities where crm_configuration_id = 337 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\nSELECT sa.id,\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 = 431 and sa.provider = 'salesforce';\n\nSELECT * FROM teams WHERE name LIKE '%BiP%'; # 401, 320\nSELECT * FROM teams where id = 401;\nSELECT * FROM crm_configurations where team_id = 401;\nSELECT * FROM activity_providers where team_id = 401;\nSELECT * FROM activities where crm_configuration_id = 320 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\nSELECT sa.id,\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 = 401 and sa.provider = 'salesforce';\n\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 307; # 379 - Story Terrace Inc , portalId: 3921157\nSELECT * FROM contacts WHERE team_id = 379 and updated_at > '2026-01-31 11:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 379 and updated_at > '2026-02-01 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 379 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\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 = 379 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 485; # 563 - LATUS Group (ad94d501-5d09-44fd-878f-ca3a9f8865c3) , portalId: 3904501\nSELECT * FROM opportunities WHERE team_id = 563 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 563 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 338; # 432 - Formalize , portalId: 9214205\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 = 432 and sa.provider = 'hubspot';\nSELECT * FROM opportunities WHERE team_id = 432 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 432 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 436; # 519 - Moxso , portalId: 25531989\nSELECT * FROM opportunities WHERE team_id = 519 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 519 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 96; # 119 - Nourish Care , portalId: 26617984\nSELECT * FROM opportunities WHERE team_id = 119 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 119 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 331; # 416 - The National College , portalId: 7213852\nSELECT * FROM opportunities WHERE team_id = 416 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 416 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 308; # 380 - Foodles , portalId: 7723616\nSELECT * FROM opportunities WHERE team_id = 380 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 380 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 379; # 471 - imat-uve , portalId: 9177354\nSELECT * FROM opportunities WHERE team_id = 471 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 471 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 465; # 545 - Spotler , portalId: 144759271\nSELECT * FROM opportunities WHERE team_id = 545 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 545 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 455; # 537 - indevis , portalId: 25666868\nSELECT * FROM opportunities WHERE team_id = 537 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 537 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 200; # 265 - Jobadder , portalId: 6426676\nSELECT * FROM opportunities WHERE team_id = 265 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 265 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 335; # 429 - Eletive , portalId: 6110563\nSELECT * FROM opportunities WHERE team_id = 429 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 429 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 363; # 456 - Global Group , portalId: 8901981\nSELECT * FROM opportunities WHERE team_id = 456 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 456 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 297; # 369 - Unbiased , portalId: 9229005\nSELECT * FROM opportunities WHERE team_id = 369 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 369 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 353; # 449 - Fuuse , portalId: 25781745\nSELECT * FROM opportunities WHERE team_id = 449 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 449 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 487; # 566 - Nimbus , portalId: 39982590\nSELECT * FROM opportunities WHERE team_id = 566 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 566 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 487;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1630;\nselect * from crm_fields where crm_configuration_id = 487 and\n(uuid_to_bin('4c6b2971-64d4-45b8-b377-427be758b5a5') = uuid or uuid_to_bin('59e368d8-65a0-4b77-b611-db37c99fbe68') = uuid);\nSELECT * FROM crm_field_values WHERE crm_field_id = 375177;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 420; # 506 - voiio , portalId: 145629154\nSELECT * FROM opportunities WHERE team_id = 506 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 506 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 479; # 558 - Momice , portalId: 535962\nSELECT * FROM opportunities WHERE team_id = 558 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 558 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 59; # 80 - Storyclash GmbH , portalId: 4268479\nSELECT * FROM opportunities WHERE team_id = 80 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 80 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 175; # 203 - Team iAM , portalId: 5534732\nSELECT * FROM opportunities WHERE team_id = 203 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 203 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 368; # 460 - OneTouch Health , portalId: 5534732183355\nSELECT * FROM opportunities WHERE team_id = 460 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 460 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\n\n\nselect * from users where id = 29643;\nSELECT * FROM crm_field_values WHERE crm_field_id = 375177;\n# ********************************************************************\nSELECT * FROM teams WHERE name LIKE '%Buynomics%'; # 462, 482, 14910\nSELECT * FROM activities WHERE crm_configuration_id = 482\nand type NOT IN ('email-inbound', 'email-outbound')\n# and description like '%The call focused on understanding Welch%'\norder by id desc;\n\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 = 462 and sa.provider = 'salesforce';\n\nselect * from contacts where crm_configuration_id = 482 and name = 'Cyndall Hill'; # 15504749\nselect * from contacts where id = 10891096; # 482\nSELECT * FROM activities WHERE crm_configuration_id = 482\nand type NOT IN ('email-inbound', 'email-outbound')\nand contact_id = 15504749\norder by id desc;\n\nselect * from activities where id = 36793003; # 96cc7bc1-8622-4d27-92f4-baf664fc1a56, 00UOf00000PDdOXMA1\nselect * from transcription where id = 7646782;\nselect * from ai_prompts where transcription_id = 7646782;\n\n# ********************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('7a8471a3-847e-4822-802b-ddf426bbc252') = uuid; # 37370018\nSELECT * FROM activity_summary_logs WHERE activity_id = 37370018;\nSELECT * FROM teams WHERE id = 555;\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 = 555 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('7c17b8aa-09df-4f85-a0f7-51f47afd712d') = uuid; # 37395250\nSELECT * FROM activities WHERE uuid_to_bin('14d60388-260d-494b-aa0d-63fdb1c78026') = uuid; # 37395250\n\nSELECT a.* FROM activities a JOIN crm_configurations c on c.id = a.crm_configuration_id\nwhere a.type IN ('softphone', 'softphone-outbound') and c.provider = 'hubspot'\nand a.provider NOT IN ('hubspot')\n# and a.provider IN ('salesloft')\n# and c.id NOT IN (70)\n# and a.duration > 30\n# and actual_start_time > '2026-02-05 00:00:00'\norder by a.id desc;\n\nSELECT * FROM activities WHERE id = 37549787;\nSELECT * FROM crm_profiles WHERE user_id = 17613;\n\nSELECT * FROM crm_configurations WHERE id = 70;\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 = 93 and sa.provider = 'hubspot';\n\nSELECT asf.activity_search_id, asf.id, asf.value\nFROM activity_search_filters asf\nWHERE asf.filter = 'group_id'\nAND asf.value IN (\n SELECT CONCAT(\n HEX(SUBSTR(uuid, 5, 4)), '-',\n HEX(SUBSTR(uuid, 3, 2)), '-',\n HEX(SUBSTR(uuid, 1, 2)), '-',\n HEX(SUBSTR(uuid, 9, 2)), '-',\n HEX(SUBSTR(uuid, 11))\n )\n FROM groups\n WHERE deleted_at IS NOT NULL\n);\n\nSELECT * FROM crm_configurations WHERE id = 373; # KPSBremen.de 465 # - no social account\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 = 465 and sa.provider = 'hubspot';\n\nselect * from crm_configurations where id = 494;\n\nSELECT * FROM teams WHERE name LIKE '%splose%'; # 572, 495, 18708\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 = 572 and sa.provider = 'pipedrive';\n\nselect * from opportunities where team_id = 572\n# and name like '%Onebright%'\n# and is_closed = 1 and is_won = 0\n order by id desc;\n\n\nselect * from users where deleted_at is null and status = 2;\n\nselect * from contacts where id = 17900517;\nselect * from accounts where id = 10109838;\nselect * from opportunities where id = 6955880;\n\nselect * from opportunity_contacts where opportunity_id = 6955880;\nselect * from opportunity_contacts where contact_id = 17900517;\n\nselect * from contact_roles cr join crm_configurations crm on cr.crm_configuration_id = crm.id\nwhere crm.provider != 'salesforce';\n\nSELECT * FROM activities WHERE uuid_to_bin('adcb8331-5988-4353-834e-383a355abba2') = uuid; # 38056424, crm 104659682404\nselect * from teams where id = 456;\nSELECT * FROM crm_configurations WHERE id = 363;\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 = 456 and sa.provider = 'hubspot';\n\nselect * from crm_layouts where crm_configuration_id = 363;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id IN (1203, 1204, 1635);\nSELECT * FROM crm_fields WHERE id IN (181536, 181538, 213455);\n\nSELECT * FROM teams WHERE name LIKE '%Electric%'; # 342, 272, 12767\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 = 342 and sa.provider = 'pipedrive';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 and name like 'NORTHUMBRIA POL%'; # and updated_at > '2025-07-01 00:00:00';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 order by remotely_created_at asc; # and updated_at > '2025-07-01 00:00:00';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 and updated_at > '2026-01-01 00:00:00';\nSELECT * FROM crm_fields WHERE crm_configuration_id = 272 and object_type = 'opportunity';\nSELECT * FROM crm_field_values WHERE crm_field_id = 127164;\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 = 342 and sa.provider = 'pipedrive';\n\nSELECT * FROM teams WHERE id = 472;\nSELECT * FROM crm_configurations WHERE id = 380;\nselect * from activities where id = 38285673; # 38285673\nSELECT * FROM users WHERE id = 16942;\nSELECT * FROM groups WHERE id = 1964;\nSELECT * FROM playbooks WHERE id = 2033;\n\nselect * from teams where created_at > '2026-03-09';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 499; # 1065\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1678;\n\nSELECT * FROM teams WHERE id = 575;\nselect * from opportunities where team_id = 575;\n\nSELECT * FROM activities WHERE uuid_to_bin('96b1261f-2357-49f9-ab38-23ce12008ea0') = uuid;\n\nselect * from contacts c\nwhere c.crm_configuration_id = 370 order by c.updated_at desc;\n\nSELECT * FROM participants where activity_id = 38833541;\nSELECT * FROM participants where activity_id = 39216301;\nSELECT * FROM activity_summary_logs where activity_id = 39216301;\nSELECT * FROM activities WHERE uuid_to_bin('c7d99fbe-1fb1-41f2-8f4d-52e2bf70e1e9') = uuid; # 38833541, crm 478116564181\nSELECT * FROM activities WHERE uuid_to_bin('2e6ff4d3-9faa-447a-a8c1-9acde4d885ae') = uuid; # 39216301, crm 480171536586\nselect * from crm_profiles where crm_configuration_id = 319 and crm_provider_id = 525785080;\nselect * from opportunities where crm_configuration_id = 319 and crm_provider_id = 410150124747;\nselect * from accounts where crm_configuration_id = 319 and crm_provider_id = 47150650569;\nselect * from contacts where crm_configuration_id = 319 and crm_provider_id IN ('665587441856', '742723347700');\n# owner 13236 525785080\n# contact 1 16779180 665587441856 - activity - Alex Howes alex@supportroom.com created 2026-01-26\n# contact 2 19247563 742723347700 - ash@supportroom.com 2026-03-24\n# company 4176133 47150650569\n# deal 7100953 410150124747\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 = 400 and sa.provider = 'hubspot';\n\nselect * from features;\nselect * from team_features where feature_id = 40;\n\nselect * from teams where id = 556; # owner: 18101, crm: 477\nselect * from crm_configurations where id = 477;\nSELECT * FROM users WHERE id = 18101;\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 = 556 and sa.provider = 'integration-app';\n\nselect * from opportunities where id = 7594349;\nselect * from opportunity_stages where opportunity_id = 7594349 order by created_at desc;\nselect * from business_processes where id = 6024;\nselect * from business_process_stages where stage_id = 16352;\nselect * from business_process_stages where business_process_id = 6024;\nselect * from stages where team_id = 459;\nselect * from teams where id = 459;\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 = 459 and sa.provider = 'hubspot';\n\nSELECT os.stage_id, s.crm_provider_id, s.name, COUNT(*) as cnt\nFROM opportunity_stages os\nJOIN stages s ON s.id = os.stage_id\nWHERE os.opportunity_id = 7594349\nGROUP BY os.stage_id, s.crm_provider_id, s.name\nORDER BY cnt DESC;\n\nSELECT s.id, s.crm_provider_id, s.name, s.team_id, s.crm_configuration_id\nFROM stages s\nJOIN business_process_stages bps ON bps.stage_id = s.id\nWHERE bps.business_process_id = 6024\nAND s.crm_provider_id = 'contractsent';\n\nselect * from stages where id IN (16352,20612,18281,7344,16378,16309,5036,15223,14535,6293,12098,11607)\n\nSELECT * FROM teams WHERE name LIKE '%Pulsar Group%'; # 472, 380, 15138, raza.gilani@vuelio.com\nselect * from playbooks where team_id = 472; # event 226147\nSELECT * FROM playbook_categories WHERE playbook_id = 2288;\nSELECT * FROM crm_fields WHERE id = 226147;\nSELECT * FROM crm_field_values WHERE crm_field_id = 226147;\n\nSELECT * FROM crm_configurations WHERE id = 380;\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 = 472 and sa.provider = 'salesforce';\n\nselect * from activities where id = 58081273;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2;\n\nSELECT * FROM users WHERE name LIKE '%Neil Hoyle%'; # 17651\nSELECT * FROM social_accounts WHERE sociable_id = 17651;\n\nSELECT * FROM activities WHERE uuid_to_bin('975c6830-7d49-4c1e-b2e9-ac80c10a738a') = uuid;\nSELECT * FROM opportunities WHERE id IN (7842553, 6211727);\nSELECT * FROM contacts WHERE id IN (10202724, 6211727);\nSELECT * FROM opportunity_stages WHERE opportunity_id = 7842553;\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 = 519 and sa.provider = 'hubspot';\n\nselect * from crm_configurations where id = 436;\nselect * from crm_profiles where crm_configuration_id = 436; # 76091797 -> 16612\n\nselect * from contact_roles where contact_id = 10202724;\n\nselect * from stages where team_id = 519; # 18778\n18775\n\nSELECT\n id,\n crm_provider_id,\n stage_id,\n is_closed,\n is_won,\n stage_updated_at,\n updated_at\nFROM opportunities\nWHERE id IN (6211727, 7842553);\n\nSELECT * FROM opportunity_contacts\nWHERE opportunity_id = 6211727 AND contact_id = 10202724;\n\nSELECT id, name, stage_id, is_closed, is_won, updated_at, remotely_created_at\nFROM opportunities\nWHERE account_id = 8179134\nORDER BY updated_at DESC;\n\n\nselect * from text_relays where created_at > '2026-01-01';\nAND id IN (691, 692);\n\nselect * from teams;\n\n# ***************\nSELECT DISTINCT u.id, u.email, u.name, u.softphone_number, COUNT(a.id) as sms_count\nFROM users u\nINNER JOIN activities a ON u.id = a.user_id\nWHERE a.type LIKE 'sms%'\nAND a.created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)\nGROUP BY u.id, u.email, u.name, u.softphone_number\nORDER BY sms_count DESC;\n\nSELECT DISTINCT u.id, u.email, u.name, u.team_id, t.name as team_name,\n t.twilio_sms_sid, t.twilio_messaging_sid\nFROM users u\nINNER JOIN teams t ON u.team_id = t.id\nWHERE (t.twilio_sms_sid IS NOT NULL OR t.twilio_messaging_sid IS NOT NULL)\nAND u.status = 1\nORDER BY t.name, u.email;\n\nSELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, salesforce-admin@tourlane.com\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 = 187 and sa.provider = 'salesforce';\n\nselect * from activities where id = 31264367;\nselect * from contacts where id = 6331639;\nselect * from accounts where id = 4156632;\nselect * from opportunities where id = 4843610;\n# update `activities` set `account_id` = 4156632, `contact_id` = 6331639, `opportunity_id` = 4843610,\n# `stage_id` = 13273, `activities`.`updated_at` = 2026-05-22 07:16:17 where `id` = 31264367)\"\n\nselect * from text_relays where created_at > '2026-05-01';\n\nselect * from activities order by id desc;\n\nselect * from users where name like '%Subra%';\n\nSELECT * FROM opportunities WHERE uuid_to_bin('04a9cfad-2c87-4453-9e72-20aeb78ccf8d') = uuid;\nselect * from teams where id = 555;\nselect * from stages where team_id = 555;\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 = 100 and sa.provider = 'hubspot';","depth":4,"on_screen":true,"value":"SELECT * FROM team_features where team_id = 1;\n\nSELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922\nSELECT * FROM users WHERE team_id = 340; # 12015\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 340\nand sa.provider = 'salesforce';\n# and sa.provider = 'salesloft';\n\nselect * from crm_fields where crm_configuration_id = 270 and object_type = 'event';\n# 125558 - Event Type - Event_Type__c\n# 125552 - Event Status - Event_Status__c\n\nSELECT * FROM sidekick_settings WHERE team_id = 340;\n\nSELECT * FROM crm_field_values WHERE crm_field_id in (125552);\n\nselect * from activities where crm_configuration_id = 270\nand type = 'conference' and crm_provider_id IS NOT NULL\nand actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;\n\nSELECT * FROM activities WHERE id = 20871677;\nSELECT * FROM crm_field_data WHERE activity_id = 20871677;\n\nselect * from crm_layouts where crm_configuration_id = 270;\nselect * from crm_layout_entities where crm_layout_id in (886,887);\n\nSELECT * FROM crm_configurations WHERE id = 270;\n\nselect * from playbooks where team_id = 340; # 1514\nselect * from groups where team_id = 340;\nSELECT * FROM crm_fields WHERE id IN (125393, 125401);\n\nselect g.name as 'team name', p.name as 'playbook name', f.label as 'activity type field' from groups g\njoin playbooks p on g.playbook_id = p.id\njoin crm_fields f on p.activity_field_id = f.id\nwhere g.team_id = 340;\n\nSELECT * FROM activities WHERE uuid_to_bin('0c180357-67d2-419e-a8c3-b832a3490770') = uuid; # 20448716\nselect * from crm_field_data where object_id = 20448716;\n\nselect * from activities where crm_configuration_id = 270 and provider = 'salesloft' order by id desc;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%CybSafe%'; # 343,273,12008\nselect * from opportunities where team_id = 343;\nselect * from opportunities where team_id = 343 and crm_provider_id = '18099102526';\nselect * from opportunities where team_id = 343 and account_id = 945217482;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nselect * from accounts where team_id = 343 order by name asc;\n\nselect * from stages where crm_configuration_id = 273 and type = 'opportunity';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Voyado%'; # 353,283,12143\nSELECT * FROM activities WHERE crm_configuration_id = 283 and account_id = 3777844 order by id desc;\nSELECT * FROM accounts WHERE team_id = 353 AND name LIKE '%Salesloft%';\nSELECT * FROM activities WHERE id = 20717903;\n\nselect * from participants where activity_id IN (20929172,20928605,20928468,20926272,20926271,20926270,20926269,20916499,20916454,20916436,20916435,20900015,20900014,20900013,20897312,20897243,20897241,20897237,20897232,20897229,20893648,20893231,20893230,20893229,20893228,20889784,20885039,20885038,20885037,20885036,20885035,20882728,20882708,20882703,20882702,20869828,20869811,20869806,20869801,20869799,20869798,20869796,20869795,20869794,20869761,20869760,20869759,20868688,20868687,20850340,20847195,20841710,20833967,20827021,20825307,20825305,20825297,20824615,20824400,20823927,20821760,20795588,20794233,20794057,20793710,20785811,20781789,20781394,20781307,20762651,20758453,20758282,20757323,20756643,20756636,20756629,20756627,20756606,20756605,20756604,20756603,20756602,20756600,20756599,20756598,20756595,20756594,20756589,20756587,20756577,20756573,20748918,20748386,20748385,20748384,20748383,20748382,20748381,20748380,20748379,20748377,20748375,20748373,20743301,20717905,20717904,20717903,20717901,20717899);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 353\nand sa.provider = 'salesforce';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%modern world business solutions%'; # 345,275,12016, l.atkinson@mwbsolutions.co.uk\nSELECT * FROM activities WHERE uuid_to_bin('3921d399-3fef-4609-a291-b0097a166d43') = uuid;\n# id: 20940638, user: 12022, contact: 5305871\nSELECT * FROM activity_summary_logs WHERE activity_id = 20940638;\nselect * from contacts where team_id = 345 and crm_provider_id = '30891432415' order by name asc; # 5305871\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 345\nand sa.provider = 'hubspot';\n\nselect * from users where team_id = 345 and id = 12022;\nSELECT * FROM crm_profiles WHERE user_id = 12022;\nSELECT * FROM participants WHERE activity_id = 20940638;\nSELECT * FROM users u\nJOIN crm_profiles cp ON u.id = cp.user_id\nWHERE u.team_id = 345;\n\nselect * from contacts where team_id = 345 and crm_provider_id = '30880813535' order by name desc; # 5305871\n\nselect * from team_features where team_id = 345;\nSELECT * FROM activities WHERE uuid_to_bin('11701e2d-2f82-4dab-a616-1db4fad238df') = uuid; # 21115197\nSELECT * FROM participants WHERE activity_id = 20897406;\n\n\n\nSELECT * FROM activities WHERE uuid_to_bin('63ba55cd-1abc-447d-83da-0137000005b7') = uuid; # 20953912\nSELECT * FROM activities WHERE crm_configuration_id = 275 and provider = 'ringcentral' and title like '%1252629100%';\n\n\nSELECT * FROM activities WHERE id = 20946641;\nSELECT * FROM crm_profiles WHERE user_id = 10211;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120,97,10984, triger@lunio.ai\nSELECT * FROM opportunities WHERE crm_configuration_id = 97 and crm_provider_id = '006N1000006c5PpIAI';\nselect * from stages where crm_configuration_id = 97 and type = 'opportunity';\nselect * from opportunities where team_id = 120;\n\n\nselect * from crm_configurations crm join teams t on crm.id = t.crm_id\nwhere 1=1\nAND t.current_billing_plan IS NOT NULL\nAND crm.auto_sync_activity = 0\nand crm.provider = 'hubspot';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Exclaimer%'; # 270,205,10053,james.lewendon@exclaimer.com\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 270\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('b54df794-2a9a-4957-8d80-09a600ead5f8') = uuid; # 21637956\nSELECT * FROM crm_profiles WHERE user_id = 11446;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Cygnetise%'; # 372,300,12554, alex.chikly@cygnetise.com\nselect * from playbooks where team_id = 372;\nselect * from crm_fields where crm_configuration_id = 300 and object_type = 'event'; # 141340\nSELECT * FROM crm_field_values WHERE crm_field_id = 141340;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 372\nand sa.provider = 'salesforce';\n\nselect * from crm_profiles where crm_configuration_id = 300;\nSELECT * FROM crm_configurations WHERE team_id = 372;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Planday%'; # 291,242,11501,mfa@planday.com\nSELECT * FROM opportunities WHERE team_id = 291 and crm_provider_id = '006bG000005DO86QAG'; # 3207756\nselect * from crm_field_data where object_id = 3207756;\nSELECT * FROM crm_fields WHERE id = 111834;\n\nselect f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value\nFROM crm_fields f\nJOIN crm_field_data fd ON f.id = fd.crm_field_id\nWHERE f.crm_configuration_id = 242\nAND f.object_type = 'opportunity'\nAND fd.object_id IN (3207756)\nORDER BY fd.object_id, fd.updated_at;\n\nSELECT * FROM crm_configurations WHERE auto_connect = 1;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150,salesforce-admin@tourlane.com\nselect * from group_deal_risk_types drgt join groups g on drgt.group_id = g.id\nwhere g.team_id = 187;\n\nselect * from `groups` where team_id = 187;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 187\nand sa.provider = 'salesforce';\n\n# Destination - 98870 - Destination__c\n# Stage - 79014 - StageName\n# Land Arrangement - 98856 - Land_Arrangement__c\n# Flight - 98848 - Flight__c\n# Last activity date - 98812 - LastActivityDate\n# Last modified date - 98809 - LastModifiedDate\n# Last inbound mail timestamp - 99151 - Last_Inbound_Mail_Timestamp__c\n# next call - 98864 - Next_Call__c\n\nselect * from crm_fields where crm_configuration_id = 209 and object_type = 'opportunity';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 209;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;\n\nselect * from opportunities where team_id = 187 and name LIKE'%Muriel Sal%';\nselect * from opportunities where team_id = 187 and user_id = 9951 and is_closed = 0;\nselect * from activities where opportunity_id = 3538248;\n\nSELECT * FROM crm_profiles WHERE user_id = 8150;\n\nselect * from deal_risks where opportunity_id = 3538248;\n\nselect * from teams where crm_id IS NULL;\n\nSELECT opp.id AS opportunity_id,\n u.group_id AS group_id,\n MAX(\n CASE\n WHEN a.type IN (\"sms-inbound\", \"sms-outbound\") THEN a.created_at\n ELSE a.actual_end_time\n END) as last_date\nFROM opportunities opp\nleft join activities a on a.opportunity_id = opp.id\ninner join users u on opp.user_id = u.id\nwhere opp.user_id IN (9951)\n\nAND opp.is_closed = 0\nand a.status IN ('completed', 'received', 'delivered') OR a.status IS NULL\ngroup by opp.id;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Cybsafe%'; # 343,301,12008,polly.morphew@cybsafe.com\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 301;\nSELECT * FROM contacts WHERE id = 6612363;\nSELECT * FROM accounts WHERE id = 4235676;\nSELECT * FROM opportunities WHERE crm_configuration_id = 301 and crm_provider_id = 32983784868;\nselect * from opportunity_stages where opportunity_id = 4503759;\n# SELECT * FROM opportunities WHERE id = 4569937;\n\nselect * from activities where crm_configuration_id = 301;\nSELECT * FROM activities WHERE uuid_to_bin('d3b2b28b-c3d0-4c2d-8ed0-eef42855278a') = uuid; # 26330370\nSELECT * FROM participants WHERE activity_id = 26330370;\n\nSELECT * FROM teams WHERE id = 375;\nselect * from playbooks where team_id = 375;\n\nselect * from stages where crm_configuration_id = 301 and type = 'opportunity';\n\nselect * from teams;\nselect * from contact_roles;\n\nSELECT * FROM opportunities WHERE team_id = 343 and user_id = 12871 and close_date >= '2024-11-01';\n\nselect * from users u join crm_profiles cp on cp.user_id = u.id where u.team_id = 343;\n\nSELECT * FROM crm_field_data WHERE object_id = 3771706;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_fields WHERE crm_configuration_id = 301 and object_type = 'opportunity'\nand crm_provider_id LIKE \"%traffic_light%\";\nSELECT * FROM crm_field_values WHERE crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531);\n\nSELECT fd.* FROM opportunities o\nJOIN crm_field_data fd ON o.id = fd.object_id\nWHERE o.team_id = 343\n# and o.user_id IS NOT NULL\nand fd.crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531)\nand fd.value != ''\norder by value desc\n# group by o.id\n;\n\nSELECT * FROM opportunities WHERE id = 3769843;\n\nSELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150, salesforce-admin@tourlane.com\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 209;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Funding Circle%'; # 220,177,8603,aswini.mishra@fundingcircle.com\nSELECT * FROM activities WHERE uuid_to_bin('7a40e99b-3b37-4bb1-b983-325b81801c01') = uuid; # 23139839\n\n\nSELECT * FROM opportunities WHERE id = 3855992;\n\nSELECT * FROM users WHERE name LIKE '%Angus Pollard%'; # 8988\n\nSELECT * FROM teams WHERE name LIKE '%Story Terrace%'; # 379, 307, 12894\nSELECT * FROM crm_fields WHERE crm_configuration_id = 307 and object_type != 'opportunity';\n\nselect * from contacts where team_id = 379 and name like '%bebro%'; # 5874411, crm: 77229348507\nSELECT * FROM crm_field_data WHERE object_id = 5874411;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 379\nand sa.provider = 'hubspot';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%mentio%'; # 117, 94, 6371, nikhil.kumar@mention-me.com\nSELECT * FROM activities WHERE uuid_to_bin('82939311-1af0-4506-8546-21e8d1fdf2c1') = uuid;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, salesforce-admin@tourlane.com\nSELECT * FROM opportunities WHERE team_id = 187 and crm_provider_id = '006Se000008xfvNIAQ'; # 3537793\nselect * from generic_ai_prompts where subject_id = 3537793;\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120, 97, 10984, triger@lunio.ai\nSELECT * FROM crm_configurations WHERE id = 97;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 97;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 355;\nSELECT * FROM crm_fields WHERE id = 32682;\n\nselect cfd.value, o.* from opportunities o\njoin crm_field_data cfd on o.id = cfd.object_id and cfd.crm_field_id = 32682\nwhere team_id = 120\nand cfd.value != ''\n;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 120\nand sa.provider = 'salesforce';\n\nselect * from opportunities where team_id = 120 and crm_provider_id = '006N1000007X8MAIA0';\nSELECT * FROM crm_field_data WHERE object_id = 2313439;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE id = 410;\nSELECT * FROM teams WHERE name LIKE '%Local Business Oxford%';\nselect * from scorecards where team_id = 410;\nselect * from scorecard_rules;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Funding%'; # 220, 177, 8603, aswini.mishra@fundingcircle.com\nselect * from activities a\njoin opportunities o on a.opportunity_id = o.id\njoin users u on o.user_id = u.id\nwhere a.crm_configuration_id = 177 and a.type LIKE '%email-out%'\n# and a.actual_end_time > '2024-12-16 00:00:00'\n# and o.remotely_created_at > '2024-12-01 00:00:00'\n# and u.group_id = 1014\nand u.id = 9021\norder by a.id desc;\nSELECT * FROM opportunities WHERE id in (3981384,4017346);\nSELECT * FROM users WHERE team_id = 220 and id IN (8775, 11435);\n\nselect * from users where id = 9021;\nselect * from inboxes where user_id = 9021;\n\nselect * from inbox_emails where inbox_id = 1349 and email_date > '2024-12-18 00:00:00';\n\nselect * from email_messages where team_id = 220\nand orig_date > '2024-12-16 00:00:00' and orig_date < '2024-12-19 00:00:00'\nand subject LIKE '%Personal%'\n# and 'from' = 'credit@fundingcircle.com'\n;\n\nselect * from activities a\njoin opportunities o on a.opportunity_id = o.id\nwhere a.user_id = 9021 and a.type LIKE '%email-out%'\nand a.actual_end_time > '2024-12-18 00:00:00'\nand o.user_id IS NOT NULL\nand o.remotely_created_at > '2024-12-01 00:00:00'\norder by a.id desc;\n\nSELECT * FROM opportunities WHERE team_id = 220 and name LIKE '%Right Car move Limited%' and id = 3966852;\nselect * from activities where crm_configuration_id = 177 and type LIKE '%email%' and opportunity_id = 3966852 order by id desc;\n\nselect * from team_settings where name IN ('useCloseDate');\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Hurree%'; # 104, 81, 6175, jfarrell@hurree.co\nSELECT * FROM opportunities WHERE team_id = 104 and name = 'PropOp';\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 104\nand sa.provider = 'hubspot';\n\nselect * from crm_configurations where last_synced_at > '2025-01-19 01:00:00'\nselect * from teams where crm_id IS NULL;\n\nselect t.name as 'team', u.name as 'owner', u.email, u.phone\nfrom teams t\njoin activity_providers ap on t.id = ap.team_id\njoin users u on t.owner_id = u.id\nwhere 1=1\n and t.status = 'active'\n and ap.is_enabled = 1\n# and u.status = 1\n and ap.provider = 'ms-teams';\n\nselect * from crm_configurations where provider = 'bullhorn'; # 344\nSELECT * FROM teams WHERE id = 442; # 14293\nselect * from users where team_id = 442;\nselect * from social_accounts sa where sa.sociable_id = 14293;\nselect * from invitations where team_id = 442;\n\n# ********************************************************************************************************\nSELECT * FROM users WHERE email LIKE '%nea.liikamaa@eletive.com%'; # 14022\nSELECT * FROM teams WHERE id = 429;\nselect * from opportunities where team_id = 429 and crm_provider_id IN (16157415775, 22246219645);\nselect * from activities where opportunity_id in (4340436,4353519);\n\nselect * from transcription where activity_id IN (25630961,25381771);\nselect * from generic_ai_prompts where subject_id IN (4353519);\n\nSELECT\n a.id as activity_id,\n a.opportunity_id,\n a.type as activity_type,\n a.language,\n CONCAT(a.title, a.description) AS mail_content,\n e.from AS mail_from,\n e.to AS mail_to,\n e.subject AS mail_subject,\n e.body AS mail_body,\n p.type as prompt_type,\n p.status as prompt_status,\n p.content AS prompt_content,\n a.actual_start_time as created_at\nFROM activities a\n LEFT JOIN ai_prompts p ON a.transcription_id = p.transcription_id AND p.deleted_at IS NULL\n LEFT JOIN email_messages e ON a.id = e.activity_id\nWHERE a.actual_start_time > '2024-01-01 00:00:00'\n AND a.opportunity_id IN (4353519)\n AND a.status IN ('completed', 'received', 'delivered')\n AND a.deleted_at IS NULL\n AND a.type NOT IN ('sms-inbound', 'sms-outbound')\nORDER BY a.opportunity_id ASC, a.id ASC;\n\nSELECT * FROM users WHERE name LIKE '%George Fierstone%'; # 14293\nSELECT * FROM teams WHERE id = 442;\nSELECT * FROM crm_configurations WHERE id = 344;\nselect * from team_features where team_id = 442;\nselect * from groups where team_id = 442;\nselect * from playbooks where team_id = 442;\nselect * from playbook_categories where playbook_id = 1729;\nselect * from crm_fields where crm_configuration_id = 344 and id = 172024;\nSELECT * FROM crm_field_values WHERE crm_field_id = 172024;\nselect * from crm_layouts where crm_configuration_id = 344;\nselect * from playbook_layouts where playbook_id = 1729;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 221, 9444\n\nselect s.*\n# , s.sent_at, u.name, a.*\nfrom activity_summary_logs s\ninner join activities a on a.id = s.activity_id\ninner join users u on u.id = a.user_id\nwhere a.crm_configuration_id = 356\nand s.sent_at > date_sub(now(), interval 60 day)\norder by a.actual_end_time desc;\n\nselect * from activities a\n# inner join activity_summary_logs s on s.activity_id = a.id\nwhere a.crm_configuration_id = 356 and a.actual_end_time > date_sub(now(), interval 60 day)\n# and a.crm_provider_id is not null\n# and provider <> 'ringcentral'\nand status = 'completed'\norder by a.actual_end_time desc;\n\nselect * from teams order by id desc; # 17328, 32, 17830, integration-account@jiminny.com\nSELECT * FROM users;\nSELECT * FROM users where team_id = 260 and status = 1; # 201 - 150 active\nSELECT * FROM teams WHERE id = 260;\nselect * from team_settings where team_id = 260;\nselect * from crm_configurations where team_id = 260;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 356;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1184;\n\nselect * from accounts where crm_configuration_id = 221 order by id desc; # 7000\nselect * from leads where crm_configuration_id = 221 order by id desc; # 0\nselect * from contacts where crm_configuration_id = 221 order by id desc; # 200 000\nselect * from opportunities where crm_configuration_id = 221 order by id desc; # 0\nselect * from crm_profiles where crm_configuration_id = 221 order by id desc; # 23\nselect * from crm_fields where crm_configuration_id = 221;\nselect * from crm_field_values where crm_field_id = 5302 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 221 order by id desc;\nselect * from stages where crm_configuration_id = 221 order by id desc;\n\nselect * from accounts where crm_configuration_id = 356 order by id desc; # 7000\nselect * from leads where crm_configuration_id = 356 order by id desc; # 0\nselect * from contacts where crm_configuration_id = 356 order by id desc; # 200 000\nselect * from opportunities where crm_configuration_id = 356 order by id desc; # 0\nselect * from crm_profiles where crm_configuration_id = 356 order by id desc; # 23\nselect * from crm_fields where crm_configuration_id = 356;\nselect * from crm_field_values where crm_field_id = 5302 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 356 order by id desc;\nselect * from stages where crm_configuration_id = 356 order by id desc;\n\nselect * from playbooks where team_id = 260 order by id desc; # 4 (2 deleted)\nselect * from groups where team_id = 260 order by id desc; # 27 groups, (2 deleted)\nselect * from playbook_layouts where playbook_id IN (1410,1409,1276,1254); # 4\nselect ce.* from calendars c\njoin users u on c.user_id = u.id\njoin calendar_events ce on c.id = ce.calendar_id\nwhere u.team_id = 260\nand (ce.start_time > '2025-02-21 00:00:00')\n;\n# calendar events 1207\n#\n\nselect * from opportunities where team_id = 260;\nSELECT * FROM crm_field_data WHERE object_id = 4696496;\n\nselect * from activities where crm_configuration_id = 356 and crm_provider_id IS NOT NULL;\nselect * from activities where crm_configuration_id IN (221) and provider NOT IN ('ms-teams', 'uploader', 'zoom-bot')\n# and type = 'conference' and status = 'scheduled' and activities.is_internal = 0\nand created_at > '2024-03-01 00:00:00'\norder by id desc; # 880 000, ringcentral, avaya\nSELECT * FROM participants WHERE activity_id = 26371744;\n\n# all activities 942 000 +\n# conference 7385 - scheduled 984 - external 343\n\nselect * from activities where id = 26321812;\nselect * from participants where activity_id = 26321812;\nselect * from participants where activity_id in (26414510,26414514,26414516,26414604,26414653,26414655);\nselect * from leads where id in (720428,689175,731546,645866,621037);\n\nselect * from users where id = 13841;\nselect * from opportunities where user_id = 9541;\nselect * from stages where id = 15900;\n\nselect * from accounts where\n# id IN (4160055,5053725,4965303,4896434)\nid in (4584518,3249934,3218025,3891133,3399450,4172999,4485161,3101785,4587203,3070816,2870343,2870341,3563940,4550846,3424464,3249963,2870342)\n;\n\nselect * from activities where id = 26654935;\nSELECT * FROM opportunities WHERE id = 4803458;\n\nSELECT * FROM opportunities where team_id = 260 and user_id = 13841 AND stage_id = 15900;\nSELECT id, uuid, provider, type, lead_id, account_id, contact_id, opportunity_id, stage_id, status, recording_state, title, actual_start_time, actual_end_time\nFROM activities WHERE user_id = 13841 AND opportunity_id IN (4729783, 4731717, 4731726, 4732064, 4732849, 4803458, 4813213);\n\nSELECT DISTINCT\n o.id, o.stage_id, s.name, a.title,\n a.*\nFROM activities a\n# INNER JOIN tracks t ON a.id = t.activity_id\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams team ON u.team_id = team.id\nINNER JOIN groups g ON u.group_id = g.id\nINNER JOIN opportunities o ON a.opportunity_id = o.id\nINNER JOIN stages s ON o.stage_id = s.id\nWHERE\n a.crm_configuration_id = 356\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n# and a.user_id = 13841\n AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')\n AND team.uuid = uuid_to_bin('a607fba7-452e-4683-b2af-00d6cb52c93c')\n AND g.uuid = uuid_to_bin('b5d69e40-24a0-4c16-810b-5fa462299f94')\n\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND t.type IN ('audio', 'video')\n AND (\n (a.actual_start_time BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59')\n OR\n (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59'\n )\n )\n AND (\n a.is_private = 0\n OR (\n a.is_private = 1\n AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')\n )\n )\n AND (\n# s.id = 15900\n s.uuid = uuid_to_bin('04ca1c26-c666-4268-a129-419c0acffd73')\n OR s.uuid IS NULL -- Include records without opportunity stage\n )\n\nORDER BY a.actual_end_time DESC;\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lead Forensics%'; # 190, 162, 8474, willsc@leadforensics.com\nSELECT * FROM users WHERE team_id = 190;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 190\nand sa.provider = 'hubspot';\n\nselect * from role_user where user_id = 8474;\n\nselect * from crm_configurations where provider = 'bullhorn';\n\nSELECT * FROM opportunities WHERE uuid_to_bin('94578249-65ec-4205-90f2-7d1a7d5ab64a') = uuid;\nSELECT * FROM users WHERE uuid_to_bin('26dbadeb-926f-4150-b11b-771b9d4c2f9a') = uuid;\n\nSELECT * FROM opportunities WHERE id = 4732493;\nselect * from activities where opportunity_id = 4732493;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE id = 443; # 358, 14315, andrea.romano@correrenaturale.com\nSELECT * FROM opportunities WHERE team_id = 443;\n\nSELECT a.id, a.type, a.user_id, a.status, a.deleted_at, u.name, u.email, u.team_id as activity_team_id, u.status, u.deleted_at, t.name, t.status, s.team_id as stage_team_id\nFROM activities AS a\nJOIN stages AS s ON a.stage_id = s.id\nJOIN users AS u ON u.id = a.user_id\nJOIN teams AS t ON t.id = s.team_id\nWHERE u.team_id <> s.team_id and t.id > 135;\n\n\nSELECT\n crm_configuration_id,\n crm_provider_id,\n COUNT(*) as duplicate_count,\n GROUP_CONCAT(id) as stage_ids,\n GROUP_CONCAT(name) as stage_names\nFROM stages\nGROUP BY crm_configuration_id, crm_provider_id\nHAVING COUNT(*) > 1\nORDER BY duplicate_count DESC;\n\nselect * from stages where id IN (14898,14907);\n\nselect * from business_processes;\n\nSELECT *\nFROM crm_configurations\nWHERE team_id IN (\n SELECT team_id\n FROM crm_configurations\n GROUP BY team_id\n HAVING COUNT(*) > 1\n)\nORDER BY team_id;\n\nSELECT *\nFROM teams\nWHERE crm_id IN (\n SELECT crm_id\n FROM teams\n GROUP BY crm_id\n HAVING COUNT(*) > 1\n)\nORDER BY crm_id;\n\n# ***************************************************************************\nselect * from crm_configurations where provider = 'integration-app';\nSELECT * FROM teams WHERE id = 443; # Correre Naturale 358 14315 andrea.romano@correrenaturale.com\nselect * from activities where crm_configuration_id = 358 order by actual_end_time desc;\nselect id, uuid, actual_end_time, crm_provider_id, is_internal, playbook_category_id, type, user_id, lead_id, contact_id, account_id, opportunity_id, status, title from activities where crm_configuration_id = 358 order by actual_end_time desc;\nselect * from team_features where team_id = 358;\nselect * from activity_summary_logs;\n\nselect * from teams where id = 406;\n\n# ************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Sportfive%'; # 267, 202, 14637, srv.salesforce@sportfive.com\nselect * from activities where crm_configuration_id = 202 order by actual_end_time desc;\n\nSELECT * FROM users where id = 14637;\nSELECT * FROM teams where id = 267;\nSELECT * FROM groups where id = 1118;\n\nselect g.name, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\ninner join groups g on g.id = u.group_id\nwhere a.crm_configuration_id = 202\nand a.is_internal = 0\nand (a.scheduled_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type = 'conference'\nand a.status != 'completed'\nand a.external_id is not null\norder by a.scheduled_start_time desc;\n\nSELECT * FROM activities\nWHERE crm_configuration_id = 202\n AND status IN ('completed', 'failed')\n AND recording_state != 'stopped'\n AND type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n AND (is_private = 0 OR user_id = 14637)\n AND (\n (\n actual_start_time BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n ) OR (\n actual_start_time IS NULL\n AND type IN ('sms-outbound', 'sms-inbound')\n AND created_at BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n )\n )\n AND NOT EXISTS (\n SELECT 1\n FROM tracks\n WHERE\n tracks.activity_id = activities.id\n AND tracks.type IN ('audio', 'video')\n )\nORDER BY actual_end_time DESC;\n\nSELECT DISTINCT\n a.*\nFROM activities a\nINNER JOIN tracks t ON a.id = t.activity_id\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams team ON u.team_id = team.id\nWHERE\n a.crm_configuration_id = 202\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n# and a.user_id = 14637\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND t.type IN ('audio', 'video')\n AND (\n (a.actual_start_time BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59')\n OR\n (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n )\n )\n AND (\n a.is_private = 0\n OR (\n a.is_private = 1\n AND a.user_id = 14637\n )\n )\n\nORDER BY a.actual_end_time DESC\n;\n\nSELECT DISTINCT a.*\nFROM activities a\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams t ON u.team_id = t.id\n# INNER JOIN tracks tr ON a.id = tr.activity_id\n# INNER JOIN groups g ON u.group_id = g.id\nWHERE 1=1\n AND t.id = 267\n# AND t.uuid = uuid_to_bin('aed4927b-f1ea-499e-94c3-83762fd233e8')\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND tr.type NOT IN ('audio', 'video')\n AND (\n a.is_private = 0\n OR a.user_id = 14637\n )\n AND (\n (a.actual_start_time BETWEEN '2025-03-19 00:00:00' AND '2025-03-21 23:59:59')\n OR (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-19 00:00:00' AND '2025-03-21 23:59:59'\n )\n )\n# and NOT EXISTS (\n# SELECT 1\n# FROM tracks t\n# WHERE t.activity_id = a.id\n# AND t.type IN ('audio', 'video')\n# )\n\nORDER BY a.actual_end_time DESC;\n\nSELECT * FROM tracks WHERE activity_id = 26485995;\n\nselect a.is_private, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\nwhere a.crm_configuration_id = 202\n# and a.is_internal = 0\nand (a.actual_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type IN (\"softphone\",\"softphone-inbound\",\"conference\",\"sms-inbound\")\nand a.status IN ('completed', 'failed')\n# and a.external_id is not null\norder by a.actual_end_time desc;\n\nselect * from activities a where a.crm_configuration_id = 202\nand a.actual_start_time between '2025-03-20 00:00:00' and '2025-03-21 00:00:00'\n# AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n\nselect g.name, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\ninner join groups g on g.id = u.group_id\nwhere a.crm_configuration_id = 202\nand a.is_internal = 0\nand (a.scheduled_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type = 'conference'\nand a.status != 'completed'\nand a.external_id is not null\norder by a.scheduled_start_time desc;\n\nSELECT * FROM teams WHERE name LIKE '%Tourlane%';\nSELECT * FROM crm_fields WHERE crm_configuration_id = 209 and object_type = 'opportunity';\nSELECT * FROM crm_field_data WHERE crm_field_id = 98809;\n\nselect * from users where status = 1 AND timezone = 'MDT';\n\nselect * from opportunities where id = 3769814;\nselect * from deal_risks where opportunity_id = 3769814;\n\nselect cp.* from crm_profiles cp\njoin users u on cp.user_id = u.id\njoin crm_configurations crm on cp.crm_configuration_id = crm.id\nwhere crm.provider = 'hubspot' AND u.status = 1 AND log_notes != 'none';\n\nselect * from crm_fields where id = 154575;\n\nselect * from team_features where feature = 'SUPPORTS_SYNC_MISSING_CALL_DISPOSITIONS';\nSELECT * FROM teams WHERE id = 176; # crm 148\nselect * from activities where crm_configuration_id = 148 and provider = 'hubspot' order by id desc;\n\nselect * from activity_providers where provider = 'amazon-connect';\n\nselect * from crm_fields cf\njoin crm_configurations crm on crm.id = cf.crm_configuration_id\nwhere crm.provider = 'hubspot' and cf.object_type IN ('account', 'contact');\n\n# *********************************************************************************************\nSELECT * FROM users WHERE id IN (15415, 15418);\nSELECT * FROM groups WHERE id IN (1805,1806);\nSELECT * FROM playbooks WHERE id = 1860;\nSELECT * FROM playbook_categories WHERE id = 38634;\nSELECT * FROM crm_fields WHERE id = 189962;\n\nSELECT * FROM teams WHERE name = 'Pulsar Group'; # 472, 380, 15138 raza.gilani@vuelio.com\n\nSELECT * FROM crm_profiles WHERE user_id = 15415;\nSELECT * FROM social_accounts WHERE sociable_id = 15415 and provider = 'salesforce';\n\nselect * from sidekick_settings where team_id = 472;\n\nSELECT * FROM activities WHERE uuid_to_bin('452c58c7-b87c-4fdd-953e-d7af185e9588') = uuid; # 28617536, user: 15418\nSELECT * FROM activities WHERE uuid_to_bin('399114ee-d3a8-458c-bff5-5f654658db0a') = uuid; # 28344407, user: 15415\nSELECT * FROM activities WHERE uuid_to_bin('f0aa567f-0ab1-4bbb-96aa-37dcf184676b') = uuid; # 28580288, user: 15415\nSELECT * FROM activities WHERE uuid_to_bin('50c086b1-2770-4bca-b5ae-6bac22ec426b') = uuid; # 28566069, user: 15415\n\n# *********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%TeamTailor%'; # 109, 218, 13969, salesforce-integrations@teamtailor.com\nselect * from crm_configurations where id = 218;\nSELECT * FROM activities WHERE uuid_to_bin('e39b5857-7fdb-4f5a-951a-8d3ca69bb1b0') = uuid; # 28338765\nSELECT * FROM users WHERE id IN (13232, 13230);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\n\n0057R00000EPL5HQAX Inez Ekblad\n\n1091cb81-5ea1-4951-a0ed-f00b568f0140 Triman Kaur\n\nSELECT * FROM crm_profiles WHERE user_id IN (13232, 13230);\n\n############################################################################################\nSELECT * FROM activities WHERE uuid_to_bin('675eeaeb-5681-42db-90bc-54c07a604408') = uuid; # 28655939 00UVg00000FLvnSMAT\nSELECT * FROM crm_field_data WHERE activity_id = 28655939;\nSELECT * FROM crm_fields WHERE id IN (94491,94493,94498);\nSELECT * FROM users WHERE id = 13658;\nSELECT * FROM teams WHERE id = 109;\nSELECT * FROM crm_configurations WHERE id = 218;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Strengthscope%'; # 481, 390, 15420, katy.holden@strengthscope.comk\nSELECT * FROM stages WHERE crm_configuration_id = 390;\nselect * from business_processes where team_id = 481 and crm_configuration_id = 390;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 481\nand sa.provider = 'salesforce';\n\n\nSELECT * FROM users WHERE id = 15780; # team 462\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 462\nand sa.provider = 'hubspot';\n\n\nselect * from teams where id = 495;\nSELECT * FROM users WHERE id = 15794;\nselect * from social_accounts where sociable_id = 15794;\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Flight%'; # 427, 333, 13752\nSELECT * FROM accounts WHERE team_id = 427 and crm_provider_id = '668731000183444517';\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Group GTI%'; # 495, 407, 15794\nSELECT * FROM activities WHERE crm_configuration_id = 407\nand status = 'completed' and type = 'conference'\norder by id desc;\n\nselect ru.*, pr.*, p.* from users u join role_user ru on ru.user_id = u.id\njoin permission_role pr on pr.role_id = ru.role_id\n join permissions p on p.id = pr.permission_id\nwhere team_id = 495 and p.name IN ('dial');\n\nselect * from permission_role;\n\nselect * from activities where crm_configuration_id = 407 and status = 'completed' order by id desc;\nSELECT * FROM activities WHERE id = 29512773;\nSELECT * FROM activities WHERE id IN (29042721,28991325,29002874);\n\nSELECT al.* from activity_summary_logs al join activities a on a.id = al.activity_id\nwhere a.crm_configuration_id = 407\n# and a.id IN (29042721,28991325,29002874);\n\nSELECT * FROM users WHERE id = 15794;\nSELECT * FROM users WHERE team_id = 495;\nSELECT * FROM social_accounts WHERE sociable_id = 15794;\nSELECT * FROM opportunities WHERE team_id = 495 and name like '%OC:%';\nSELECT * FROM contacts WHERE team_id = 495;\nSELECT * FROM leads WHERE team_id = 495;\nSELECT * FROM accounts WHERE team_id = 495;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 407;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 407;\nSELECT * FROM crm_configurations WHERE id = 407;\nSELECT * FROM opportunities WHERE team_id = 495 and close_date BETWEEN '2025-06-01' AND '2025-07-01'\nand user_id IS NOT NULL and is_closed = 1 and is_won = 1;\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Hamilton Court FX LLP%'; # 249, 187, 10103\nSELECT * FROM activities WHERE uuid_to_bin('4659c2bb-9a49-484e-9327-a3d66f1e028c') = uuid; # 28951064\nSELECT * FROM crm_fields WHERE crm_configuration_id = 187 and object_type IN ('tasks', 'event');\n\n# *********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Checkstep%'; # 325, 256, 11753\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 325\nand sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('7be372e2-1916-4d79-a2f3-ca3db1346db3') = uuid; # 28611085\nSELECT * FROM activities WHERE uuid_to_bin('980f0336-840b-4185-a5a9-30cf8b0749a8') = uuid; # 28719733\nSELECT * FROM activity_summary_logs where activity_id = 28719733;\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 356, 9444\nSELECT * FROM activity_summary_logs where sent_at BETWEEN '2025-06-09 11:38:00' AND '2025-06-09 11:40:00';\nSELECT * FROM leads WHERE crm_configuration_id = 356 and crm_provider_id = '230045001502770504'; # 823630\nselect * from activities where crm_configuration_id = 356 and lead_id = 841732;\n\nSELECT * from activity_summary_logs al join activities a on a.id = al.activity_id\nwhere a.crm_configuration_id = 356;\n\nselect * from activities where crm_configuration_id = 356\nand actual_end_time between '2025-06-09 11:00:00' and '2025-06-09 12:00:00'\norder by id desc;\n\nselect * from accounts where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\nselect * from leads where crm_configuration_id = 356 and crm_provider_id = '230045001514275654' order by id desc;\nselect * from contacts where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\nselect * from opportunities where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\n\nselect * from team_features where team_id = 260;\nselect * from features where id IN (1,2,4,6,18,19,20,9,10,3,23,24,25,26,27);\n\nSELECT * FROM activities WHERE uuid_to_bin('7be372e2-1916-4d79-a2f3-ca3db1346db3') = uuid;\n\nselect * from crm_fields;\nselect * from crm_layout_entities;\n\nSELECT * FROM teams WHERE name LIKE '%Optable%';\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Teamtailor%'; # 109, 218, 13969\nSELECT * FROM crm_configurations WHERE id = 218;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('675eeaeb-5681-42db-90bc-54c07a604408') = uuid; # 28655939\nSELECT * FROM crm_field_data WHERE activity_id = 28655939;\nSELECT * FROM crm_fields WHERE id in (94491,94493,94498);\n\nselect * from teams where crm_id IS NULL;\n\nSELECT * FROM activities WHERE uuid_to_bin('71aa8a0c-9652-4ff6-bee7-d98ae60abef6') = uuid;\n\n# *************************************************************************************************\nselect * from team_domains where team_id = 399;\nSELECT * FROM teams WHERE name LIKE '%Rydoo%'; # 399, 318, 13207\n\nselect * from calendar_events where id = 5163781;\nSELECT * FROM activities WHERE uuid_to_bin('be2cbc52-7fda-46a0-9ae0-25d9553eafc0') = uuid; # 29443896\nSELECT * FROM participants WHERE activity_id = 29443896;\nselect * from contacts where crm_configuration_id = 318 and email = 'marianne.westeng@strawberry.no';\nselect * from leads where crm_configuration_id = 318 and email = 'marianne.westeng@strawberry.no';\n\nselect * from activities where user_id = 14937 order by created_at ;\n\nselect * from users where id = 14937;\n\nselect * from contacts where crm_configuration_id = 318 and email LIKE '%@strawberry.se';\nselect * from opportunities where crm_configuration_id = 318 and crm_provider_id = '006Sf00000D1WOAIA3';\n\nselect * from activities a join participants p on a.id = p.activity_id\nwhere crm_configuration_id = 318 and a.updated_at > '2025-06-23T08:18:43Z';\n\n# *************************************************************************************************\nSELECT * FROM opportunities WHERE team_id = 379 and crm_provider_id = '39334518886';\nSELECT * FROM opportunities WHERE team_id = 379 order by id desc;\nSELECT * FROM teams WHERE id = 379;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 379 and sociable_id = 13852\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations WHERE id = 307;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 307;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1027;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 307\n and id IN (144750,144855,145158,155227);\n\nSELECT * FROM activities;\n\n\nselect * from activities\nwhere created_at > '2025-07-01 00:00:00'\n# and created_at < '2025-08-01 00:00:00'\nand type not in ('email-outbound', 'email-inbound')\nand account_id is null\nand contact_id is null\nand lead_id is null\nand opportunity_id is not null\n;\nSELECT * FROM activities WHERE id IN (25344155, 25344296, 25501909, 28692187);\nSELECT * FROM crm_configurations WHERE id in (335,301,200);\n\nselect * from crm_fields where crm_configuration_id = 230 and crm_provider_id = 'Age2__c';\n\nSELECT * FROM teams WHERE name LIKE '%Resights%';\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\n\nselect * from crm_configurations where provider = 'bullhorn'; # 344\nselect * from teams where id IN (442);\n\nselect * from activities\nwhere crm_configuration_id = 177\nand provider = 'amazon-connect'\n order by id desc;\n# and source <> 'gong';\n\nselect * from activity_providers where provider = 'amazon-connect';\n\nSELECT * FROM activities WHERE uuid_to_bin('cec1993b-a7e5-4164-b74d-d680ea51d2f2') = uuid;\n\n\nselect * from crm_configurations where store_transcript = 1;\nSELECT * FROM teams WHERE id IN (80);\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Sedna%'; # 277, 213, 12594\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 277\nand sa.provider = 'salesforce';\n\nselect * from activities where crm_configuration_id = 213 and account_id = 2511502;\n\nselect * from crm_configurations where id = 213;\n\nSELECT * FROM activities WHERE uuid_to_bin('35aa790a-8569-4544-8268-66f9a4a26804') = uuid; # 33981604\nSELECT * FROM participants WHERE activity_id = 33981604;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 337 and object_type = 'task';\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 431\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('b5476c7d-19a8-491b-869d-676ea1e857b6') = uuid; # 33997223\nselect * from activity_summary_logs where activity_id = 33997223;\nselect * from activity_notes where activity_id = 33997223;\n\n# ***********************************\nSELECT * FROM teams WHERE name LIKE '%Abode%';\n\n\nselect * from features;\nselect * from teams t\nwhere t.status = 'active'\nand id NOT IN (select team_id from team_features where feature_id = 9)\n;\n\n\nselect * from playbook_layouts where playbook_id = 1725;\nSELECT * FROM activities WHERE uuid_to_bin('65cc283c-4849-49e6-927f-4c281c8fea19') = uuid; # 34297473\nselect * from teams where id = 318;\nselect * from crm_configurations where team_id = 318;\nselect * from playbooks where team_id = 318;\nSELECT * FROM crm_layouts where crm_configuration_id = 381;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1259;\nSELECT * FROM crm_fields WHERE id IN (192938,192936,192939);\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1266;\nSELECT * FROM crm_fields WHERE id IN (192980,192991,192997,192998,193064,193067);\n\nSELECT * FROM activities WHERE uuid_to_bin('a902289b-285c-48eb-9cc2-6ad6c5d938f5') = uuid; # 34297533\n\n\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 927;\nSELECT * FROM crm_fields WHERE id IN (131668,131669,131670,131671,131676,131797);\n\nSELECT * FROM teams WHERE name LIKE '%Peripass%'; # 351, 281, 12124\nselect * from crm_layouts where crm_configuration_id = 281;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 927;\nselect * from crm_fields where crm_configuration_id = 281 and id in (131668,131669,131670,131671,131676,131797);\nselect * from opportunities where crm_configuration_id = 281;\n\nSELECT * FROM activities WHERE id IN (34211315, 34130075);\nSELECT * FROM crm_field_data WHERE object_id IN (34211315, 34130075);\n\nselect cf.crm_configuration_id, cle.crm_layout_id, cle.id, cf.id from crm_field_data cfd\njoin crm_layout_entities cle on cle.id = cfd.crm_layout_entity_id\njoin crm_fields cf on cle.crm_field_id = cf.id\nwhere cf.deleted_at IS NOT NULL\nGROUP BY cle.id, cf.id;\n\nselect * from crm_layouts where id IN (355);\nselect u.email, t.crm_id, t.* from teams t\njoin users u on u.id = t.owner_id\nwhere crm_id IN (97);\n\nSELECT * FROM crm_fields WHERE id = 96492;\n\nselect * from permissions;\nselect * from permission_role where permission_id = 247;\nselect * from roles;\n\nselect * from migrations;\n# *****************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('291e3c21-11cc-4728-aee7-6e4bedf86d72') = uuid; # 34262174\nSELECT * FROM crm_configurations WHERE id = 301;\nSELECT * FROM teams WHERE id = 343;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nselect * from participants where activity_id = 34262174;\n\nselect * from contacts where crm_configuration_id = 301 and id = 6976326;\nselect * from accounts where crm_configuration_id = 301 and id IN (4647626, 4815829); # 30761335403\n\nselect * from activity_summary_logs where activity_id = 34262174;\n\nselect * from users where status = 1 AND timezone = 'EST';\n\n# ****************************************************************************\nSELECT * FROM users WHERE id = 13869;\nSELECT * FROM crm_configurations WHERE id = 320;\nSELECT * FROM teams WHERE id = 401;\n\nSELECT * FROM activities WHERE uuid_to_bin('2228c16f-10be-48d5-90d4-67385219dc01') = uuid; # 29670601\n\nSELECT * FROM accounts WHERE id = 7761483;\nSELECT * FROM opportunities WHERE id = 6051814;\n\nSELECT * FROM teams WHERE name LIKE '%Seedlegals%';\n\n;select * from opportunities where updated_at > '2025-10-11' AND crm_provider_id = '34713761166';\n\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 177;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 577;\nSELECT * FROM crm_fields WHERE id IN (68458,68459,68480,68497,68524,68530,68554,68618,68662,68781,68810,68898,68981,69049,97467);\n\nSELECT t.id, crm.id, t.name, crm.sync_objects, crm.provider, crm.last_synced_at FROM crm_configurations crm join teams t on t.crm_id = crm.id\nwhere t.status = 'active' AND crm.provider = 'hubspot' AND crm.last_synced_at < '2025-10-22 00:00:00';\n\nSELECT * FROM activities WHERE uuid_to_bin('fa09449f-cba9-496a-b8f3-865cd3c72351') = uuid;\nSELECT * FROM crm_configurations where id = 184;\nSELECT * FROM teams WHERE id = 246;\nSELECT * FROM social_accounts WHERE sociable_id = 9259 and provider = 'hubspot';\n\nSELECT * FROM users WHERE email LIKE '%rhian.old@bud.co.uk%'; # 17700\nSELECT * FROM teams WHERE id = 551;\n\nSELECT * FROM crm_configurations WHERE id = 471;\nSELECT * FROM activities WHERE crm_configuration_id = 471 and crm_provider_id IS NOT NULL;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 471;\nSELECT * FROM crm_fields WHERE id = 307260;\nSELECT * FROM crm_field_values WHERE crm_field_id = 307260;\n\nselect * from crm_layouts where crm_configuration_id = 471;\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1547;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1548;\n\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 = 551 and sa.provider = 'hubspot';\n\nSELECT * FROM teams WHERE name LIKE '%$PCS%';\n\n# ********************************************************************************************************\nselect * from crm_configurations crm\njoin teams t on t.crm_id = crm.id\nwhere t.status = 'active'\nand crm.provider = 'hubspot';\n\n# $slug = 'HUBSPOT_WEBHOOK_SYNC';\n# $team = Jiminny\\Models\\Team::find(2);\n# $feature = Feature::query()->where('slug', $slug)->first();\n# TeamFeature::query()->create(['feature_id' => $feature->getId(),'team_id' => $team->getId()]);\n\n# hubspot_webhook_metrics\n\nselect * from crm_configurations where id = 331; # 416\nSELECT * FROM teams WHERE id = 416;\nSELECT * FROM opportunities WHERE team_id = 190;\n\nSELECT * FROM teams WHERE name LIKE '%Lead Forensics%';\nSELECT sa.id,\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 = 190 and sa.provider = 'hubspot';\n\n\n\nSELECT * FROM teams WHERE name LIKE '%Rapaport%'; # 431, 337\nSELECT * FROM teams where id = 431;\nSELECT * FROM crm_configurations where team_id = 431;\nSELECT * FROM activity_providers where team_id = 431;\nSELECT * FROM activities where crm_configuration_id = 337 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\nSELECT sa.id,\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 = 431 and sa.provider = 'salesforce';\n\nSELECT * FROM teams WHERE name LIKE '%BiP%'; # 401, 320\nSELECT * FROM teams where id = 401;\nSELECT * FROM crm_configurations where team_id = 401;\nSELECT * FROM activity_providers where team_id = 401;\nSELECT * FROM activities where crm_configuration_id = 320 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\nSELECT sa.id,\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 = 401 and sa.provider = 'salesforce';\n\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 307; # 379 - Story Terrace Inc , portalId: 3921157\nSELECT * FROM contacts WHERE team_id = 379 and updated_at > '2026-01-31 11:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 379 and updated_at > '2026-02-01 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 379 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\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 = 379 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 485; # 563 - LATUS Group (ad94d501-5d09-44fd-878f-ca3a9f8865c3) , portalId: 3904501\nSELECT * FROM opportunities WHERE team_id = 563 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 563 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 338; # 432 - Formalize , portalId: 9214205\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 = 432 and sa.provider = 'hubspot';\nSELECT * FROM opportunities WHERE team_id = 432 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 432 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 436; # 519 - Moxso , portalId: 25531989\nSELECT * FROM opportunities WHERE team_id = 519 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 519 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 96; # 119 - Nourish Care , portalId: 26617984\nSELECT * FROM opportunities WHERE team_id = 119 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 119 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 331; # 416 - The National College , portalId: 7213852\nSELECT * FROM opportunities WHERE team_id = 416 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 416 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 308; # 380 - Foodles , portalId: 7723616\nSELECT * FROM opportunities WHERE team_id = 380 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 380 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 379; # 471 - imat-uve , portalId: 9177354\nSELECT * FROM opportunities WHERE team_id = 471 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 471 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 465; # 545 - Spotler , portalId: 144759271\nSELECT * FROM opportunities WHERE team_id = 545 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 545 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 455; # 537 - indevis , portalId: 25666868\nSELECT * FROM opportunities WHERE team_id = 537 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 537 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 200; # 265 - Jobadder , portalId: 6426676\nSELECT * FROM opportunities WHERE team_id = 265 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 265 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 335; # 429 - Eletive , portalId: 6110563\nSELECT * FROM opportunities WHERE team_id = 429 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 429 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 363; # 456 - Global Group , portalId: 8901981\nSELECT * FROM opportunities WHERE team_id = 456 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 456 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 297; # 369 - Unbiased , portalId: 9229005\nSELECT * FROM opportunities WHERE team_id = 369 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 369 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 353; # 449 - Fuuse , portalId: 25781745\nSELECT * FROM opportunities WHERE team_id = 449 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 449 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 487; # 566 - Nimbus , portalId: 39982590\nSELECT * FROM opportunities WHERE team_id = 566 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 566 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 487;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1630;\nselect * from crm_fields where crm_configuration_id = 487 and\n(uuid_to_bin('4c6b2971-64d4-45b8-b377-427be758b5a5') = uuid or uuid_to_bin('59e368d8-65a0-4b77-b611-db37c99fbe68') = uuid);\nSELECT * FROM crm_field_values WHERE crm_field_id = 375177;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 420; # 506 - voiio , portalId: 145629154\nSELECT * FROM opportunities WHERE team_id = 506 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 506 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 479; # 558 - Momice , portalId: 535962\nSELECT * FROM opportunities WHERE team_id = 558 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 558 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 59; # 80 - Storyclash GmbH , portalId: 4268479\nSELECT * FROM opportunities WHERE team_id = 80 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 80 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 175; # 203 - Team iAM , portalId: 5534732\nSELECT * FROM opportunities WHERE team_id = 203 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 203 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 368; # 460 - OneTouch Health , portalId: 5534732183355\nSELECT * FROM opportunities WHERE team_id = 460 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 460 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\n\n\nselect * from users where id = 29643;\nSELECT * FROM crm_field_values WHERE crm_field_id = 375177;\n# ********************************************************************\nSELECT * FROM teams WHERE name LIKE '%Buynomics%'; # 462, 482, 14910\nSELECT * FROM activities WHERE crm_configuration_id = 482\nand type NOT IN ('email-inbound', 'email-outbound')\n# and description like '%The call focused on understanding Welch%'\norder by id desc;\n\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 = 462 and sa.provider = 'salesforce';\n\nselect * from contacts where crm_configuration_id = 482 and name = 'Cyndall Hill'; # 15504749\nselect * from contacts where id = 10891096; # 482\nSELECT * FROM activities WHERE crm_configuration_id = 482\nand type NOT IN ('email-inbound', 'email-outbound')\nand contact_id = 15504749\norder by id desc;\n\nselect * from activities where id = 36793003; # 96cc7bc1-8622-4d27-92f4-baf664fc1a56, 00UOf00000PDdOXMA1\nselect * from transcription where id = 7646782;\nselect * from ai_prompts where transcription_id = 7646782;\n\n# ********************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('7a8471a3-847e-4822-802b-ddf426bbc252') = uuid; # 37370018\nSELECT * FROM activity_summary_logs WHERE activity_id = 37370018;\nSELECT * FROM teams WHERE id = 555;\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 = 555 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('7c17b8aa-09df-4f85-a0f7-51f47afd712d') = uuid; # 37395250\nSELECT * FROM activities WHERE uuid_to_bin('14d60388-260d-494b-aa0d-63fdb1c78026') = uuid; # 37395250\n\nSELECT a.* FROM activities a JOIN crm_configurations c on c.id = a.crm_configuration_id\nwhere a.type IN ('softphone', 'softphone-outbound') and c.provider = 'hubspot'\nand a.provider NOT IN ('hubspot')\n# and a.provider IN ('salesloft')\n# and c.id NOT IN (70)\n# and a.duration > 30\n# and actual_start_time > '2026-02-05 00:00:00'\norder by a.id desc;\n\nSELECT * FROM activities WHERE id = 37549787;\nSELECT * FROM crm_profiles WHERE user_id = 17613;\n\nSELECT * FROM crm_configurations WHERE id = 70;\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 = 93 and sa.provider = 'hubspot';\n\nSELECT asf.activity_search_id, asf.id, asf.value\nFROM activity_search_filters asf\nWHERE asf.filter = 'group_id'\nAND asf.value IN (\n SELECT CONCAT(\n HEX(SUBSTR(uuid, 5, 4)), '-',\n HEX(SUBSTR(uuid, 3, 2)), '-',\n HEX(SUBSTR(uuid, 1, 2)), '-',\n HEX(SUBSTR(uuid, 9, 2)), '-',\n HEX(SUBSTR(uuid, 11))\n )\n FROM groups\n WHERE deleted_at IS NOT NULL\n);\n\nSELECT * FROM crm_configurations WHERE id = 373; # KPSBremen.de 465 # - no social account\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 = 465 and sa.provider = 'hubspot';\n\nselect * from crm_configurations where id = 494;\n\nSELECT * FROM teams WHERE name LIKE '%splose%'; # 572, 495, 18708\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 = 572 and sa.provider = 'pipedrive';\n\nselect * from opportunities where team_id = 572\n# and name like '%Onebright%'\n# and is_closed = 1 and is_won = 0\n order by id desc;\n\n\nselect * from users where deleted_at is null and status = 2;\n\nselect * from contacts where id = 17900517;\nselect * from accounts where id = 10109838;\nselect * from opportunities where id = 6955880;\n\nselect * from opportunity_contacts where opportunity_id = 6955880;\nselect * from opportunity_contacts where contact_id = 17900517;\n\nselect * from contact_roles cr join crm_configurations crm on cr.crm_configuration_id = crm.id\nwhere crm.provider != 'salesforce';\n\nSELECT * FROM activities WHERE uuid_to_bin('adcb8331-5988-4353-834e-383a355abba2') = uuid; # 38056424, crm 104659682404\nselect * from teams where id = 456;\nSELECT * FROM crm_configurations WHERE id = 363;\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 = 456 and sa.provider = 'hubspot';\n\nselect * from crm_layouts where crm_configuration_id = 363;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id IN (1203, 1204, 1635);\nSELECT * FROM crm_fields WHERE id IN (181536, 181538, 213455);\n\nSELECT * FROM teams WHERE name LIKE '%Electric%'; # 342, 272, 12767\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 = 342 and sa.provider = 'pipedrive';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 and name like 'NORTHUMBRIA POL%'; # and updated_at > '2025-07-01 00:00:00';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 order by remotely_created_at asc; # and updated_at > '2025-07-01 00:00:00';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 and updated_at > '2026-01-01 00:00:00';\nSELECT * FROM crm_fields WHERE crm_configuration_id = 272 and object_type = 'opportunity';\nSELECT * FROM crm_field_values WHERE crm_field_id = 127164;\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 = 342 and sa.provider = 'pipedrive';\n\nSELECT * FROM teams WHERE id = 472;\nSELECT * FROM crm_configurations WHERE id = 380;\nselect * from activities where id = 38285673; # 38285673\nSELECT * FROM users WHERE id = 16942;\nSELECT * FROM groups WHERE id = 1964;\nSELECT * FROM playbooks WHERE id = 2033;\n\nselect * from teams where created_at > '2026-03-09';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 499; # 1065\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1678;\n\nSELECT * FROM teams WHERE id = 575;\nselect * from opportunities where team_id = 575;\n\nSELECT * FROM activities WHERE uuid_to_bin('96b1261f-2357-49f9-ab38-23ce12008ea0') = uuid;\n\nselect * from contacts c\nwhere c.crm_configuration_id = 370 order by c.updated_at desc;\n\nSELECT * FROM participants where activity_id = 38833541;\nSELECT * FROM participants where activity_id = 39216301;\nSELECT * FROM activity_summary_logs where activity_id = 39216301;\nSELECT * FROM activities WHERE uuid_to_bin('c7d99fbe-1fb1-41f2-8f4d-52e2bf70e1e9') = uuid; # 38833541, crm 478116564181\nSELECT * FROM activities WHERE uuid_to_bin('2e6ff4d3-9faa-447a-a8c1-9acde4d885ae') = uuid; # 39216301, crm 480171536586\nselect * from crm_profiles where crm_configuration_id = 319 and crm_provider_id = 525785080;\nselect * from opportunities where crm_configuration_id = 319 and crm_provider_id = 410150124747;\nselect * from accounts where crm_configuration_id = 319 and crm_provider_id = 47150650569;\nselect * from contacts where crm_configuration_id = 319 and crm_provider_id IN ('665587441856', '742723347700');\n# owner 13236 525785080\n# contact 1 16779180 665587441856 - activity - Alex Howes alex@supportroom.com created 2026-01-26\n# contact 2 19247563 742723347700 - ash@supportroom.com 2026-03-24\n# company 4176133 47150650569\n# deal 7100953 410150124747\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 = 400 and sa.provider = 'hubspot';\n\nselect * from features;\nselect * from team_features where feature_id = 40;\n\nselect * from teams where id = 556; # owner: 18101, crm: 477\nselect * from crm_configurations where id = 477;\nSELECT * FROM users WHERE id = 18101;\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 = 556 and sa.provider = 'integration-app';\n\nselect * from opportunities where id = 7594349;\nselect * from opportunity_stages where opportunity_id = 7594349 order by created_at desc;\nselect * from business_processes where id = 6024;\nselect * from business_process_stages where stage_id = 16352;\nselect * from business_process_stages where business_process_id = 6024;\nselect * from stages where team_id = 459;\nselect * from teams where id = 459;\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 = 459 and sa.provider = 'hubspot';\n\nSELECT os.stage_id, s.crm_provider_id, s.name, COUNT(*) as cnt\nFROM opportunity_stages os\nJOIN stages s ON s.id = os.stage_id\nWHERE os.opportunity_id = 7594349\nGROUP BY os.stage_id, s.crm_provider_id, s.name\nORDER BY cnt DESC;\n\nSELECT s.id, s.crm_provider_id, s.name, s.team_id, s.crm_configuration_id\nFROM stages s\nJOIN business_process_stages bps ON bps.stage_id = s.id\nWHERE bps.business_process_id = 6024\nAND s.crm_provider_id = 'contractsent';\n\nselect * from stages where id IN (16352,20612,18281,7344,16378,16309,5036,15223,14535,6293,12098,11607)\n\nSELECT * FROM teams WHERE name LIKE '%Pulsar Group%'; # 472, 380, 15138, raza.gilani@vuelio.com\nselect * from playbooks where team_id = 472; # event 226147\nSELECT * FROM playbook_categories WHERE playbook_id = 2288;\nSELECT * FROM crm_fields WHERE id = 226147;\nSELECT * FROM crm_field_values WHERE crm_field_id = 226147;\n\nSELECT * FROM crm_configurations WHERE id = 380;\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 = 472 and sa.provider = 'salesforce';\n\nselect * from activities where id = 58081273;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2;\n\nSELECT * FROM users WHERE name LIKE '%Neil Hoyle%'; # 17651\nSELECT * FROM social_accounts WHERE sociable_id = 17651;\n\nSELECT * FROM activities WHERE uuid_to_bin('975c6830-7d49-4c1e-b2e9-ac80c10a738a') = uuid;\nSELECT * FROM opportunities WHERE id IN (7842553, 6211727);\nSELECT * FROM contacts WHERE id IN (10202724, 6211727);\nSELECT * FROM opportunity_stages WHERE opportunity_id = 7842553;\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 = 519 and sa.provider = 'hubspot';\n\nselect * from crm_configurations where id = 436;\nselect * from crm_profiles where crm_configuration_id = 436; # 76091797 -> 16612\n\nselect * from contact_roles where contact_id = 10202724;\n\nselect * from stages where team_id = 519; # 18778\n18775\n\nSELECT\n id,\n crm_provider_id,\n stage_id,\n is_closed,\n is_won,\n stage_updated_at,\n updated_at\nFROM opportunities\nWHERE id IN (6211727, 7842553);\n\nSELECT * FROM opportunity_contacts\nWHERE opportunity_id = 6211727 AND contact_id = 10202724;\n\nSELECT id, name, stage_id, is_closed, is_won, updated_at, remotely_created_at\nFROM opportunities\nWHERE account_id = 8179134\nORDER BY updated_at DESC;\n\n\nselect * from text_relays where created_at > '2026-01-01';\nAND id IN (691, 692);\n\nselect * from teams;\n\n# ***************\nSELECT DISTINCT u.id, u.email, u.name, u.softphone_number, COUNT(a.id) as sms_count\nFROM users u\nINNER JOIN activities a ON u.id = a.user_id\nWHERE a.type LIKE 'sms%'\nAND a.created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)\nGROUP BY u.id, u.email, u.name, u.softphone_number\nORDER BY sms_count DESC;\n\nSELECT DISTINCT u.id, u.email, u.name, u.team_id, t.name as team_name,\n t.twilio_sms_sid, t.twilio_messaging_sid\nFROM users u\nINNER JOIN teams t ON u.team_id = t.id\nWHERE (t.twilio_sms_sid IS NOT NULL OR t.twilio_messaging_sid IS NOT NULL)\nAND u.status = 1\nORDER BY t.name, u.email;\n\nSELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, salesforce-admin@tourlane.com\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 = 187 and sa.provider = 'salesforce';\n\nselect * from activities where id = 31264367;\nselect * from contacts where id = 6331639;\nselect * from accounts where id = 4156632;\nselect * from opportunities where id = 4843610;\n# update `activities` set `account_id` = 4156632, `contact_id` = 6331639, `opportunity_id` = 4843610,\n# `stage_id` = 13273, `activities`.`updated_at` = 2026-05-22 07:16:17 where `id` = 31264367)\"\n\nselect * from text_relays where created_at > '2026-05-01';\n\nselect * from activities order by id desc;\n\nselect * from users where name like '%Subra%';\n\nSELECT * FROM opportunities WHERE uuid_to_bin('04a9cfad-2c87-4453-9e72-20aeb78ccf8d') = uuid;\nselect * from teams where id = 555;\nselect * from stages where team_id = 555;\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 = 100 and sa.provider = 'hubspot';","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.011968086,"top":0.047885075,"width":0.024268618,"height":0.024740623},"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}]...
|
6342989898062187878
|
2074961217668396653
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Code changed:
Hide
Sync Changes
Hide This Notification
31
9
29
3
109
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM team_features where team_id = 1;
SELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922
SELECT * FROM users WHERE team_id = 340; # 12015
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 340
and sa.provider = 'salesforce';
# and sa.provider = 'salesloft';
select * from crm_fields where crm_configuration_id = 270 and object_type = 'event';
# 125558 - Event Type - Event_Type__c
# 125552 - Event Status - Event_Status__c
SELECT * FROM sidekick_settings WHERE team_id = 340;
SELECT * FROM crm_field_values WHERE crm_field_id in (125552);
select * from activities where crm_configuration_id = 270
and type = 'conference' and crm_provider_id IS NOT NULL
and actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;
SELECT * FROM activities WHERE id = 20871677;
SELECT * FROM crm_field_data WHERE activity_id = 20871677;
select * from crm_layouts where crm_configuration_id = 270;
select * from crm_layout_entities where crm_layout_id in (886,887);
SELECT * FROM crm_configurations WHERE id = 270;
select * from playbooks where team_id = 340; # 1514
select * from groups where team_id = 340;
SELECT * FROM crm_fields WHERE id IN (125393, 125401);
select g.name as 'team name', p.name as 'playbook name', f.label as 'activity type field' from groups g
join playbooks p on g.playbook_id = p.id
join crm_fields f on p.activity_field_id = f.id
where g.team_id = 340;
SELECT * FROM activities WHERE uuid_to_bin('0c180357-67d2-419e-a8c3-b832a3490770') = uuid; # 20448716
select * from crm_field_data where object_id = 20448716;
select * from activities where crm_configuration_id = 270 and provider = 'salesloft' order by id desc;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%CybSafe%'; # 343,273,12008
select * from opportunities where team_id = 343;
select * from opportunities where team_id = 343 and crm_provider_id = '18099102526';
select * from opportunities where team_id = 343 and account_id = 945217482;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
select * from accounts where team_id = 343 order by name asc;
select * from stages where crm_configuration_id = 273 and type = 'opportunity';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Voyado%'; # 353,283,12143
SELECT * FROM activities WHERE crm_configuration_id = 283 and account_id = 3777844 order by id desc;
SELECT * FROM accounts WHERE team_id = 353 AND name LIKE '%Salesloft%';
SELECT * FROM activities WHERE id = 20717903;
select * from participants where activity_id IN (20929172,20928605,20928468,20926272,20926271,20926270,20926269,20916499,20916454,20916436,20916435,20900015,20900014,20900013,20897312,20897243,20897241,20897237,20897232,20897229,20893648,20893231,20893230,20893229,20893228,20889784,20885039,20885038,20885037,20885036,20885035,20882728,20882708,20882703,20882702,20869828,20869811,20869806,20869801,20869799,20869798,20869796,20869795,20869794,20869761,20869760,20869759,20868688,20868687,20850340,20847195,20841710,20833967,20827021,20825307,20825305,20825297,20824615,20824400,20823927,20821760,20795588,20794233,20794057,20793710,20785811,20781789,20781394,20781307,20762651,20758453,20758282,20757323,20756643,20756636,20756629,20756627,20756606,20756605,20756604,20756603,20756602,20756600,20756599,20756598,20756595,20756594,20756589,20756587,20756577,20756573,20748918,20748386,20748385,20748384,20748383,20748382,20748381,20748380,20748379,20748377,20748375,20748373,20743301,20717905,20717904,20717903,20717901,20717899);
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 353
and sa.provider = 'salesforce';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%modern world business solutions%'; # 345,275,12016, [EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('3921d399-3fef-4609-a291-b0097a166d43') = uuid;
# id: 20940638, user: 12022, contact: 5305871
SELECT * FROM activity_summary_logs WHERE activity_id = 20940638;
select * from contacts where team_id = 345 and crm_provider_id = '30891432415' order by name asc; # 5305871
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 345
and sa.provider = 'hubspot';
select * from users where team_id = 345 and id = 12022;
SELECT * FROM crm_profiles WHERE user_id = 12022;
SELECT * FROM participants WHERE activity_id = 20940638;
SELECT * FROM users u
JOIN crm_profiles cp ON u.id = cp.user_id
WHERE u.team_id = 345;
select * from contacts where team_id = 345 and crm_provider_id = '30880813535' order by name desc; # 5305871
select * from team_features where team_id = 345;
SELECT * FROM activities WHERE uuid_to_bin('11701e2d-2f82-4dab-a616-1db4fad238df') = uuid; # 21115197
SELECT * FROM participants WHERE activity_id = 20897406;
SELECT * FROM activities WHERE uuid_to_bin('63ba55cd-1abc-447d-83da-0137000005b7') = uuid; # 20953912
SELECT * FROM activities WHERE crm_configuration_id = 275 and provider = 'ringcentral' and title like '%1252629100%';
SELECT * FROM activities WHERE id = 20946641;
SELECT * FROM crm_profiles WHERE user_id = 10211;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120,97,10984, [EMAIL]
SELECT * FROM opportunities WHERE crm_configuration_id = 97 and crm_provider_id = '006N1000006c5PpIAI';
select * from stages where crm_configuration_id = 97 and type = 'opportunity';
select * from opportunities where team_id = 120;
select * from crm_configurations crm join teams t on crm.id = t.crm_id
where 1=1
AND t.current_billing_plan IS NOT NULL
AND crm.auto_sync_activity = 0
and crm.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Exclaimer%'; # 270,205,10053,[EMAIL]
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 270
and sa.provider = 'salesforce';
SELECT * FROM activities WHERE uuid_to_bin('b54df794-2a9a-4957-8d80-09a600ead5f8') = uuid; # 21637956
SELECT * FROM crm_profiles WHERE user_id = 11446;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Cygnetise%'; # 372,300,12554, [EMAIL]
select * from playbooks where team_id = 372;
select * from crm_fields where crm_configuration_id = 300 and object_type = 'event'; # 141340
SELECT * FROM crm_field_values WHERE crm_field_id = 141340;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 372
and sa.provider = 'salesforce';
select * from crm_profiles where crm_configuration_id = 300;
SELECT * FROM crm_configurations WHERE team_id = 372;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Planday%'; # 291,242,11501,[EMAIL]
SELECT * FROM opportunities WHERE team_id = 291 and crm_provider_id = '006bG000005DO86QAG'; # 3207756
select * from crm_field_data where object_id = 3207756;
SELECT * FROM crm_fields WHERE id = 111834;
select f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value
FROM crm_fields f
JOIN crm_field_data fd ON f.id = fd.crm_field_id
WHERE f.crm_configuration_id = 242
AND f.object_type = 'opportunity'
AND fd.object_id IN (3207756)
ORDER BY fd.object_id, fd.updated_at;
SELECT * FROM crm_configurations WHERE auto_connect = 1;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150,[EMAIL]
select * from group_deal_risk_types drgt join groups g on drgt.group_id = g.id
where g.team_id = 187;
select * from `groups` where team_id = 187;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 187
and sa.provider = 'salesforce';
# Destination - 98870 - Destination__c
# Stage - 79014 - StageName
# Land Arrangement - 98856 - Land_Arrangement__c
# Flight - 98848 - Flight__c
# Last activity date - 98812 - LastActivityDate
# Last modified date - 98809 - LastModifiedDate
# Last inbound mail timestamp - 99151 - Last_Inbound_Mail_Timestamp__c
# next call - 98864 - Next_Call__c
select * from crm_fields where crm_configuration_id = 209 and object_type = 'opportunity';
SELECT * FROM crm_layouts WHERE crm_configuration_id = 209;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;
select * from opportunities where team_id = 187 and name LIKE'%Muriel Sal%';
select * from opportunities where team_id = 187 and user_id = 9951 and is_closed = 0;
select * from activities where opportunity_id = 3538248;
SELECT * FROM crm_profiles WHERE user_id = 8150;
select * from deal_risks where opportunity_id = 3538248;
select * from teams where crm_id IS NULL;
SELECT opp.id AS opportunity_id,
u.group_id AS group_id,
MAX(
CASE
WHEN a.type IN ("sms-inbound", "sms-outbound") THEN a.created_at
ELSE a.actual_end_time
END) as last_date
FROM opportunities opp
left join activities a on a.opportunity_id = opp.id
inner join users u on opp.user_id = u.id
where opp.user_id IN (9951)
AND opp.is_closed = 0
and a.status IN ('completed', 'received', 'delivered') OR a.status IS NULL
group by opp.id;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Cybsafe%'; # 343,301,12008,[EMAIL]
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
SELECT * FROM crm_profiles WHERE crm_configuration_id = 301;
SELECT * FROM contacts WHERE id = 6612363;
SELECT * FROM accounts WHERE id = 4235676;
SELECT * FROM opportunities WHERE crm_configuration_id = 301 and crm_provider_id = 32983784868;
select * from opportunity_stages where opportunity_id = 4503759;
# SELECT * FROM opportunities WHERE id = 4569937;
select * from activities where crm_configuration_id = 301;
SELECT * FROM activities WHERE uuid_to_bin('d3b2b28b-c3d0-4c2d-8ed0-eef42855278a') = uuid; # 26330370
SELECT * FROM participants WHERE activity_id = 26330370;
SELECT * FROM teams WHERE id = 375;
select * from playbooks where team_id = 375;
select * from stages where crm_configuration_id = 301 and type = 'opportunity';
select * from teams;
select * from contact_roles;
SELECT * FROM opportunities WHERE team_id = 343 and user_id = 12871 and close_date >= '2024-11-01';
select * from users u join crm_profiles cp on cp.user_id = u.id where u.team_id = 343;
SELECT * FROM crm_field_data WHERE object_id = 3771706;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
SELECT * FROM crm_fields WHERE crm_configuration_id = 301 and object_type = 'opportunity'
and crm_provider_id LIKE "%traffic_light%";
SELECT * FROM crm_field_values WHERE crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531);
SELECT fd.* FROM opportunities o
JOIN crm_field_data fd ON o.id = fd.object_id
WHERE o.team_id = 343
# and o.user_id IS NOT NULL
and fd.crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531)
and fd.value != ''
order by value desc
# group by o.id
;
SELECT * FROM opportunities WHERE id = 3769843;
SELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150, [EMAIL]
SELECT * FROM crm_layouts WHERE crm_configuration_id = 209;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Funding Circle%'; # 220,177,8603,[EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('7a40e99b-3b37-4bb1-b983-325b81801c01') = uuid; # 23139839
SELECT * FROM opportunities WHERE id = 3855992;
SELECT * FROM users WHERE name LIKE '%Angus Pollard%'; # 8988
SELECT * FROM teams WHERE name LIKE '%Story Terrace%'; # 379, 307, 12894
SELECT * FROM crm_fields WHERE crm_configuration_id = 307 and object_type != 'opportunity';
select * from contacts where team_id = 379 and name like '%bebro%'; # 5874411, crm: 77229348507
SELECT * FROM crm_field_data WHERE object_id = 5874411;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 379
and sa.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%mentio%'; # 117, 94, 6371, [EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('82939311-1af0-4506-8546-21e8d1fdf2c1') = uuid;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, [EMAIL]
SELECT * FROM opportunities WHERE team_id = 187 and crm_provider_id = '006Se000008xfvNIAQ'; # 3537793
select * from generic_ai_prompts where subject_id = 3537793;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120, 97, 10984, [EMAIL]
SELECT * FROM crm_configurations WHERE id = 97;
SELECT * FROM crm_layouts WHERE crm_configuration_id = 97;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 355;
SELECT * FROM crm_fields WHERE id = 32682;
select cfd.value, o.* from opportunities o
join crm_field_data cfd on o.id = cfd.object_id and cfd.crm_field_id = 32682
where team_id = 120
and cfd.value != ''
;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 120
and sa.provider = 'salesforce';
select * from opportunities where team_id = 120 and crm_provider_id = '006N1000007X8MAIA0';
SELECT * FROM crm_field_data WHERE object_id = 2313439;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE id = 410;
SELECT * FROM teams WHERE name LIKE '%Local Business Oxford%';
select * from scorecards where team_id = 410;
select * from scorecard_rules;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Funding%'; # 220, 177, 8603, [EMAIL]
select * from activities a
join opportunities o on a.opportunity_id = o.id
join users u on o.user_id = u.id
where a.crm_configuration_id = 177 and a.type LIKE '%email-out%'
# and a.actual_end_time > '2024-12-16 00:00:00'
# and o.remotely_created_at > '2024-12-01 00:00:00'
# and u.group_id = 1014
and u.id = 9021
order by a.id desc;
SELECT * FROM opportunities WHERE id in (3981384,4017346);
SELECT * FROM users WHERE team_id = 220 and id IN (8775, 11435);
select * from users where id = 9021;
select * from inboxes where user_id = 9021;
select * from inbox_emails where inbox_id = 1349 and email_date > '2024-12-18 00:00:00';
select * from email_messages where team_id = 220
and orig_date > '2024-12-16 00:00:00' and orig_date < '2024-12-19 00:00:00'
and subject LIKE '%Personal%'
# and 'from' = '[EMAIL]'
;
select * from activities a
join opportunities o on a.opportunity_id = o.id
where a.user_id = 9021 and a.type LIKE '%email-out%'
and a.actual_end_time > '2024-12-18 00:00:00'
and o.user_id IS NOT NULL
and o.remotely_created_at > '2024-12-01 00:00:00'
order by a.id desc;
SELECT * FROM opportunities WHERE team_id = 220 and name LIKE '%Right Car move Limited%' and id = 3966852;
select * from activities where crm_configuration_id = 177 and type LIKE '%email%' and opportunity_id = 3966852 order by id desc;
select * from team_settings where name IN ('useCloseDate');
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Hurree%'; # 104, 81, 6175, [EMAIL]
SELECT * FROM opportunities WHERE team_id = 104 and name = 'PropOp';
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 104
and sa.provider = 'hubspot';
select * from crm_configurations where last_synced_at > '2025-01-19 01:00:00'
select * from teams where crm_id IS NULL;
select t.name as 'team', u.name as 'owner', u.email, u.phone
from teams t
join activity_providers ap on t.id = ap.team_id
join users u on t.owner_id = u.id
where 1=1
and t.status = 'active'
and ap.is_enabled = 1
# and u.status = 1
and ap.provider = 'ms-teams';
select * from crm_configurations where provider = 'bullhorn'; # 344
SELECT * FROM teams WHERE id = 442; # 14293
select * from users where team_id = 442;
select * from social_accounts sa where sa.sociable_id = 14293;
select * from invitations where team_id = 442;
# [PASSWORD_DOTS]
SELECT * FROM users WHERE email LIKE '%[EMAIL]%'; # 14022
SELECT * FROM teams WHERE id = 429;
select * from opportunities where team_id = 429 and crm_provider_id IN (16157415775, 22246219645);
select * from activities where opportunity_id in (4340436,4353519);
select * from transcription where activity_id IN (25630961,25381771);
select * from generic_ai_prompts where subject_id IN (4353519);
SELECT
a.id as activity_id,
a.opportunity_id,
a.type as activity_type,
a.language,
CONCAT(a.title, a.description) AS mail_content,
e.from AS mail_from,
e.to AS mail_to,
e.subject AS mail_subject,
e.body AS mail_body,
p.type as prompt_type,
p.status as prompt_status,
p.content AS prompt_content,
a.actual_start_time as created_at
FROM activities a
LEFT JOIN ai_prompts p ON a.transcription_id = p.transcription_id AND p.deleted_at IS NULL
LEFT JOIN email_messages e ON a.id = e.activity_id
WHERE a.actual_start_time > '2024-01-01 00:00:00'
AND a.opportunity_id IN (4353519)
AND a.status IN ('completed', 'received', 'delivered')
AND a.deleted_at IS NULL
AND a.type NOT IN ('sms-inbound', 'sms-outbound')
ORDER BY a.opportunity_id ASC, a.id ASC;
SELECT * FROM users WHERE name LIKE '%George Fierstone%'; # 14293
SELECT * FROM teams WHERE id = 442;
SELECT * FROM crm_configurations WHERE id = 344;
select * from team_features where team_id = 442;
select * from groups where team_id = 442;
select * from playbooks where team_id = 442;
select * from playbook_categories where playbook_id = 1729;
select * from crm_fields where crm_configuration_id = 344 and id = 172024;
SELECT * FROM crm_field_values WHERE crm_field_id = 172024;
select * from crm_layouts where crm_configuration_id = 344;
select * from playbook_layouts where playbook_id = 1729;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 221, 9444
select s.*
# , s.sent_at, u.name, a.*
from activity_summary_logs s
inner join activities a on a.id = s.activity_id
inner join users u on u.id = a.user_id
where a.crm_configuration_id = 356
and s.sent_at > date_sub(now(), interval 60 day)
order by a.actual_end_time desc;
select * from activities a
# inner join activity_summary_logs s on s.activity_id = a.id
where a.crm_configuration_id = 356 and a.actual_end_time > date_sub(now(), interval 60 day)
# and a.crm_provider_id is not null
# and provider <> 'ringcentral'
and status = 'completed'
order by a.actual_end_time desc;
select * from teams order by id desc; # 17328, 32, 17830, [EMAIL]
SELECT * FROM users;
SELECT * FROM users where team_id = 260 and status = 1; # 201 - 150 active
SELECT * FROM teams WHERE id = 260;
select * from team_settings where team_id = 260;
select * from crm_configurations where team_id = 260;
SELECT * FROM crm_layouts WHERE crm_configuration_id = 356;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1184;
select * from accounts where crm_configuration_id = 221 order by id desc; # 7000
select * from leads where crm_configuration_id = 221 order by id desc; # 0
select * from contacts where crm_configuration_id = 221 order by id desc; # 200 000
select * from opportunities where crm_configuration_id = 221 order by id desc; # 0
select * from crm_profiles where crm_configuration_id = 221 order by id desc; # 23
select * from crm_fields where crm_configuration_id = 221;
select * from crm_field_values where crm_field_id = 5302 order by id desc;
select * from crm_layouts where crm_configuration_id = 221 order by id desc;
select * from stages where crm_configuration_id = 221 order by id desc;
select * from accounts where crm_configuration_id = 356 order by id desc; # 7000
select * from leads where crm_configuration_id = 356 order by id desc; # 0
select * from contacts where crm_configuration_id = 356 order by id desc; # 200 000
select * from opportunities where crm_configuration_id = 356 order by id desc; # 0
select * from crm_profiles where crm_configuration_id = 356 order by id desc; # 23
select * from crm_fields where crm_configuration_id = 356;
select * from crm_field_values where crm_field_id = 5302 order by id desc;
select * from crm_layouts where crm_configuration_id = 356 order by id desc;
select * from stages where crm_configuration_id = 356 order by id desc;
select * from playbooks where team_id = 260 order by id desc; # 4 (2 deleted)
select * from groups where team_id = 260 order by id desc; # 27 groups, (2 deleted)
select * from playbook_layouts where playbook_id IN (1410,1409,1276,1254); # 4
select ce.* from calendars c
join users u on c.user_id = u.id
join calendar_events ce on c.id = ce.calendar_id
where u.team_id = 260
and (ce.start_time > '2025-02-21 00:00:00')
;
# calendar events 1207
#
select * from opportunities where team_id = 260;
SELECT * FROM crm_field_data WHERE object_id = 4696496;
select * from activities where crm_configuration_id = 356 and crm_provider_id IS NOT NULL;
select * from activities where crm_configuration_id IN (221) and provider NOT IN ('ms-teams', 'uploader', 'zoom-bot')
# and type = 'conference' and status = 'scheduled' and activities.is_internal = 0
and created_at > '2024-03-01 00:00:00'
order by id desc; # 880 000, ringcentral, avaya
SELECT * FROM participants WHERE activity_id = 26371744;
# all activities 942 000 +
# conference 7385 - scheduled 984 - external 343
select * from activities where id = 26321812;
select * from participants where activity_id = 26321812;
select * from participants where activity_id in (26414510,26414514,26414516,26414604,26414653,26414655);
select * from leads where id in (720428,689175,731546,645866,621037);
select * from users where id = 13841;
select * from opportunities where user_id = 9541;
select * from stages where id = 15900;
select * from accounts where
# id IN (4160055,5053725,4965303,4896434)
id in (4584518,3249934,3218025,3891133,3399450,4172999,4485161,3101785,4587203,3070816,2870343,2870341,3563940,4550846,3424464,3249963,2870342)
;
select * from activities where id = 26654935;
SELECT * FROM opportunities WHERE id = 4803458;
SELECT * FROM opportunities where team_id = 260 and user_id = 13841 AND stage_id = 15900;
SELECT id, uuid, provider, type, lead_id, account_id, contact_id, opportunity_id, stage_id, status, recording_state, title, actual_start_time, actual_end_time
FROM activities WHERE user_id = 13841 AND opportunity_id IN (4729783, 4731717, 4731726, 4732064, 4732849, 4803458, 4813213);
SELECT DISTINCT
o.id, o.stage_id, s.name, a.title,
a.*
FROM activities a
# INNER JOIN tracks t ON a.id = t.activity_id
INNER JOIN users u ON a.user_id = u.id
INNER JOIN teams team ON u.team_id = team.id
INNER JOIN groups g ON u.group_id = g.id
INNER JOIN opportunities o ON a.opportunity_id = o.id
INNER JOIN stages s ON o.stage_id = s.id
WHERE
a.crm_configuration_id = 356
AND a.status IN ('completed', 'failed')
AND a.recording_state != 'stopped'
# and a.user_id = 13841
AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')
AND team.uuid = uuid_to_bin('a607fba7-452e-4683-b2af-00d6cb52c93c')
AND g.uuid = uuid_to_bin('b5d69e40-24a0-4c16-810b-5fa462299f94')
AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')
# AND t.type IN ('audio', 'video')
AND (
(a.actual_start_time BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59')
OR
(
a.actual_start_time IS NULL
AND a.type IN ('sms-outbound', 'sms-inbound')
AND a.created_at BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59'
)
)
AND (
a.is_private = 0
OR (
a.is_private = 1
AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')
)
)
AND (
# s.id = 15900
s.uuid = uuid_to_bin('04ca1c26-c666-4268-a129-419c0acffd73')
OR s.uuid IS NULL -- Include records without opportunity stage
)
ORDER BY a.actual_end_time DESC;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lead Forensics%'; # 190, 162, 8474, [EMAIL]
SELECT * FROM users WHERE team_id = 190;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 190
and sa.provider = 'hubspot';
select * from role_user where user_id = 8474;
select * from crm_configurations where provider = 'bullhorn';
SELECT * FROM opportunities WHERE uuid_to_bin('94578249-65ec-4205-90f2-7d1a7d5ab64a') = uuid;
SELECT * FROM users WHERE uuid_to_bin('26dbadeb-926f-4150-b11b-771b9d4c2f9a') = uuid;
SELECT * FROM opportunities ...
|
87826
|
NULL
|
NULL
|
NULL
|
|
87826
|
3001
|
1
|
2026-05-28T16:25:12.120597+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985512120_m2.jpg...
|
PhpStorm
|
faVsco.js – console [EU]
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-8030868166066345329
|
-8630655715339954048
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
rapstomViewCoocWindowFV faVsco.|s ~#12121 on JY-20963-fx-in© Service Test.phpM.CLAUDE mocomooserisonwolcnnedvityCimbald.ongy uimaeumyociwiceonaewemwwocorotor.or(©) ProspectCache.phpACUViy.oncomooserlockdeoendency-checkercordev.sonids.txtintection.son.deMAINCTAImMAINSeNAws.wowcstemwoowonoryownctain© HubspotLastModifiedCreatedRecentiyOpenSyncStrateay.ohg©) PayloadBullder.pho x=custom.loglaravel.logA SF fiminny@loca host)C Salesforce/Service.phd& console (EU] XPropertyChangeManager.phguis users (EUTA console [STAGINGOojiminnyOROERBY SOS COUnT DES031 49 A29 V 3 У 109 A 1class Payloadbuzlden687688liminny_storageMallicaneae maM Makefile# package-lock.jsonphpstan.neon.distEphpstan-baseline.neo< phpunit.xmltraw-Sclquely.scMEREADME.md& sonar-prolect.propertiesEtestiov<> Untitied Diagram.xmls vetur.confialeM.WEBHOOK_FILTERING.IMPLEMENTAT OYnexensorteev Scratches and ConsolesVteeostConot497console iaulADEAL RISKS (EUToNTEUA EU (EU)ylliminnusochinostconsole tliminnweioch moshDi riminny@localhostHS ocallitliminnw@loca nosh#SF (iminny@localhost)zoho-dev (iminny@localhost)V A PRODA console PRODnancalo logeniA DI (PRODI› AOA> A QAI> QAI PRODV ASTAGINGA console (STAGINGA console 1 (STAGING"A uranus (STAGING)>M ExtensionsMScratchas€ | A8 X25 A ~ 17091701* Generate a payload to search for contacts by name.*The searchois a token search sin dinstnane on uostnend17881704public function generateSearchContactsByNamePay2oad(string Snane, array Sficlds): array(...}178S178617075 usages1708public function buildAddAssociationPayload(string Scrnid, array Sids, int Sassociationlype): array{ 17091710public function buildRemoveAssociationPayload(string Scrnid, array $ids): arrayf...;/usagespublic function addClosedStageFilters(array &Spayload, array SclosedStages): voidif ( enpty(SclosedStagesf 'won'1)) 5oavrosolnwense"propercynane" s> "dealstage"vallues 8>SclSeoSROrSROnif (4 enoty(SclosedStagesf'lost•1)) !SoayLondn'Sittens"me'propertyName' => "dealstage","onematon""NODN"-17191720ANDURENH"vallues' E> SclosedStaoest" lost"1749%1737)public function addCreatedDateFilters(array &Spayload, Carbon ScreatedAfter): voidf...*10 usagespublic function getDealsinBulkPayload(array Sdealids): array ...;JEUEER1710SELECT DISTINCT u.id, U.enail, U.name, u.team_id, t.name as team_namet.twilio_sns_sid, t.twilio_messaging_sioFRON users uINNER JOIN teans t (1.n<->1: ON U.tean_id = t.idWHERE (t.twilio_sms_sid IS NOT NULL OR t.twilio_nessaging_sid IS NOT NULL)AND u.status = 1ORDER BY t.name, u.enail;SELECT * FROM teans WHERE nane LIKE "XTourlanex"; # 187,289, 8150, salesforce-adningtourlane.cSELECTCONCAT(u.id, CASE WHEN u.id = t.ownerid THEN " (ouner)' ELSE "* END) AS useridt.owner id FROM social accounts saJOIN users u on u.id = sa.sociable idJOIN teans t 1.n<->1: on t.id = u.tean idWHERE u.team id = 187 and sa.provider = 'salesforce':select * from activities where id = 31264367;select * fron contacts nhere 1d = 6331639:select * fron accounts nhere 1d = 4156632:WheND8 4845018account 1d' = 4156632, "contact 1d" = 6331639opportunity id' = 48"staoe 1d' = 13273)'actsivitstes" "uodated at' = 2826-85-22 87:16-17 wherel"1d' = 31264367)"select * from text_relays where created_at > *2026-85-01°:select * from activities order by id desc;sclect * fron usene shere nane like igSubrake.select * from teans mhere id = 555;CONCAT(u.id, CASE WHEN U.id = t.owner id THEN • (ouner)' ELSE •* END) AS user idv.emailsa.*t.ouner_id FROM social_accounts sainiM neong man noldescodsohloJOIN teams t 1.n<->1on t.id = u.tean 1dNHERE v.team id = 180 and sa.provider = 'hubspot':MH111• Thu 28 May 19:25:11ServiceTestmeesdales orceeneeworeeoeionhnves ohtine oDon+0.run by inportStages(). And inportStages() only runs when a business process or stage is missing.The true, definitive answerAfter all this analysis, the most likely explanation is this is a data snapshot from an earlier time. The opportunity was synoed when closedlost hadprobability 0 (before May 4, 2026). Then someone manually changed the stage probability to 100 on May 4 in Jiminny. But the opportunity hasn't been resynced since then - it shows updated_at: 2826-85-20 but that could be from a different field being updated (lice dealnane, value, etc.) via the Propertychangorsnsteirs orcor uposte pot, wrch does Not roes culate is-wonLook at Procert ychano Mananer: ihandiedeal of rectUodateerooartChaooaltnanonohoohtooh// Update nodel property it mSpropertyMappings = self::0BJECT PROPERTY MAPPINGS [self:: 0BJECT TYPE DEAL] 27 []:tlassetSorocertwaopinasoropertyasesthis=sopportunityRepos{tory=>update0rCreate(...)// Update field datasthises coortootectfelcoatal.ooSOEREUPIATEWWESoro0RENoe.nanedescriot.ton.um.denlmeeorcescrinttonweohook.cucntc.mein.on.wav/0xtcwoud1.Uodate naee on the cooortunty (via undatcorcreste → touches uodatedat2. Return true (bypassing the fuil handleObjectSync / batch queue path)3. NOT recalculate is.voThis is the answer. On May 20, a dealnane or description change webhook arrived. PropertychangeManager: : hand LeDea LDirectUpdate ran, updatecweooworurysnoauoda.coar077-20007301.917800/0UrneoTte=Sk0KW0C1SWCTWOUldnaVrecalculated is, von. The deal's is von was already @ from a previous sync (when closedlost had probability 0, before May 4), and the May 20 directSummarytthe dodortur ty hie iouwed monoruseRators Maw.Shoa20hkliclocadlocthaomaatttituain.tim.amie.nklconsicthotwsth.thhoCootecatttnahtorox//ctwaa.namdr*closedlost*), Any sync at that time would out "closedlost» in lostll → fa closadat, ste vonse2. May 4: Someone manualy updated the stage probability to 100 in Jiminny DB (and/or HubSpot updated their stage label/settings). Stage updated.at:2026-05-04XMav2ozAtn.Soomomoodiodonimraoedesccintionmooew.chanceamvedtoctbe.denPnooadodchono Mintasranhand nhon i nac Miodarafired -it undated the cooortunity's nase field directly (touching undated.at.) but returned true without queuing a full sync. fts won was neve:roasiculstad4. Result: vodatod at= 2976-85-29 looks recent, but the ts mon value is stale from a sync that hagoened before May 4 when the stage probability waetiltoThe fix is to trigger a fresh sync of this specific opportunity: syncOpportunity(*494058190845") would fetch it from HubSpot, see dealstace a *closedlosiodit in moafl (ocobat 100 mowd.nod satemoumGuntaok I still don't cet it. After I nun manual command to pho artisan crmisync-opportunity --teamid 555 --pocortunitvid 494058190045 the cpportunity is.woJiminny last time onCGndalCANA• o172021UITee...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87824
|
3001
|
0
|
2026-05-28T16:25:05.899522+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985505899_m2.jpg...
|
PhpStorm
|
faVsco.js – console [EU]
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Code changed:
Hide
Sync Changes
Hide This Notification
31
9
29
3
109
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM team_features where team_id = 1;
SELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922
SELECT * FROM users WHERE team_id = 340; # 12015
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 340
and sa.provider = 'salesforce';
# and sa.provider = 'salesloft';
select * from crm_fields where crm_configuration_id = 270 and object_type = 'event';
# 125558 - Event Type - Event_Type__c
# 125552 - Event Status - Event_Status__c
SELECT * FROM sidekick_settings WHERE team_id = 340;
SELECT * FROM crm_field_values WHERE crm_field_id in (125552);
select * from activities where crm_configuration_id = 270
and type = 'conference' and crm_provider_id IS NOT NULL
and actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;
SELECT * FROM activities WHERE id = 20871677;
SELECT * FROM crm_field_data WHERE activity_id = 20871677;
select * from crm_layouts where crm_configuration_id = 270;
select * from crm_layout_entities where crm_layout_id in (886,887);
SELECT * FROM crm_configurations WHERE id = 270;
select * from playbooks where team_id = 340; # 1514
select * from groups where team_id = 340;
SELECT * FROM crm_fields WHERE id IN (125393, 125401);
select g.name as 'team name', p.name as 'playbook name', f.label as 'activity type field' from groups g
join playbooks p on g.playbook_id = p.id
join crm_fields f on p.activity_field_id = f.id
where g.team_id = 340;
SELECT * FROM activities WHERE uuid_to_bin('0c180357-67d2-419e-a8c3-b832a3490770') = uuid; # 20448716
select * from crm_field_data where object_id = 20448716;
select * from activities where crm_configuration_id = 270 and provider = 'salesloft' order by id desc;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%CybSafe%'; # 343,273,12008
select * from opportunities where team_id = 343;
select * from opportunities where team_id = 343 and crm_provider_id = '18099102526';
select * from opportunities where team_id = 343 and account_id = 945217482;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
select * from accounts where team_id = 343 order by name asc;
select * from stages where crm_configuration_id = 273 and type = 'opportunity';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Voyado%'; # 353,283,12143
SELECT * FROM activities WHERE crm_configuration_id = 283 and account_id = 3777844 order by id desc;
SELECT * FROM accounts WHERE team_id = 353 AND name LIKE '%Salesloft%';
SELECT * FROM activities WHERE id = 20717903;
select * from participants where activity_id IN (20929172,20928605,20928468,20926272,20926271,20926270,20926269,20916499,20916454,20916436,20916435,20900015,20900014,20900013,20897312,20897243,20897241,20897237,20897232,20897229,20893648,20893231,20893230,20893229,20893228,20889784,20885039,20885038,20885037,20885036,20885035,20882728,20882708,20882703,20882702,20869828,20869811,20869806,20869801,20869799,20869798,20869796,20869795,20869794,20869761,20869760,20869759,20868688,20868687,20850340,20847195,20841710,20833967,20827021,20825307,20825305,20825297,20824615,20824400,20823927,20821760,20795588,20794233,20794057,20793710,20785811,20781789,20781394,20781307,20762651,20758453,20758282,20757323,20756643,20756636,20756629,20756627,20756606,20756605,20756604,20756603,20756602,20756600,20756599,20756598,20756595,20756594,20756589,20756587,20756577,20756573,20748918,20748386,20748385,20748384,20748383,20748382,20748381,20748380,20748379,20748377,20748375,20748373,20743301,20717905,20717904,20717903,20717901,20717899);
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 353
and sa.provider = 'salesforce';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%modern world business solutions%'; # 345,275,12016, [EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('3921d399-3fef-4609-a291-b0097a166d43') = uuid;
# id: 20940638, user: 12022, contact: 5305871
SELECT * FROM activity_summary_logs WHERE activity_id = 20940638;
select * from contacts where team_id = 345 and crm_provider_id = '30891432415' order by name asc; # 5305871
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 345
and sa.provider = 'hubspot';
select * from users where team_id = 345 and id = 12022;
SELECT * FROM crm_profiles WHERE user_id = 12022;
SELECT * FROM participants WHERE activity_id = 20940638;
SELECT * FROM users u
JOIN crm_profiles cp ON u.id = cp.user_id
WHERE u.team_id = 345;
select * from contacts where team_id = 345 and crm_provider_id = '30880813535' order by name desc; # 5305871
select * from team_features where team_id = 345;
SELECT * FROM activities WHERE uuid_to_bin('11701e2d-2f82-4dab-a616-1db4fad238df') = uuid; # 21115197
SELECT * FROM participants WHERE activity_id = 20897406;
SELECT * FROM activities WHERE uuid_to_bin('63ba55cd-1abc-447d-83da-0137000005b7') = uuid; # 20953912
SELECT * FROM activities WHERE crm_configuration_id = 275 and provider = 'ringcentral' and title like '%1252629100%';
SELECT * FROM activities WHERE id = 20946641;
SELECT * FROM crm_profiles WHERE user_id = 10211;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120,97,10984, [EMAIL]
SELECT * FROM opportunities WHERE crm_configuration_id = 97 and crm_provider_id = '006N1000006c5PpIAI';
select * from stages where crm_configuration_id = 97 and type = 'opportunity';
select * from opportunities where team_id = 120;
select * from crm_configurations crm join teams t on crm.id = t.crm_id
where 1=1
AND t.current_billing_plan IS NOT NULL
AND crm.auto_sync_activity = 0
and crm.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Exclaimer%'; # 270,205,10053,[EMAIL]
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 270
and sa.provider = 'salesforce';
SELECT * FROM activities WHERE uuid_to_bin('b54df794-2a9a-4957-8d80-09a600ead5f8') = uuid; # 21637956
SELECT * FROM crm_profiles WHERE user_id = 11446;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Cygnetise%'; # 372,300,12554, [EMAIL]
select * from playbooks where team_id = 372;
select * from crm_fields where crm_configuration_id = 300 and object_type = 'event'; # 141340
SELECT * FROM crm_field_values WHERE crm_field_id = 141340;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 372
and sa.provider = 'salesforce';
select * from crm_profiles where crm_configuration_id = 300;
SELECT * FROM crm_configurations WHERE team_id = 372;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Planday%'; # 291,242,11501,[EMAIL]
SELECT * FROM opportunities WHERE team_id = 291 and crm_provider_id = '006bG000005DO86QAG'; # 3207756
select * from crm_field_data where object_id = 3207756;
SELECT * FROM crm_fields WHERE id = 111834;
select f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value
FROM crm_fields f
JOIN crm_field_data fd ON f.id = fd.crm_field_id
WHERE f.crm_configuration_id = 242
AND f.object_type = 'opportunity'
AND fd.object_id IN (3207756)
ORDER BY fd.object_id, fd.updated_at;
SELECT * FROM crm_configurations WHERE auto_connect = 1;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150,[EMAIL]
select * from group_deal_risk_types drgt join groups g on drgt.group_id = g.id
where g.team_id = 187;
select * from `groups` where team_id = 187;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 187
and sa.provider = 'salesforce';
# Destination - 98870 - Destination__c
# Stage - 79014 - StageName
# Land Arrangement - 98856 - Land_Arrangement__c
# Flight - 98848 - Flight__c
# Last activity date - 98812 - LastActivityDate
# Last modified date - 98809 - LastModifiedDate
# Last inbound mail timestamp - 99151 - Last_Inbound_Mail_Timestamp__c
# next call - 98864 - Next_Call__c
select * from crm_fields where crm_configuration_id = 209 and object_type = 'opportunity';
SELECT * FROM crm_layouts WHERE crm_configuration_id = 209;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;
select * from opportunities where team_id = 187 and name LIKE'%Muriel Sal%';
select * from opportunities where team_id = 187 and user_id = 9951 and is_closed = 0;
select * from activities where opportunity_id = 3538248;
SELECT * FROM crm_profiles WHERE user_id = 8150;
select * from deal_risks where opportunity_id = 3538248;
select * from teams where crm_id IS NULL;
SELECT opp.id AS opportunity_id,
u.group_id AS group_id,
MAX(
CASE
WHEN a.type IN ("sms-inbound", "sms-outbound") THEN a.created_at
ELSE a.actual_end_time
END) as last_date
FROM opportunities opp
left join activities a on a.opportunity_id = opp.id
inner join users u on opp.user_id = u.id
where opp.user_id IN (9951)
AND opp.is_closed = 0
and a.status IN ('completed', 'received', 'delivered') OR a.status IS NULL
group by opp.id;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Cybsafe%'; # 343,301,12008,[EMAIL]
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
SELECT * FROM crm_profiles WHERE crm_configuration_id = 301;
SELECT * FROM contacts WHERE id = 6612363;
SELECT * FROM accounts WHERE id = 4235676;
SELECT * FROM opportunities WHERE crm_configuration_id = 301 and crm_provider_id = 32983784868;
select * from opportunity_stages where opportunity_id = 4503759;
# SELECT * FROM opportunities WHERE id = 4569937;
select * from activities where crm_configuration_id = 301;
SELECT * FROM activities WHERE uuid_to_bin('d3b2b28b-c3d0-4c2d-8ed0-eef42855278a') = uuid; # 26330370
SELECT * FROM participants WHERE activity_id = 26330370;
SELECT * FROM teams WHERE id = 375;
select * from playbooks where team_id = 375;
select * from stages where crm_configuration_id = 301 and type = 'opportunity';
select * from teams;
select * from contact_roles;
SELECT * FROM opportunities WHERE team_id = 343 and user_id = 12871 and close_date >= '2024-11-01';
select * from users u join crm_profiles cp on cp.user_id = u.id where u.team_id = 343;
SELECT * FROM crm_field_data WHERE object_id = 3771706;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
SELECT * FROM crm_fields WHERE crm_configuration_id = 301 and object_type = 'opportunity'
and crm_provider_id LIKE "%traffic_light%";
SELECT * FROM crm_field_values WHERE crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531);
SELECT fd.* FROM opportunities o
JOIN crm_field_data fd ON o.id = fd.object_id
WHERE o.team_id = 343
# and o.user_id IS NOT NULL
and fd.crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531)
and fd.value != ''
order by value desc
# group by o.id
;
SELECT * FROM opportunities WHERE id = 3769843;
SELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150, [EMAIL]
SELECT * FROM crm_layouts WHERE crm_configuration_id = 209;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Funding Circle%'; # 220,177,8603,[EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('7a40e99b-3b37-4bb1-b983-325b81801c01') = uuid; # 23139839
SELECT * FROM opportunities WHERE id = 3855992;
SELECT * FROM users WHERE name LIKE '%Angus Pollard%'; # 8988
SELECT * FROM teams WHERE name LIKE '%Story Terrace%'; # 379, 307, 12894
SELECT * FROM crm_fields WHERE crm_configuration_id = 307 and object_type != 'opportunity';
select * from contacts where team_id = 379 and name like '%bebro%'; # 5874411, crm: 77229348507
SELECT * FROM crm_field_data WHERE object_id = 5874411;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 379
and sa.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%mentio%'; # 117, 94, 6371, [EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('82939311-1af0-4506-8546-21e8d1fdf2c1') = uuid;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, [EMAIL]
SELECT * FROM opportunities WHERE team_id = 187 and crm_provider_id = '006Se000008xfvNIAQ'; # 3537793
select * from generic_ai_prompts where subject_id = 3537793;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120, 97, 10984, [EMAIL]
SELECT * FROM crm_configurations WHERE id = 97;
SELECT * FROM crm_layouts WHERE crm_configuration_id = 97;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 355;
SELECT * FROM crm_fields WHERE id = 32682;
select cfd.value, o.* from opportunities o
join crm_field_data cfd on o.id = cfd.object_id and cfd.crm_field_id = 32682
where team_id = 120
and cfd.value != ''
;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 120
and sa.provider = 'salesforce';
select * from opportunities where team_id = 120 and crm_provider_id = '006N1000007X8MAIA0';
SELECT * FROM crm_field_data WHERE object_id = 2313439;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE id = 410;
SELECT * FROM teams WHERE name LIKE '%Local Business Oxford%';
select * from scorecards where team_id = 410;
select * from scorecard_rules;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Funding%'; # 220, 177, 8603, [EMAIL]
select * from activities a
join opportunities o on a.opportunity_id = o.id
join users u on o.user_id = u.id
where a.crm_configuration_id = 177 and a.type LIKE '%email-out%'
# and a.actual_end_time > '2024-12-16 00:00:00'
# and o.remotely_created_at > '2024-12-01 00:00:00'
# and u.group_id = 1014
and u.id = 9021
order by a.id desc;
SELECT * FROM opportunities WHERE id in (3981384,4017346);
SELECT * FROM users WHERE team_id = 220 and id IN (8775, 11435);
select * from users where id = 9021;
select * from inboxes where user_id = 9021;
select * from inbox_emails where inbox_id = 1349 and email_date > '2024-12-18 00:00:00';
select * from email_messages where team_id = 220
and orig_date > '2024-12-16 00:00:00' and orig_date < '2024-12-19 00:00:00'
and subject LIKE '%Personal%'
# and 'from' = '[EMAIL]'
;
select * from activities a
join opportunities o on a.opportunity_id = o.id
where a.user_id = 9021 and a.type LIKE '%email-out%'
and a.actual_end_time > '2024-12-18 00:00:00'
and o.user_id IS NOT NULL
and o.remotely_created_at > '2024-12-01 00:00:00'
order by a.id desc;
SELECT * FROM opportunities WHERE team_id = 220 and name LIKE '%Right Car move Limited%' and id = 3966852;
select * from activities where crm_configuration_id = 177 and type LIKE '%email%' and opportunity_id = 3966852 order by id desc;
select * from team_settings where name IN ('useCloseDate');
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Hurree%'; # 104, 81, 6175, [EMAIL]
SELECT * FROM opportunities WHERE team_id = 104 and name = 'PropOp';
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 104
and sa.provider = 'hubspot';
select * from crm_configurations where last_synced_at > '2025-01-19 01:00:00'
select * from teams where crm_id IS NULL;
select t.name as 'team', u.name as 'owner', u.email, u.phone
from teams t
join activity_providers ap on t.id = ap.team_id
join users u on t.owner_id = u.id
where 1=1
and t.status = 'active'
and ap.is_enabled = 1
# and u.status = 1
and ap.provider = 'ms-teams';
select * from crm_configurations where provider = 'bullhorn'; # 344
SELECT * FROM teams WHERE id = 442; # 14293
select * from users where team_id = 442;
select * from social_accounts sa where sa.sociable_id = 14293;
select * from invitations where team_id = 442;
# [PASSWORD_DOTS]
SELECT * FROM users WHERE email LIKE '%[EMAIL]%'; # 14022
SELECT * FROM teams WHERE id = 429;
select * from opportunities where team_id = 429 and crm_provider_id IN (16157415775, 22246219645);
select * from activities where opportunity_id in (4340436,4353519);
select * from transcription where activity_id IN (25630961,25381771);
select * from generic_ai_prompts where subject_id IN (4353519);
SELECT
a.id as activity_id,
a.opportunity_id,
a.type as activity_type,
a.language,
CONCAT(a.title, a.description) AS mail_content,
e.from AS mail_from,
e.to AS mail_to,
e.subject AS mail_subject,
e.body AS mail_body,
p.type as prompt_type,
p.status as prompt_status,
p.content AS prompt_content,
a.actual_start_time as created_at
FROM activities a
LEFT JOIN ai_prompts p ON a.transcription_id = p.transcription_id AND p.deleted_at IS NULL
LEFT JOIN email_messages e ON a.id = e.activity_id
WHERE a.actual_start_time > '2024-01-01 00:00:00'
AND a.opportunity_id IN (4353519)
AND a.status IN ('completed', 'received', 'delivered')
AND a.deleted_at IS NULL
AND a.type NOT IN ('sms-inbound', 'sms-outbound')
ORDER BY a.opportunity_id ASC, a.id ASC;
SELECT * FROM users WHERE name LIKE '%George Fierstone%'; # 14293
SELECT * FROM teams WHERE id = 442;
SELECT * FROM crm_configurations WHERE id = 344;
select * from team_features where team_id = 442;
select * from groups where team_id = 442;
select * from playbooks where team_id = 442;
select * from playbook_categories where playbook_id = 1729;
select * from crm_fields where crm_configuration_id = 344 and id = 172024;
SELECT * FROM crm_field_values WHERE crm_field_id = 172024;
select * from crm_layouts where crm_configuration_id = 344;
select * from playbook_layouts where playbook_id = 1729;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 221, 9444
select s.*
# , s.sent_at, u.name, a.*
from activity_summary_logs s
inner join activities a on a.id = s.activity_id
inner join users u on u.id = a.user_id
where a.crm_configuration_id = 356
and s.sent_at > date_sub(now(), interval 60 day)
order by a.actual_end_time desc;
select * from activities a
# inner join activity_summary_logs s on s.activity_id = a.id
where a.crm_configuration_id = 356 and a.actual_end_time > date_sub(now(), interval 60 day)
# and a.crm_provider_id is not null
# and provider <> 'ringcentral'
and status = 'completed'
order by a.actual_end_time desc;
select * from teams order by id desc; # 17328, 32, 17830, [EMAIL]
SELECT * FROM users;
SELECT * FROM users where team_id = 260 and status = 1; # 201 - 150 active
SELECT * FROM teams WHERE id = 260;
select * from team_settings where team_id = 260;
select * from crm_configurations where team_id = 260;
SELECT * FROM crm_layouts WHERE crm_configuration_id = 356;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1184;
select * from accounts where crm_configuration_id = 221 order by id desc; # 7000
select * from leads where crm_configuration_id = 221 order by id desc; # 0
select * from contacts where crm_configuration_id = 221 order by id desc; # 200 000
select * from opportunities where crm_configuration_id = 221 order by id desc; # 0
select * from crm_profiles where crm_configuration_id = 221 order by id desc; # 23
select * from crm_fields where crm_configuration_id = 221;
select * from crm_field_values where crm_field_id = 5302 order by id desc;
select * from crm_layouts where crm_configuration_id = 221 order by id desc;
select * from stages where crm_configuration_id = 221 order by id desc;
select * from accounts where crm_configuration_id = 356 order by id desc; # 7000
select * from leads where crm_configuration_id = 356 order by id desc; # 0
select * from contacts where crm_configuration_id = 356 order by id desc; # 200 000
select * from opportunities where crm_configuration_id = 356 order by id desc; # 0
select * from crm_profiles where crm_configuration_id = 356 order by id desc; # 23
select * from crm_fields where crm_configuration_id = 356;
select * from crm_field_values where crm_field_id = 5302 order by id desc;
select * from crm_layouts where crm_configuration_id = 356 order by id desc;
select * from stages where crm_configuration_id = 356 order by id desc;
select * from playbooks where team_id = 260 order by id desc; # 4 (2 deleted)
select * from groups where team_id = 260 order by id desc; # 27 groups, (2 deleted)
select * from playbook_layouts where playbook_id IN (1410,1409,1276,1254); # 4
select ce.* from calendars c
join users u on c.user_id = u.id
join calendar_events ce on c.id = ce.calendar_id
where u.team_id = 260
and (ce.start_time > '2025-02-21 00:00:00')
;
# calendar events 1207
#
select * from opportunities where team_id = 260;
SELECT * FROM crm_field_data WHERE object_id = 4696496;
select * from activities where crm_configuration_id = 356 and crm_provider_id IS NOT NULL;
select * from activities where crm_configuration_id IN (221) and provider NOT IN ('ms-teams', 'uploader', 'zoom-bot')
# and type = 'conference' and status = 'scheduled' and activities.is_internal = 0
and created_at > '2024-03-01 00:00:00'
order by id desc; # 880 000, ringcentral, avaya
SELECT * FROM participants WHERE activity_id = 26371744;
# all activities 942 000 +
# conference 7385 - scheduled 984 - external 343
select * from activities where id = 26321812;
select * from participants where activity_id = 26321812;
select * from participants where activity_id in (26414510,26414514,26414516,26414604,26414653,26414655);
select * from leads where id in (720428,689175,731546,645866,621037);
select * from users where id = 13841;
select * from opportunities where user_id = 9541;
select * from stages where id = 15900;
select * from accounts where
# id IN (4160055,5053725,4965303,4896434)
id in (4584518,3249934,3218025,3891133,3399450,4172999,4485161,3101785,4587203,3070816,2870343,2870341,3563940,4550846,3424464,3249963,2870342)
;
select * from activities where id = 26654935;
SELECT * FROM opportunities WHERE id = 4803458;
SELECT * FROM opportunities where team_id = 260 and user_id = 13841 AND stage_id = 15900;
SELECT id, uuid, provider, type, lead_id, account_id, contact_id, opportunity_id, stage_id, status, recording_state, title, actual_start_time, actual_end_time
FROM activities WHERE user_id = 13841 AND opportunity_id IN (4729783, 4731717, 4731726, 4732064, 4732849, 4803458, 4813213);
SELECT DISTINCT
o.id, o.stage_id, s.name, a.title,
a.*
FROM activities a
# INNER JOIN tracks t ON a.id = t.activity_id
INNER JOIN users u ON a.user_id = u.id
INNER JOIN teams team ON u.team_id = team.id
INNER JOIN groups g ON u.group_id = g.id
INNER JOIN opportunities o ON a.opportunity_id = o.id
INNER JOIN stages s ON o.stage_id = s.id
WHERE
a.crm_configuration_id = 356
AND a.status IN ('completed', 'failed')
AND a.recording_state != 'stopped'
# and a.user_id = 13841
AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')
AND team.uuid = uuid_to_bin('a607fba7-452e-4683-b2af-00d6cb52c93c')
AND g.uuid = uuid_to_bin('b5d69e40-24a0-4c16-810b-5fa462299f94')
AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')
# AND t.type IN ('audio', 'video')
AND (
(a.actual_start_time BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59')
OR
(
a.actual_start_time IS NULL
AND a.type IN ('sms-outbound', 'sms-inbound')
AND a.created_at BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59'
)
)
AND (
a.is_private = 0
OR (
a.is_private = 1
AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')
)
)
AND (
# s.id = 15900
s.uuid = uuid_to_bin('04ca1c26-c666-4268-a129-419c0acffd73')
OR s.uuid IS NULL -- Include records without opportunity stage
)
ORDER BY a.actual_end_time DESC;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lead Forensics%'; # 190, 162, 8474, [EMAIL]
SELECT * FROM users WHERE team_id = 190;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 190
and sa.provider = 'hubspot';
select * from role_user where user_id = 8474;
select * from crm_configurations where provider = 'bullhorn';
SELECT * FROM opportunities WHERE uuid_to_bin('94578249-65ec-4205-90f2-7d1a7d5ab64a') = uuid;
SELECT * FROM users WHERE uuid_to_bin('26dbadeb-926f-4150-b11b-771b9d4c2f9a') = uuid;
SELECT * FROM opportunities ...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.025930852,"top":0.019952115,"width":0.03856383,"height":0.025538707},"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"bounds":{"left":0.064494684,"top":0.019952115,"width":0.11569149,"height":0.025538707},"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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.85638297,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"bounds":{"left":0.87167555,"top":0.019952115,"width":0.043882977,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"bounds":{"left":0.9155585,"top":0.019952115,"width":0.011303191,"height":0.025538707},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"bounds":{"left":0.9268617,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9381649,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.96609044,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9773936,"top":0.019952115,"width":0.011303191,"height":0.025538707},"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.9886968,"top":0.019952115,"width":0.011303186,"height":0.025538707},"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,"bounds":{"left":0.36635637,"top":0.17478053,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","depth":4,"bounds":{"left":0.37632978,"top":0.17478053,"width":0.009973404,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.3879654,"top":0.17318435,"width":0.00731383,"height":0.018355945},"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.39527926,"top":0.17318435,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Execute","depth":4,"bounds":{"left":0.4039229,"top":0.09896249,"width":0.008643617,"height":0.01915403},"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.41256648,"top":0.09896249,"width":0.008643617,"height":0.01915403},"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,"bounds":{"left":0.42353722,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"bounds":{"left":0.43218085,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"bounds":{"left":0.44082448,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"bounds":{"left":0.45179522,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"bounds":{"left":0.46276596,"top":0.09896249,"width":0.024268618,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"bounds":{"left":0.4893617,"top":0.09896249,"width":0.008643617,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"bounds":{"left":0.5003325,"top":0.09896249,"width":0.029587766,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.64261967,"top":0.09896249,"width":0.02825798,"height":0.01915403},"on_screen":true,"role_description":"button","is_enabled":true,"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":"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":"AXStaticText","text":"31","depth":4,"bounds":{"left":0.60039896,"top":0.123703115,"width":0.009640957,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"9","depth":4,"bounds":{"left":0.61203456,"top":0.123703115,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"29","depth":4,"bounds":{"left":0.62200797,"top":0.123703115,"width":0.010305851,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"3","depth":4,"bounds":{"left":0.6343085,"top":0.123703115,"width":0.007978723,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"109","depth":4,"bounds":{"left":0.6442819,"top":0.123703115,"width":0.011968086,"height":0.015163607},"on_screen":true,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.65791225,"top":0.12210695,"width":0.00731383,"height":0.018355945},"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.66522604,"top":0.12210695,"width":0.006981383,"height":0.018355945},"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"SELECT * FROM team_features where team_id = 1;\n\nSELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922\nSELECT * FROM users WHERE team_id = 340; # 12015\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 340\nand sa.provider = 'salesforce';\n# and sa.provider = 'salesloft';\n\nselect * from crm_fields where crm_configuration_id = 270 and object_type = 'event';\n# 125558 - Event Type - Event_Type__c\n# 125552 - Event Status - Event_Status__c\n\nSELECT * FROM sidekick_settings WHERE team_id = 340;\n\nSELECT * FROM crm_field_values WHERE crm_field_id in (125552);\n\nselect * from activities where crm_configuration_id = 270\nand type = 'conference' and crm_provider_id IS NOT NULL\nand actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;\n\nSELECT * FROM activities WHERE id = 20871677;\nSELECT * FROM crm_field_data WHERE activity_id = 20871677;\n\nselect * from crm_layouts where crm_configuration_id = 270;\nselect * from crm_layout_entities where crm_layout_id in (886,887);\n\nSELECT * FROM crm_configurations WHERE id = 270;\n\nselect * from playbooks where team_id = 340; # 1514\nselect * from groups where team_id = 340;\nSELECT * FROM crm_fields WHERE id IN (125393, 125401);\n\nselect g.name as 'team name', p.name as 'playbook name', f.label as 'activity type field' from groups g\njoin playbooks p on g.playbook_id = p.id\njoin crm_fields f on p.activity_field_id = f.id\nwhere g.team_id = 340;\n\nSELECT * FROM activities WHERE uuid_to_bin('0c180357-67d2-419e-a8c3-b832a3490770') = uuid; # 20448716\nselect * from crm_field_data where object_id = 20448716;\n\nselect * from activities where crm_configuration_id = 270 and provider = 'salesloft' order by id desc;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%CybSafe%'; # 343,273,12008\nselect * from opportunities where team_id = 343;\nselect * from opportunities where team_id = 343 and crm_provider_id = '18099102526';\nselect * from opportunities where team_id = 343 and account_id = 945217482;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nselect * from accounts where team_id = 343 order by name asc;\n\nselect * from stages where crm_configuration_id = 273 and type = 'opportunity';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Voyado%'; # 353,283,12143\nSELECT * FROM activities WHERE crm_configuration_id = 283 and account_id = 3777844 order by id desc;\nSELECT * FROM accounts WHERE team_id = 353 AND name LIKE '%Salesloft%';\nSELECT * FROM activities WHERE id = 20717903;\n\nselect * from participants where activity_id IN (20929172,20928605,20928468,20926272,20926271,20926270,20926269,20916499,20916454,20916436,20916435,20900015,20900014,20900013,20897312,20897243,20897241,20897237,20897232,20897229,20893648,20893231,20893230,20893229,20893228,20889784,20885039,20885038,20885037,20885036,20885035,20882728,20882708,20882703,20882702,20869828,20869811,20869806,20869801,20869799,20869798,20869796,20869795,20869794,20869761,20869760,20869759,20868688,20868687,20850340,20847195,20841710,20833967,20827021,20825307,20825305,20825297,20824615,20824400,20823927,20821760,20795588,20794233,20794057,20793710,20785811,20781789,20781394,20781307,20762651,20758453,20758282,20757323,20756643,20756636,20756629,20756627,20756606,20756605,20756604,20756603,20756602,20756600,20756599,20756598,20756595,20756594,20756589,20756587,20756577,20756573,20748918,20748386,20748385,20748384,20748383,20748382,20748381,20748380,20748379,20748377,20748375,20748373,20743301,20717905,20717904,20717903,20717901,20717899);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 353\nand sa.provider = 'salesforce';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%modern world business solutions%'; # 345,275,12016, l.atkinson@mwbsolutions.co.uk\nSELECT * FROM activities WHERE uuid_to_bin('3921d399-3fef-4609-a291-b0097a166d43') = uuid;\n# id: 20940638, user: 12022, contact: 5305871\nSELECT * FROM activity_summary_logs WHERE activity_id = 20940638;\nselect * from contacts where team_id = 345 and crm_provider_id = '30891432415' order by name asc; # 5305871\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 345\nand sa.provider = 'hubspot';\n\nselect * from users where team_id = 345 and id = 12022;\nSELECT * FROM crm_profiles WHERE user_id = 12022;\nSELECT * FROM participants WHERE activity_id = 20940638;\nSELECT * FROM users u\nJOIN crm_profiles cp ON u.id = cp.user_id\nWHERE u.team_id = 345;\n\nselect * from contacts where team_id = 345 and crm_provider_id = '30880813535' order by name desc; # 5305871\n\nselect * from team_features where team_id = 345;\nSELECT * FROM activities WHERE uuid_to_bin('11701e2d-2f82-4dab-a616-1db4fad238df') = uuid; # 21115197\nSELECT * FROM participants WHERE activity_id = 20897406;\n\n\n\nSELECT * FROM activities WHERE uuid_to_bin('63ba55cd-1abc-447d-83da-0137000005b7') = uuid; # 20953912\nSELECT * FROM activities WHERE crm_configuration_id = 275 and provider = 'ringcentral' and title like '%1252629100%';\n\n\nSELECT * FROM activities WHERE id = 20946641;\nSELECT * FROM crm_profiles WHERE user_id = 10211;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120,97,10984, triger@lunio.ai\nSELECT * FROM opportunities WHERE crm_configuration_id = 97 and crm_provider_id = '006N1000006c5PpIAI';\nselect * from stages where crm_configuration_id = 97 and type = 'opportunity';\nselect * from opportunities where team_id = 120;\n\n\nselect * from crm_configurations crm join teams t on crm.id = t.crm_id\nwhere 1=1\nAND t.current_billing_plan IS NOT NULL\nAND crm.auto_sync_activity = 0\nand crm.provider = 'hubspot';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Exclaimer%'; # 270,205,10053,james.lewendon@exclaimer.com\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 270\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('b54df794-2a9a-4957-8d80-09a600ead5f8') = uuid; # 21637956\nSELECT * FROM crm_profiles WHERE user_id = 11446;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Cygnetise%'; # 372,300,12554, alex.chikly@cygnetise.com\nselect * from playbooks where team_id = 372;\nselect * from crm_fields where crm_configuration_id = 300 and object_type = 'event'; # 141340\nSELECT * FROM crm_field_values WHERE crm_field_id = 141340;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 372\nand sa.provider = 'salesforce';\n\nselect * from crm_profiles where crm_configuration_id = 300;\nSELECT * FROM crm_configurations WHERE team_id = 372;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Planday%'; # 291,242,11501,mfa@planday.com\nSELECT * FROM opportunities WHERE team_id = 291 and crm_provider_id = '006bG000005DO86QAG'; # 3207756\nselect * from crm_field_data where object_id = 3207756;\nSELECT * FROM crm_fields WHERE id = 111834;\n\nselect f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value\nFROM crm_fields f\nJOIN crm_field_data fd ON f.id = fd.crm_field_id\nWHERE f.crm_configuration_id = 242\nAND f.object_type = 'opportunity'\nAND fd.object_id IN (3207756)\nORDER BY fd.object_id, fd.updated_at;\n\nSELECT * FROM crm_configurations WHERE auto_connect = 1;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150,salesforce-admin@tourlane.com\nselect * from group_deal_risk_types drgt join groups g on drgt.group_id = g.id\nwhere g.team_id = 187;\n\nselect * from `groups` where team_id = 187;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 187\nand sa.provider = 'salesforce';\n\n# Destination - 98870 - Destination__c\n# Stage - 79014 - StageName\n# Land Arrangement - 98856 - Land_Arrangement__c\n# Flight - 98848 - Flight__c\n# Last activity date - 98812 - LastActivityDate\n# Last modified date - 98809 - LastModifiedDate\n# Last inbound mail timestamp - 99151 - Last_Inbound_Mail_Timestamp__c\n# next call - 98864 - Next_Call__c\n\nselect * from crm_fields where crm_configuration_id = 209 and object_type = 'opportunity';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 209;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;\n\nselect * from opportunities where team_id = 187 and name LIKE'%Muriel Sal%';\nselect * from opportunities where team_id = 187 and user_id = 9951 and is_closed = 0;\nselect * from activities where opportunity_id = 3538248;\n\nSELECT * FROM crm_profiles WHERE user_id = 8150;\n\nselect * from deal_risks where opportunity_id = 3538248;\n\nselect * from teams where crm_id IS NULL;\n\nSELECT opp.id AS opportunity_id,\n u.group_id AS group_id,\n MAX(\n CASE\n WHEN a.type IN (\"sms-inbound\", \"sms-outbound\") THEN a.created_at\n ELSE a.actual_end_time\n END) as last_date\nFROM opportunities opp\nleft join activities a on a.opportunity_id = opp.id\ninner join users u on opp.user_id = u.id\nwhere opp.user_id IN (9951)\n\nAND opp.is_closed = 0\nand a.status IN ('completed', 'received', 'delivered') OR a.status IS NULL\ngroup by opp.id;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Cybsafe%'; # 343,301,12008,polly.morphew@cybsafe.com\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 301;\nSELECT * FROM contacts WHERE id = 6612363;\nSELECT * FROM accounts WHERE id = 4235676;\nSELECT * FROM opportunities WHERE crm_configuration_id = 301 and crm_provider_id = 32983784868;\nselect * from opportunity_stages where opportunity_id = 4503759;\n# SELECT * FROM opportunities WHERE id = 4569937;\n\nselect * from activities where crm_configuration_id = 301;\nSELECT * FROM activities WHERE uuid_to_bin('d3b2b28b-c3d0-4c2d-8ed0-eef42855278a') = uuid; # 26330370\nSELECT * FROM participants WHERE activity_id = 26330370;\n\nSELECT * FROM teams WHERE id = 375;\nselect * from playbooks where team_id = 375;\n\nselect * from stages where crm_configuration_id = 301 and type = 'opportunity';\n\nselect * from teams;\nselect * from contact_roles;\n\nSELECT * FROM opportunities WHERE team_id = 343 and user_id = 12871 and close_date >= '2024-11-01';\n\nselect * from users u join crm_profiles cp on cp.user_id = u.id where u.team_id = 343;\n\nSELECT * FROM crm_field_data WHERE object_id = 3771706;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_fields WHERE crm_configuration_id = 301 and object_type = 'opportunity'\nand crm_provider_id LIKE \"%traffic_light%\";\nSELECT * FROM crm_field_values WHERE crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531);\n\nSELECT fd.* FROM opportunities o\nJOIN crm_field_data fd ON o.id = fd.object_id\nWHERE o.team_id = 343\n# and o.user_id IS NOT NULL\nand fd.crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531)\nand fd.value != ''\norder by value desc\n# group by o.id\n;\n\nSELECT * FROM opportunities WHERE id = 3769843;\n\nSELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150, salesforce-admin@tourlane.com\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 209;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Funding Circle%'; # 220,177,8603,aswini.mishra@fundingcircle.com\nSELECT * FROM activities WHERE uuid_to_bin('7a40e99b-3b37-4bb1-b983-325b81801c01') = uuid; # 23139839\n\n\nSELECT * FROM opportunities WHERE id = 3855992;\n\nSELECT * FROM users WHERE name LIKE '%Angus Pollard%'; # 8988\n\nSELECT * FROM teams WHERE name LIKE '%Story Terrace%'; # 379, 307, 12894\nSELECT * FROM crm_fields WHERE crm_configuration_id = 307 and object_type != 'opportunity';\n\nselect * from contacts where team_id = 379 and name like '%bebro%'; # 5874411, crm: 77229348507\nSELECT * FROM crm_field_data WHERE object_id = 5874411;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 379\nand sa.provider = 'hubspot';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%mentio%'; # 117, 94, 6371, nikhil.kumar@mention-me.com\nSELECT * FROM activities WHERE uuid_to_bin('82939311-1af0-4506-8546-21e8d1fdf2c1') = uuid;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, salesforce-admin@tourlane.com\nSELECT * FROM opportunities WHERE team_id = 187 and crm_provider_id = '006Se000008xfvNIAQ'; # 3537793\nselect * from generic_ai_prompts where subject_id = 3537793;\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120, 97, 10984, triger@lunio.ai\nSELECT * FROM crm_configurations WHERE id = 97;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 97;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 355;\nSELECT * FROM crm_fields WHERE id = 32682;\n\nselect cfd.value, o.* from opportunities o\njoin crm_field_data cfd on o.id = cfd.object_id and cfd.crm_field_id = 32682\nwhere team_id = 120\nand cfd.value != ''\n;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 120\nand sa.provider = 'salesforce';\n\nselect * from opportunities where team_id = 120 and crm_provider_id = '006N1000007X8MAIA0';\nSELECT * FROM crm_field_data WHERE object_id = 2313439;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE id = 410;\nSELECT * FROM teams WHERE name LIKE '%Local Business Oxford%';\nselect * from scorecards where team_id = 410;\nselect * from scorecard_rules;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Funding%'; # 220, 177, 8603, aswini.mishra@fundingcircle.com\nselect * from activities a\njoin opportunities o on a.opportunity_id = o.id\njoin users u on o.user_id = u.id\nwhere a.crm_configuration_id = 177 and a.type LIKE '%email-out%'\n# and a.actual_end_time > '2024-12-16 00:00:00'\n# and o.remotely_created_at > '2024-12-01 00:00:00'\n# and u.group_id = 1014\nand u.id = 9021\norder by a.id desc;\nSELECT * FROM opportunities WHERE id in (3981384,4017346);\nSELECT * FROM users WHERE team_id = 220 and id IN (8775, 11435);\n\nselect * from users where id = 9021;\nselect * from inboxes where user_id = 9021;\n\nselect * from inbox_emails where inbox_id = 1349 and email_date > '2024-12-18 00:00:00';\n\nselect * from email_messages where team_id = 220\nand orig_date > '2024-12-16 00:00:00' and orig_date < '2024-12-19 00:00:00'\nand subject LIKE '%Personal%'\n# and 'from' = 'credit@fundingcircle.com'\n;\n\nselect * from activities a\njoin opportunities o on a.opportunity_id = o.id\nwhere a.user_id = 9021 and a.type LIKE '%email-out%'\nand a.actual_end_time > '2024-12-18 00:00:00'\nand o.user_id IS NOT NULL\nand o.remotely_created_at > '2024-12-01 00:00:00'\norder by a.id desc;\n\nSELECT * FROM opportunities WHERE team_id = 220 and name LIKE '%Right Car move Limited%' and id = 3966852;\nselect * from activities where crm_configuration_id = 177 and type LIKE '%email%' and opportunity_id = 3966852 order by id desc;\n\nselect * from team_settings where name IN ('useCloseDate');\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Hurree%'; # 104, 81, 6175, jfarrell@hurree.co\nSELECT * FROM opportunities WHERE team_id = 104 and name = 'PropOp';\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 104\nand sa.provider = 'hubspot';\n\nselect * from crm_configurations where last_synced_at > '2025-01-19 01:00:00'\nselect * from teams where crm_id IS NULL;\n\nselect t.name as 'team', u.name as 'owner', u.email, u.phone\nfrom teams t\njoin activity_providers ap on t.id = ap.team_id\njoin users u on t.owner_id = u.id\nwhere 1=1\n and t.status = 'active'\n and ap.is_enabled = 1\n# and u.status = 1\n and ap.provider = 'ms-teams';\n\nselect * from crm_configurations where provider = 'bullhorn'; # 344\nSELECT * FROM teams WHERE id = 442; # 14293\nselect * from users where team_id = 442;\nselect * from social_accounts sa where sa.sociable_id = 14293;\nselect * from invitations where team_id = 442;\n\n# ********************************************************************************************************\nSELECT * FROM users WHERE email LIKE '%nea.liikamaa@eletive.com%'; # 14022\nSELECT * FROM teams WHERE id = 429;\nselect * from opportunities where team_id = 429 and crm_provider_id IN (16157415775, 22246219645);\nselect * from activities where opportunity_id in (4340436,4353519);\n\nselect * from transcription where activity_id IN (25630961,25381771);\nselect * from generic_ai_prompts where subject_id IN (4353519);\n\nSELECT\n a.id as activity_id,\n a.opportunity_id,\n a.type as activity_type,\n a.language,\n CONCAT(a.title, a.description) AS mail_content,\n e.from AS mail_from,\n e.to AS mail_to,\n e.subject AS mail_subject,\n e.body AS mail_body,\n p.type as prompt_type,\n p.status as prompt_status,\n p.content AS prompt_content,\n a.actual_start_time as created_at\nFROM activities a\n LEFT JOIN ai_prompts p ON a.transcription_id = p.transcription_id AND p.deleted_at IS NULL\n LEFT JOIN email_messages e ON a.id = e.activity_id\nWHERE a.actual_start_time > '2024-01-01 00:00:00'\n AND a.opportunity_id IN (4353519)\n AND a.status IN ('completed', 'received', 'delivered')\n AND a.deleted_at IS NULL\n AND a.type NOT IN ('sms-inbound', 'sms-outbound')\nORDER BY a.opportunity_id ASC, a.id ASC;\n\nSELECT * FROM users WHERE name LIKE '%George Fierstone%'; # 14293\nSELECT * FROM teams WHERE id = 442;\nSELECT * FROM crm_configurations WHERE id = 344;\nselect * from team_features where team_id = 442;\nselect * from groups where team_id = 442;\nselect * from playbooks where team_id = 442;\nselect * from playbook_categories where playbook_id = 1729;\nselect * from crm_fields where crm_configuration_id = 344 and id = 172024;\nSELECT * FROM crm_field_values WHERE crm_field_id = 172024;\nselect * from crm_layouts where crm_configuration_id = 344;\nselect * from playbook_layouts where playbook_id = 1729;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 221, 9444\n\nselect s.*\n# , s.sent_at, u.name, a.*\nfrom activity_summary_logs s\ninner join activities a on a.id = s.activity_id\ninner join users u on u.id = a.user_id\nwhere a.crm_configuration_id = 356\nand s.sent_at > date_sub(now(), interval 60 day)\norder by a.actual_end_time desc;\n\nselect * from activities a\n# inner join activity_summary_logs s on s.activity_id = a.id\nwhere a.crm_configuration_id = 356 and a.actual_end_time > date_sub(now(), interval 60 day)\n# and a.crm_provider_id is not null\n# and provider <> 'ringcentral'\nand status = 'completed'\norder by a.actual_end_time desc;\n\nselect * from teams order by id desc; # 17328, 32, 17830, integration-account@jiminny.com\nSELECT * FROM users;\nSELECT * FROM users where team_id = 260 and status = 1; # 201 - 150 active\nSELECT * FROM teams WHERE id = 260;\nselect * from team_settings where team_id = 260;\nselect * from crm_configurations where team_id = 260;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 356;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1184;\n\nselect * from accounts where crm_configuration_id = 221 order by id desc; # 7000\nselect * from leads where crm_configuration_id = 221 order by id desc; # 0\nselect * from contacts where crm_configuration_id = 221 order by id desc; # 200 000\nselect * from opportunities where crm_configuration_id = 221 order by id desc; # 0\nselect * from crm_profiles where crm_configuration_id = 221 order by id desc; # 23\nselect * from crm_fields where crm_configuration_id = 221;\nselect * from crm_field_values where crm_field_id = 5302 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 221 order by id desc;\nselect * from stages where crm_configuration_id = 221 order by id desc;\n\nselect * from accounts where crm_configuration_id = 356 order by id desc; # 7000\nselect * from leads where crm_configuration_id = 356 order by id desc; # 0\nselect * from contacts where crm_configuration_id = 356 order by id desc; # 200 000\nselect * from opportunities where crm_configuration_id = 356 order by id desc; # 0\nselect * from crm_profiles where crm_configuration_id = 356 order by id desc; # 23\nselect * from crm_fields where crm_configuration_id = 356;\nselect * from crm_field_values where crm_field_id = 5302 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 356 order by id desc;\nselect * from stages where crm_configuration_id = 356 order by id desc;\n\nselect * from playbooks where team_id = 260 order by id desc; # 4 (2 deleted)\nselect * from groups where team_id = 260 order by id desc; # 27 groups, (2 deleted)\nselect * from playbook_layouts where playbook_id IN (1410,1409,1276,1254); # 4\nselect ce.* from calendars c\njoin users u on c.user_id = u.id\njoin calendar_events ce on c.id = ce.calendar_id\nwhere u.team_id = 260\nand (ce.start_time > '2025-02-21 00:00:00')\n;\n# calendar events 1207\n#\n\nselect * from opportunities where team_id = 260;\nSELECT * FROM crm_field_data WHERE object_id = 4696496;\n\nselect * from activities where crm_configuration_id = 356 and crm_provider_id IS NOT NULL;\nselect * from activities where crm_configuration_id IN (221) and provider NOT IN ('ms-teams', 'uploader', 'zoom-bot')\n# and type = 'conference' and status = 'scheduled' and activities.is_internal = 0\nand created_at > '2024-03-01 00:00:00'\norder by id desc; # 880 000, ringcentral, avaya\nSELECT * FROM participants WHERE activity_id = 26371744;\n\n# all activities 942 000 +\n# conference 7385 - scheduled 984 - external 343\n\nselect * from activities where id = 26321812;\nselect * from participants where activity_id = 26321812;\nselect * from participants where activity_id in (26414510,26414514,26414516,26414604,26414653,26414655);\nselect * from leads where id in (720428,689175,731546,645866,621037);\n\nselect * from users where id = 13841;\nselect * from opportunities where user_id = 9541;\nselect * from stages where id = 15900;\n\nselect * from accounts where\n# id IN (4160055,5053725,4965303,4896434)\nid in (4584518,3249934,3218025,3891133,3399450,4172999,4485161,3101785,4587203,3070816,2870343,2870341,3563940,4550846,3424464,3249963,2870342)\n;\n\nselect * from activities where id = 26654935;\nSELECT * FROM opportunities WHERE id = 4803458;\n\nSELECT * FROM opportunities where team_id = 260 and user_id = 13841 AND stage_id = 15900;\nSELECT id, uuid, provider, type, lead_id, account_id, contact_id, opportunity_id, stage_id, status, recording_state, title, actual_start_time, actual_end_time\nFROM activities WHERE user_id = 13841 AND opportunity_id IN (4729783, 4731717, 4731726, 4732064, 4732849, 4803458, 4813213);\n\nSELECT DISTINCT\n o.id, o.stage_id, s.name, a.title,\n a.*\nFROM activities a\n# INNER JOIN tracks t ON a.id = t.activity_id\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams team ON u.team_id = team.id\nINNER JOIN groups g ON u.group_id = g.id\nINNER JOIN opportunities o ON a.opportunity_id = o.id\nINNER JOIN stages s ON o.stage_id = s.id\nWHERE\n a.crm_configuration_id = 356\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n# and a.user_id = 13841\n AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')\n AND team.uuid = uuid_to_bin('a607fba7-452e-4683-b2af-00d6cb52c93c')\n AND g.uuid = uuid_to_bin('b5d69e40-24a0-4c16-810b-5fa462299f94')\n\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND t.type IN ('audio', 'video')\n AND (\n (a.actual_start_time BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59')\n OR\n (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59'\n )\n )\n AND (\n a.is_private = 0\n OR (\n a.is_private = 1\n AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')\n )\n )\n AND (\n# s.id = 15900\n s.uuid = uuid_to_bin('04ca1c26-c666-4268-a129-419c0acffd73')\n OR s.uuid IS NULL -- Include records without opportunity stage\n )\n\nORDER BY a.actual_end_time DESC;\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lead Forensics%'; # 190, 162, 8474, willsc@leadforensics.com\nSELECT * FROM users WHERE team_id = 190;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 190\nand sa.provider = 'hubspot';\n\nselect * from role_user where user_id = 8474;\n\nselect * from crm_configurations where provider = 'bullhorn';\n\nSELECT * FROM opportunities WHERE uuid_to_bin('94578249-65ec-4205-90f2-7d1a7d5ab64a') = uuid;\nSELECT * FROM users WHERE uuid_to_bin('26dbadeb-926f-4150-b11b-771b9d4c2f9a') = uuid;\n\nSELECT * FROM opportunities WHERE id = 4732493;\nselect * from activities where opportunity_id = 4732493;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE id = 443; # 358, 14315, andrea.romano@correrenaturale.com\nSELECT * FROM opportunities WHERE team_id = 443;\n\nSELECT a.id, a.type, a.user_id, a.status, a.deleted_at, u.name, u.email, u.team_id as activity_team_id, u.status, u.deleted_at, t.name, t.status, s.team_id as stage_team_id\nFROM activities AS a\nJOIN stages AS s ON a.stage_id = s.id\nJOIN users AS u ON u.id = a.user_id\nJOIN teams AS t ON t.id = s.team_id\nWHERE u.team_id <> s.team_id and t.id > 135;\n\n\nSELECT\n crm_configuration_id,\n crm_provider_id,\n COUNT(*) as duplicate_count,\n GROUP_CONCAT(id) as stage_ids,\n GROUP_CONCAT(name) as stage_names\nFROM stages\nGROUP BY crm_configuration_id, crm_provider_id\nHAVING COUNT(*) > 1\nORDER BY duplicate_count DESC;\n\nselect * from stages where id IN (14898,14907);\n\nselect * from business_processes;\n\nSELECT *\nFROM crm_configurations\nWHERE team_id IN (\n SELECT team_id\n FROM crm_configurations\n GROUP BY team_id\n HAVING COUNT(*) > 1\n)\nORDER BY team_id;\n\nSELECT *\nFROM teams\nWHERE crm_id IN (\n SELECT crm_id\n FROM teams\n GROUP BY crm_id\n HAVING COUNT(*) > 1\n)\nORDER BY crm_id;\n\n# ***************************************************************************\nselect * from crm_configurations where provider = 'integration-app';\nSELECT * FROM teams WHERE id = 443; # Correre Naturale 358 14315 andrea.romano@correrenaturale.com\nselect * from activities where crm_configuration_id = 358 order by actual_end_time desc;\nselect id, uuid, actual_end_time, crm_provider_id, is_internal, playbook_category_id, type, user_id, lead_id, contact_id, account_id, opportunity_id, status, title from activities where crm_configuration_id = 358 order by actual_end_time desc;\nselect * from team_features where team_id = 358;\nselect * from activity_summary_logs;\n\nselect * from teams where id = 406;\n\n# ************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Sportfive%'; # 267, 202, 14637, srv.salesforce@sportfive.com\nselect * from activities where crm_configuration_id = 202 order by actual_end_time desc;\n\nSELECT * FROM users where id = 14637;\nSELECT * FROM teams where id = 267;\nSELECT * FROM groups where id = 1118;\n\nselect g.name, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\ninner join groups g on g.id = u.group_id\nwhere a.crm_configuration_id = 202\nand a.is_internal = 0\nand (a.scheduled_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type = 'conference'\nand a.status != 'completed'\nand a.external_id is not null\norder by a.scheduled_start_time desc;\n\nSELECT * FROM activities\nWHERE crm_configuration_id = 202\n AND status IN ('completed', 'failed')\n AND recording_state != 'stopped'\n AND type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n AND (is_private = 0 OR user_id = 14637)\n AND (\n (\n actual_start_time BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n ) OR (\n actual_start_time IS NULL\n AND type IN ('sms-outbound', 'sms-inbound')\n AND created_at BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n )\n )\n AND NOT EXISTS (\n SELECT 1\n FROM tracks\n WHERE\n tracks.activity_id = activities.id\n AND tracks.type IN ('audio', 'video')\n )\nORDER BY actual_end_time DESC;\n\nSELECT DISTINCT\n a.*\nFROM activities a\nINNER JOIN tracks t ON a.id = t.activity_id\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams team ON u.team_id = team.id\nWHERE\n a.crm_configuration_id = 202\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n# and a.user_id = 14637\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND t.type IN ('audio', 'video')\n AND (\n (a.actual_start_time BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59')\n OR\n (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n )\n )\n AND (\n a.is_private = 0\n OR (\n a.is_private = 1\n AND a.user_id = 14637\n )\n )\n\nORDER BY a.actual_end_time DESC\n;\n\nSELECT DISTINCT a.*\nFROM activities a\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams t ON u.team_id = t.id\n# INNER JOIN tracks tr ON a.id = tr.activity_id\n# INNER JOIN groups g ON u.group_id = g.id\nWHERE 1=1\n AND t.id = 267\n# AND t.uuid = uuid_to_bin('aed4927b-f1ea-499e-94c3-83762fd233e8')\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND tr.type NOT IN ('audio', 'video')\n AND (\n a.is_private = 0\n OR a.user_id = 14637\n )\n AND (\n (a.actual_start_time BETWEEN '2025-03-19 00:00:00' AND '2025-03-21 23:59:59')\n OR (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-19 00:00:00' AND '2025-03-21 23:59:59'\n )\n )\n# and NOT EXISTS (\n# SELECT 1\n# FROM tracks t\n# WHERE t.activity_id = a.id\n# AND t.type IN ('audio', 'video')\n# )\n\nORDER BY a.actual_end_time DESC;\n\nSELECT * FROM tracks WHERE activity_id = 26485995;\n\nselect a.is_private, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\nwhere a.crm_configuration_id = 202\n# and a.is_internal = 0\nand (a.actual_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type IN (\"softphone\",\"softphone-inbound\",\"conference\",\"sms-inbound\")\nand a.status IN ('completed', 'failed')\n# and a.external_id is not null\norder by a.actual_end_time desc;\n\nselect * from activities a where a.crm_configuration_id = 202\nand a.actual_start_time between '2025-03-20 00:00:00' and '2025-03-21 00:00:00'\n# AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n\nselect g.name, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\ninner join groups g on g.id = u.group_id\nwhere a.crm_configuration_id = 202\nand a.is_internal = 0\nand (a.scheduled_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type = 'conference'\nand a.status != 'completed'\nand a.external_id is not null\norder by a.scheduled_start_time desc;\n\nSELECT * FROM teams WHERE name LIKE '%Tourlane%';\nSELECT * FROM crm_fields WHERE crm_configuration_id = 209 and object_type = 'opportunity';\nSELECT * FROM crm_field_data WHERE crm_field_id = 98809;\n\nselect * from users where status = 1 AND timezone = 'MDT';\n\nselect * from opportunities where id = 3769814;\nselect * from deal_risks where opportunity_id = 3769814;\n\nselect cp.* from crm_profiles cp\njoin users u on cp.user_id = u.id\njoin crm_configurations crm on cp.crm_configuration_id = crm.id\nwhere crm.provider = 'hubspot' AND u.status = 1 AND log_notes != 'none';\n\nselect * from crm_fields where id = 154575;\n\nselect * from team_features where feature = 'SUPPORTS_SYNC_MISSING_CALL_DISPOSITIONS';\nSELECT * FROM teams WHERE id = 176; # crm 148\nselect * from activities where crm_configuration_id = 148 and provider = 'hubspot' order by id desc;\n\nselect * from activity_providers where provider = 'amazon-connect';\n\nselect * from crm_fields cf\njoin crm_configurations crm on crm.id = cf.crm_configuration_id\nwhere crm.provider = 'hubspot' and cf.object_type IN ('account', 'contact');\n\n# *********************************************************************************************\nSELECT * FROM users WHERE id IN (15415, 15418);\nSELECT * FROM groups WHERE id IN (1805,1806);\nSELECT * FROM playbooks WHERE id = 1860;\nSELECT * FROM playbook_categories WHERE id = 38634;\nSELECT * FROM crm_fields WHERE id = 189962;\n\nSELECT * FROM teams WHERE name = 'Pulsar Group'; # 472, 380, 15138 raza.gilani@vuelio.com\n\nSELECT * FROM crm_profiles WHERE user_id = 15415;\nSELECT * FROM social_accounts WHERE sociable_id = 15415 and provider = 'salesforce';\n\nselect * from sidekick_settings where team_id = 472;\n\nSELECT * FROM activities WHERE uuid_to_bin('452c58c7-b87c-4fdd-953e-d7af185e9588') = uuid; # 28617536, user: 15418\nSELECT * FROM activities WHERE uuid_to_bin('399114ee-d3a8-458c-bff5-5f654658db0a') = uuid; # 28344407, user: 15415\nSELECT * FROM activities WHERE uuid_to_bin('f0aa567f-0ab1-4bbb-96aa-37dcf184676b') = uuid; # 28580288, user: 15415\nSELECT * FROM activities WHERE uuid_to_bin('50c086b1-2770-4bca-b5ae-6bac22ec426b') = uuid; # 28566069, user: 15415\n\n# *********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%TeamTailor%'; # 109, 218, 13969, salesforce-integrations@teamtailor.com\nselect * from crm_configurations where id = 218;\nSELECT * FROM activities WHERE uuid_to_bin('e39b5857-7fdb-4f5a-951a-8d3ca69bb1b0') = uuid; # 28338765\nSELECT * FROM users WHERE id IN (13232, 13230);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\n\n0057R00000EPL5HQAX Inez Ekblad\n\n1091cb81-5ea1-4951-a0ed-f00b568f0140 Triman Kaur\n\nSELECT * FROM crm_profiles WHERE user_id IN (13232, 13230);\n\n############################################################################################\nSELECT * FROM activities WHERE uuid_to_bin('675eeaeb-5681-42db-90bc-54c07a604408') = uuid; # 28655939 00UVg00000FLvnSMAT\nSELECT * FROM crm_field_data WHERE activity_id = 28655939;\nSELECT * FROM crm_fields WHERE id IN (94491,94493,94498);\nSELECT * FROM users WHERE id = 13658;\nSELECT * FROM teams WHERE id = 109;\nSELECT * FROM crm_configurations WHERE id = 218;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Strengthscope%'; # 481, 390, 15420, katy.holden@strengthscope.comk\nSELECT * FROM stages WHERE crm_configuration_id = 390;\nselect * from business_processes where team_id = 481 and crm_configuration_id = 390;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 481\nand sa.provider = 'salesforce';\n\n\nSELECT * FROM users WHERE id = 15780; # team 462\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 462\nand sa.provider = 'hubspot';\n\n\nselect * from teams where id = 495;\nSELECT * FROM users WHERE id = 15794;\nselect * from social_accounts where sociable_id = 15794;\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Flight%'; # 427, 333, 13752\nSELECT * FROM accounts WHERE team_id = 427 and crm_provider_id = '668731000183444517';\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Group GTI%'; # 495, 407, 15794\nSELECT * FROM activities WHERE crm_configuration_id = 407\nand status = 'completed' and type = 'conference'\norder by id desc;\n\nselect ru.*, pr.*, p.* from users u join role_user ru on ru.user_id = u.id\njoin permission_role pr on pr.role_id = ru.role_id\n join permissions p on p.id = pr.permission_id\nwhere team_id = 495 and p.name IN ('dial');\n\nselect * from permission_role;\n\nselect * from activities where crm_configuration_id = 407 and status = 'completed' order by id desc;\nSELECT * FROM activities WHERE id = 29512773;\nSELECT * FROM activities WHERE id IN (29042721,28991325,29002874);\n\nSELECT al.* from activity_summary_logs al join activities a on a.id = al.activity_id\nwhere a.crm_configuration_id = 407\n# and a.id IN (29042721,28991325,29002874);\n\nSELECT * FROM users WHERE id = 15794;\nSELECT * FROM users WHERE team_id = 495;\nSELECT * FROM social_accounts WHERE sociable_id = 15794;\nSELECT * FROM opportunities WHERE team_id = 495 and name like '%OC:%';\nSELECT * FROM contacts WHERE team_id = 495;\nSELECT * FROM leads WHERE team_id = 495;\nSELECT * FROM accounts WHERE team_id = 495;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 407;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 407;\nSELECT * FROM crm_configurations WHERE id = 407;\nSELECT * FROM opportunities WHERE team_id = 495 and close_date BETWEEN '2025-06-01' AND '2025-07-01'\nand user_id IS NOT NULL and is_closed = 1 and is_won = 1;\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Hamilton Court FX LLP%'; # 249, 187, 10103\nSELECT * FROM activities WHERE uuid_to_bin('4659c2bb-9a49-484e-9327-a3d66f1e028c') = uuid; # 28951064\nSELECT * FROM crm_fields WHERE crm_configuration_id = 187 and object_type IN ('tasks', 'event');\n\n# *********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Checkstep%'; # 325, 256, 11753\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 325\nand sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('7be372e2-1916-4d79-a2f3-ca3db1346db3') = uuid; # 28611085\nSELECT * FROM activities WHERE uuid_to_bin('980f0336-840b-4185-a5a9-30cf8b0749a8') = uuid; # 28719733\nSELECT * FROM activity_summary_logs where activity_id = 28719733;\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 356, 9444\nSELECT * FROM activity_summary_logs where sent_at BETWEEN '2025-06-09 11:38:00' AND '2025-06-09 11:40:00';\nSELECT * FROM leads WHERE crm_configuration_id = 356 and crm_provider_id = '230045001502770504'; # 823630\nselect * from activities where crm_configuration_id = 356 and lead_id = 841732;\n\nSELECT * from activity_summary_logs al join activities a on a.id = al.activity_id\nwhere a.crm_configuration_id = 356;\n\nselect * from activities where crm_configuration_id = 356\nand actual_end_time between '2025-06-09 11:00:00' and '2025-06-09 12:00:00'\norder by id desc;\n\nselect * from accounts where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\nselect * from leads where crm_configuration_id = 356 and crm_provider_id = '230045001514275654' order by id desc;\nselect * from contacts where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\nselect * from opportunities where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\n\nselect * from team_features where team_id = 260;\nselect * from features where id IN (1,2,4,6,18,19,20,9,10,3,23,24,25,26,27);\n\nSELECT * FROM activities WHERE uuid_to_bin('7be372e2-1916-4d79-a2f3-ca3db1346db3') = uuid;\n\nselect * from crm_fields;\nselect * from crm_layout_entities;\n\nSELECT * FROM teams WHERE name LIKE '%Optable%';\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Teamtailor%'; # 109, 218, 13969\nSELECT * FROM crm_configurations WHERE id = 218;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('675eeaeb-5681-42db-90bc-54c07a604408') = uuid; # 28655939\nSELECT * FROM crm_field_data WHERE activity_id = 28655939;\nSELECT * FROM crm_fields WHERE id in (94491,94493,94498);\n\nselect * from teams where crm_id IS NULL;\n\nSELECT * FROM activities WHERE uuid_to_bin('71aa8a0c-9652-4ff6-bee7-d98ae60abef6') = uuid;\n\n# *************************************************************************************************\nselect * from team_domains where team_id = 399;\nSELECT * FROM teams WHERE name LIKE '%Rydoo%'; # 399, 318, 13207\n\nselect * from calendar_events where id = 5163781;\nSELECT * FROM activities WHERE uuid_to_bin('be2cbc52-7fda-46a0-9ae0-25d9553eafc0') = uuid; # 29443896\nSELECT * FROM participants WHERE activity_id = 29443896;\nselect * from contacts where crm_configuration_id = 318 and email = 'marianne.westeng@strawberry.no';\nselect * from leads where crm_configuration_id = 318 and email = 'marianne.westeng@strawberry.no';\n\nselect * from activities where user_id = 14937 order by created_at ;\n\nselect * from users where id = 14937;\n\nselect * from contacts where crm_configuration_id = 318 and email LIKE '%@strawberry.se';\nselect * from opportunities where crm_configuration_id = 318 and crm_provider_id = '006Sf00000D1WOAIA3';\n\nselect * from activities a join participants p on a.id = p.activity_id\nwhere crm_configuration_id = 318 and a.updated_at > '2025-06-23T08:18:43Z';\n\n# *************************************************************************************************\nSELECT * FROM opportunities WHERE team_id = 379 and crm_provider_id = '39334518886';\nSELECT * FROM opportunities WHERE team_id = 379 order by id desc;\nSELECT * FROM teams WHERE id = 379;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 379 and sociable_id = 13852\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations WHERE id = 307;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 307;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1027;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 307\n and id IN (144750,144855,145158,155227);\n\nSELECT * FROM activities;\n\n\nselect * from activities\nwhere created_at > '2025-07-01 00:00:00'\n# and created_at < '2025-08-01 00:00:00'\nand type not in ('email-outbound', 'email-inbound')\nand account_id is null\nand contact_id is null\nand lead_id is null\nand opportunity_id is not null\n;\nSELECT * FROM activities WHERE id IN (25344155, 25344296, 25501909, 28692187);\nSELECT * FROM crm_configurations WHERE id in (335,301,200);\n\nselect * from crm_fields where crm_configuration_id = 230 and crm_provider_id = 'Age2__c';\n\nSELECT * FROM teams WHERE name LIKE '%Resights%';\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\n\nselect * from crm_configurations where provider = 'bullhorn'; # 344\nselect * from teams where id IN (442);\n\nselect * from activities\nwhere crm_configuration_id = 177\nand provider = 'amazon-connect'\n order by id desc;\n# and source <> 'gong';\n\nselect * from activity_providers where provider = 'amazon-connect';\n\nSELECT * FROM activities WHERE uuid_to_bin('cec1993b-a7e5-4164-b74d-d680ea51d2f2') = uuid;\n\n\nselect * from crm_configurations where store_transcript = 1;\nSELECT * FROM teams WHERE id IN (80);\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Sedna%'; # 277, 213, 12594\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 277\nand sa.provider = 'salesforce';\n\nselect * from activities where crm_configuration_id = 213 and account_id = 2511502;\n\nselect * from crm_configurations where id = 213;\n\nSELECT * FROM activities WHERE uuid_to_bin('35aa790a-8569-4544-8268-66f9a4a26804') = uuid; # 33981604\nSELECT * FROM participants WHERE activity_id = 33981604;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 337 and object_type = 'task';\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 431\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('b5476c7d-19a8-491b-869d-676ea1e857b6') = uuid; # 33997223\nselect * from activity_summary_logs where activity_id = 33997223;\nselect * from activity_notes where activity_id = 33997223;\n\n# ***********************************\nSELECT * FROM teams WHERE name LIKE '%Abode%';\n\n\nselect * from features;\nselect * from teams t\nwhere t.status = 'active'\nand id NOT IN (select team_id from team_features where feature_id = 9)\n;\n\n\nselect * from playbook_layouts where playbook_id = 1725;\nSELECT * FROM activities WHERE uuid_to_bin('65cc283c-4849-49e6-927f-4c281c8fea19') = uuid; # 34297473\nselect * from teams where id = 318;\nselect * from crm_configurations where team_id = 318;\nselect * from playbooks where team_id = 318;\nSELECT * FROM crm_layouts where crm_configuration_id = 381;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1259;\nSELECT * FROM crm_fields WHERE id IN (192938,192936,192939);\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1266;\nSELECT * FROM crm_fields WHERE id IN (192980,192991,192997,192998,193064,193067);\n\nSELECT * FROM activities WHERE uuid_to_bin('a902289b-285c-48eb-9cc2-6ad6c5d938f5') = uuid; # 34297533\n\n\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 927;\nSELECT * FROM crm_fields WHERE id IN (131668,131669,131670,131671,131676,131797);\n\nSELECT * FROM teams WHERE name LIKE '%Peripass%'; # 351, 281, 12124\nselect * from crm_layouts where crm_configuration_id = 281;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 927;\nselect * from crm_fields where crm_configuration_id = 281 and id in (131668,131669,131670,131671,131676,131797);\nselect * from opportunities where crm_configuration_id = 281;\n\nSELECT * FROM activities WHERE id IN (34211315, 34130075);\nSELECT * FROM crm_field_data WHERE object_id IN (34211315, 34130075);\n\nselect cf.crm_configuration_id, cle.crm_layout_id, cle.id, cf.id from crm_field_data cfd\njoin crm_layout_entities cle on cle.id = cfd.crm_layout_entity_id\njoin crm_fields cf on cle.crm_field_id = cf.id\nwhere cf.deleted_at IS NOT NULL\nGROUP BY cle.id, cf.id;\n\nselect * from crm_layouts where id IN (355);\nselect u.email, t.crm_id, t.* from teams t\njoin users u on u.id = t.owner_id\nwhere crm_id IN (97);\n\nSELECT * FROM crm_fields WHERE id = 96492;\n\nselect * from permissions;\nselect * from permission_role where permission_id = 247;\nselect * from roles;\n\nselect * from migrations;\n# *****************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('291e3c21-11cc-4728-aee7-6e4bedf86d72') = uuid; # 34262174\nSELECT * FROM crm_configurations WHERE id = 301;\nSELECT * FROM teams WHERE id = 343;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nselect * from participants where activity_id = 34262174;\n\nselect * from contacts where crm_configuration_id = 301 and id = 6976326;\nselect * from accounts where crm_configuration_id = 301 and id IN (4647626, 4815829); # 30761335403\n\nselect * from activity_summary_logs where activity_id = 34262174;\n\nselect * from users where status = 1 AND timezone = 'EST';\n\n# ****************************************************************************\nSELECT * FROM users WHERE id = 13869;\nSELECT * FROM crm_configurations WHERE id = 320;\nSELECT * FROM teams WHERE id = 401;\n\nSELECT * FROM activities WHERE uuid_to_bin('2228c16f-10be-48d5-90d4-67385219dc01') = uuid; # 29670601\n\nSELECT * FROM accounts WHERE id = 7761483;\nSELECT * FROM opportunities WHERE id = 6051814;\n\nSELECT * FROM teams WHERE name LIKE '%Seedlegals%';\n\n;select * from opportunities where updated_at > '2025-10-11' AND crm_provider_id = '34713761166';\n\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 177;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 577;\nSELECT * FROM crm_fields WHERE id IN (68458,68459,68480,68497,68524,68530,68554,68618,68662,68781,68810,68898,68981,69049,97467);\n\nSELECT t.id, crm.id, t.name, crm.sync_objects, crm.provider, crm.last_synced_at FROM crm_configurations crm join teams t on t.crm_id = crm.id\nwhere t.status = 'active' AND crm.provider = 'hubspot' AND crm.last_synced_at < '2025-10-22 00:00:00';\n\nSELECT * FROM activities WHERE uuid_to_bin('fa09449f-cba9-496a-b8f3-865cd3c72351') = uuid;\nSELECT * FROM crm_configurations where id = 184;\nSELECT * FROM teams WHERE id = 246;\nSELECT * FROM social_accounts WHERE sociable_id = 9259 and provider = 'hubspot';\n\nSELECT * FROM users WHERE email LIKE '%rhian.old@bud.co.uk%'; # 17700\nSELECT * FROM teams WHERE id = 551;\n\nSELECT * FROM crm_configurations WHERE id = 471;\nSELECT * FROM activities WHERE crm_configuration_id = 471 and crm_provider_id IS NOT NULL;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 471;\nSELECT * FROM crm_fields WHERE id = 307260;\nSELECT * FROM crm_field_values WHERE crm_field_id = 307260;\n\nselect * from crm_layouts where crm_configuration_id = 471;\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1547;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1548;\n\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 = 551 and sa.provider = 'hubspot';\n\nSELECT * FROM teams WHERE name LIKE '%$PCS%';\n\n# ********************************************************************************************************\nselect * from crm_configurations crm\njoin teams t on t.crm_id = crm.id\nwhere t.status = 'active'\nand crm.provider = 'hubspot';\n\n# $slug = 'HUBSPOT_WEBHOOK_SYNC';\n# $team = Jiminny\\Models\\Team::find(2);\n# $feature = Feature::query()->where('slug', $slug)->first();\n# TeamFeature::query()->create(['feature_id' => $feature->getId(),'team_id' => $team->getId()]);\n\n# hubspot_webhook_metrics\n\nselect * from crm_configurations where id = 331; # 416\nSELECT * FROM teams WHERE id = 416;\nSELECT * FROM opportunities WHERE team_id = 190;\n\nSELECT * FROM teams WHERE name LIKE '%Lead Forensics%';\nSELECT sa.id,\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 = 190 and sa.provider = 'hubspot';\n\n\n\nSELECT * FROM teams WHERE name LIKE '%Rapaport%'; # 431, 337\nSELECT * FROM teams where id = 431;\nSELECT * FROM crm_configurations where team_id = 431;\nSELECT * FROM activity_providers where team_id = 431;\nSELECT * FROM activities where crm_configuration_id = 337 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\nSELECT sa.id,\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 = 431 and sa.provider = 'salesforce';\n\nSELECT * FROM teams WHERE name LIKE '%BiP%'; # 401, 320\nSELECT * FROM teams where id = 401;\nSELECT * FROM crm_configurations where team_id = 401;\nSELECT * FROM activity_providers where team_id = 401;\nSELECT * FROM activities where crm_configuration_id = 320 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\nSELECT sa.id,\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 = 401 and sa.provider = 'salesforce';\n\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 307; # 379 - Story Terrace Inc , portalId: 3921157\nSELECT * FROM contacts WHERE team_id = 379 and updated_at > '2026-01-31 11:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 379 and updated_at > '2026-02-01 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 379 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\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 = 379 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 485; # 563 - LATUS Group (ad94d501-5d09-44fd-878f-ca3a9f8865c3) , portalId: 3904501\nSELECT * FROM opportunities WHERE team_id = 563 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 563 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 338; # 432 - Formalize , portalId: 9214205\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 = 432 and sa.provider = 'hubspot';\nSELECT * FROM opportunities WHERE team_id = 432 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 432 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 436; # 519 - Moxso , portalId: 25531989\nSELECT * FROM opportunities WHERE team_id = 519 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 519 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 96; # 119 - Nourish Care , portalId: 26617984\nSELECT * FROM opportunities WHERE team_id = 119 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 119 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 331; # 416 - The National College , portalId: 7213852\nSELECT * FROM opportunities WHERE team_id = 416 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 416 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 308; # 380 - Foodles , portalId: 7723616\nSELECT * FROM opportunities WHERE team_id = 380 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 380 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 379; # 471 - imat-uve , portalId: 9177354\nSELECT * FROM opportunities WHERE team_id = 471 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 471 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 465; # 545 - Spotler , portalId: 144759271\nSELECT * FROM opportunities WHERE team_id = 545 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 545 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 455; # 537 - indevis , portalId: 25666868\nSELECT * FROM opportunities WHERE team_id = 537 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 537 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 200; # 265 - Jobadder , portalId: 6426676\nSELECT * FROM opportunities WHERE team_id = 265 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 265 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 335; # 429 - Eletive , portalId: 6110563\nSELECT * FROM opportunities WHERE team_id = 429 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 429 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 363; # 456 - Global Group , portalId: 8901981\nSELECT * FROM opportunities WHERE team_id = 456 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 456 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 297; # 369 - Unbiased , portalId: 9229005\nSELECT * FROM opportunities WHERE team_id = 369 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 369 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 353; # 449 - Fuuse , portalId: 25781745\nSELECT * FROM opportunities WHERE team_id = 449 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 449 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 487; # 566 - Nimbus , portalId: 39982590\nSELECT * FROM opportunities WHERE team_id = 566 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 566 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 487;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1630;\nselect * from crm_fields where crm_configuration_id = 487 and\n(uuid_to_bin('4c6b2971-64d4-45b8-b377-427be758b5a5') = uuid or uuid_to_bin('59e368d8-65a0-4b77-b611-db37c99fbe68') = uuid);\nSELECT * FROM crm_field_values WHERE crm_field_id = 375177;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 420; # 506 - voiio , portalId: 145629154\nSELECT * FROM opportunities WHERE team_id = 506 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 506 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 479; # 558 - Momice , portalId: 535962\nSELECT * FROM opportunities WHERE team_id = 558 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 558 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 59; # 80 - Storyclash GmbH , portalId: 4268479\nSELECT * FROM opportunities WHERE team_id = 80 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 80 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 175; # 203 - Team iAM , portalId: 5534732\nSELECT * FROM opportunities WHERE team_id = 203 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 203 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 368; # 460 - OneTouch Health , portalId: 5534732183355\nSELECT * FROM opportunities WHERE team_id = 460 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 460 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\n\n\nselect * from users where id = 29643;\nSELECT * FROM crm_field_values WHERE crm_field_id = 375177;\n# ********************************************************************\nSELECT * FROM teams WHERE name LIKE '%Buynomics%'; # 462, 482, 14910\nSELECT * FROM activities WHERE crm_configuration_id = 482\nand type NOT IN ('email-inbound', 'email-outbound')\n# and description like '%The call focused on understanding Welch%'\norder by id desc;\n\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 = 462 and sa.provider = 'salesforce';\n\nselect * from contacts where crm_configuration_id = 482 and name = 'Cyndall Hill'; # 15504749\nselect * from contacts where id = 10891096; # 482\nSELECT * FROM activities WHERE crm_configuration_id = 482\nand type NOT IN ('email-inbound', 'email-outbound')\nand contact_id = 15504749\norder by id desc;\n\nselect * from activities where id = 36793003; # 96cc7bc1-8622-4d27-92f4-baf664fc1a56, 00UOf00000PDdOXMA1\nselect * from transcription where id = 7646782;\nselect * from ai_prompts where transcription_id = 7646782;\n\n# ********************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('7a8471a3-847e-4822-802b-ddf426bbc252') = uuid; # 37370018\nSELECT * FROM activity_summary_logs WHERE activity_id = 37370018;\nSELECT * FROM teams WHERE id = 555;\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 = 555 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('7c17b8aa-09df-4f85-a0f7-51f47afd712d') = uuid; # 37395250\nSELECT * FROM activities WHERE uuid_to_bin('14d60388-260d-494b-aa0d-63fdb1c78026') = uuid; # 37395250\n\nSELECT a.* FROM activities a JOIN crm_configurations c on c.id = a.crm_configuration_id\nwhere a.type IN ('softphone', 'softphone-outbound') and c.provider = 'hubspot'\nand a.provider NOT IN ('hubspot')\n# and a.provider IN ('salesloft')\n# and c.id NOT IN (70)\n# and a.duration > 30\n# and actual_start_time > '2026-02-05 00:00:00'\norder by a.id desc;\n\nSELECT * FROM activities WHERE id = 37549787;\nSELECT * FROM crm_profiles WHERE user_id = 17613;\n\nSELECT * FROM crm_configurations WHERE id = 70;\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 = 93 and sa.provider = 'hubspot';\n\nSELECT asf.activity_search_id, asf.id, asf.value\nFROM activity_search_filters asf\nWHERE asf.filter = 'group_id'\nAND asf.value IN (\n SELECT CONCAT(\n HEX(SUBSTR(uuid, 5, 4)), '-',\n HEX(SUBSTR(uuid, 3, 2)), '-',\n HEX(SUBSTR(uuid, 1, 2)), '-',\n HEX(SUBSTR(uuid, 9, 2)), '-',\n HEX(SUBSTR(uuid, 11))\n )\n FROM groups\n WHERE deleted_at IS NOT NULL\n);\n\nSELECT * FROM crm_configurations WHERE id = 373; # KPSBremen.de 465 # - no social account\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 = 465 and sa.provider = 'hubspot';\n\nselect * from crm_configurations where id = 494;\n\nSELECT * FROM teams WHERE name LIKE '%splose%'; # 572, 495, 18708\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 = 572 and sa.provider = 'pipedrive';\n\nselect * from opportunities where team_id = 572\n# and name like '%Onebright%'\n# and is_closed = 1 and is_won = 0\n order by id desc;\n\n\nselect * from users where deleted_at is null and status = 2;\n\nselect * from contacts where id = 17900517;\nselect * from accounts where id = 10109838;\nselect * from opportunities where id = 6955880;\n\nselect * from opportunity_contacts where opportunity_id = 6955880;\nselect * from opportunity_contacts where contact_id = 17900517;\n\nselect * from contact_roles cr join crm_configurations crm on cr.crm_configuration_id = crm.id\nwhere crm.provider != 'salesforce';\n\nSELECT * FROM activities WHERE uuid_to_bin('adcb8331-5988-4353-834e-383a355abba2') = uuid; # 38056424, crm 104659682404\nselect * from teams where id = 456;\nSELECT * FROM crm_configurations WHERE id = 363;\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 = 456 and sa.provider = 'hubspot';\n\nselect * from crm_layouts where crm_configuration_id = 363;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id IN (1203, 1204, 1635);\nSELECT * FROM crm_fields WHERE id IN (181536, 181538, 213455);\n\nSELECT * FROM teams WHERE name LIKE '%Electric%'; # 342, 272, 12767\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 = 342 and sa.provider = 'pipedrive';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 and name like 'NORTHUMBRIA POL%'; # and updated_at > '2025-07-01 00:00:00';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 order by remotely_created_at asc; # and updated_at > '2025-07-01 00:00:00';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 and updated_at > '2026-01-01 00:00:00';\nSELECT * FROM crm_fields WHERE crm_configuration_id = 272 and object_type = 'opportunity';\nSELECT * FROM crm_field_values WHERE crm_field_id = 127164;\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 = 342 and sa.provider = 'pipedrive';\n\nSELECT * FROM teams WHERE id = 472;\nSELECT * FROM crm_configurations WHERE id = 380;\nselect * from activities where id = 38285673; # 38285673\nSELECT * FROM users WHERE id = 16942;\nSELECT * FROM groups WHERE id = 1964;\nSELECT * FROM playbooks WHERE id = 2033;\n\nselect * from teams where created_at > '2026-03-09';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 499; # 1065\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1678;\n\nSELECT * FROM teams WHERE id = 575;\nselect * from opportunities where team_id = 575;\n\nSELECT * FROM activities WHERE uuid_to_bin('96b1261f-2357-49f9-ab38-23ce12008ea0') = uuid;\n\nselect * from contacts c\nwhere c.crm_configuration_id = 370 order by c.updated_at desc;\n\nSELECT * FROM participants where activity_id = 38833541;\nSELECT * FROM participants where activity_id = 39216301;\nSELECT * FROM activity_summary_logs where activity_id = 39216301;\nSELECT * FROM activities WHERE uuid_to_bin('c7d99fbe-1fb1-41f2-8f4d-52e2bf70e1e9') = uuid; # 38833541, crm 478116564181\nSELECT * FROM activities WHERE uuid_to_bin('2e6ff4d3-9faa-447a-a8c1-9acde4d885ae') = uuid; # 39216301, crm 480171536586\nselect * from crm_profiles where crm_configuration_id = 319 and crm_provider_id = 525785080;\nselect * from opportunities where crm_configuration_id = 319 and crm_provider_id = 410150124747;\nselect * from accounts where crm_configuration_id = 319 and crm_provider_id = 47150650569;\nselect * from contacts where crm_configuration_id = 319 and crm_provider_id IN ('665587441856', '742723347700');\n# owner 13236 525785080\n# contact 1 16779180 665587441856 - activity - Alex Howes alex@supportroom.com created 2026-01-26\n# contact 2 19247563 742723347700 - ash@supportroom.com 2026-03-24\n# company 4176133 47150650569\n# deal 7100953 410150124747\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 = 400 and sa.provider = 'hubspot';\n\nselect * from features;\nselect * from team_features where feature_id = 40;\n\nselect * from teams where id = 556; # owner: 18101, crm: 477\nselect * from crm_configurations where id = 477;\nSELECT * FROM users WHERE id = 18101;\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 = 556 and sa.provider = 'integration-app';\n\nselect * from opportunities where id = 7594349;\nselect * from opportunity_stages where opportunity_id = 7594349 order by created_at desc;\nselect * from business_processes where id = 6024;\nselect * from business_process_stages where stage_id = 16352;\nselect * from business_process_stages where business_process_id = 6024;\nselect * from stages where team_id = 459;\nselect * from teams where id = 459;\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 = 459 and sa.provider = 'hubspot';\n\nSELECT os.stage_id, s.crm_provider_id, s.name, COUNT(*) as cnt\nFROM opportunity_stages os\nJOIN stages s ON s.id = os.stage_id\nWHERE os.opportunity_id = 7594349\nGROUP BY os.stage_id, s.crm_provider_id, s.name\nORDER BY cnt DESC;\n\nSELECT s.id, s.crm_provider_id, s.name, s.team_id, s.crm_configuration_id\nFROM stages s\nJOIN business_process_stages bps ON bps.stage_id = s.id\nWHERE bps.business_process_id = 6024\nAND s.crm_provider_id = 'contractsent';\n\nselect * from stages where id IN (16352,20612,18281,7344,16378,16309,5036,15223,14535,6293,12098,11607)\n\nSELECT * FROM teams WHERE name LIKE '%Pulsar Group%'; # 472, 380, 15138, raza.gilani@vuelio.com\nselect * from playbooks where team_id = 472; # event 226147\nSELECT * FROM playbook_categories WHERE playbook_id = 2288;\nSELECT * FROM crm_fields WHERE id = 226147;\nSELECT * FROM crm_field_values WHERE crm_field_id = 226147;\n\nSELECT * FROM crm_configurations WHERE id = 380;\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 = 472 and sa.provider = 'salesforce';\n\nselect * from activities where id = 58081273;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2;\n\nSELECT * FROM users WHERE name LIKE '%Neil Hoyle%'; # 17651\nSELECT * FROM social_accounts WHERE sociable_id = 17651;\n\nSELECT * FROM activities WHERE uuid_to_bin('975c6830-7d49-4c1e-b2e9-ac80c10a738a') = uuid;\nSELECT * FROM opportunities WHERE id IN (7842553, 6211727);\nSELECT * FROM contacts WHERE id IN (10202724, 6211727);\nSELECT * FROM opportunity_stages WHERE opportunity_id = 7842553;\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 = 519 and sa.provider = 'hubspot';\n\nselect * from crm_configurations where id = 436;\nselect * from crm_profiles where crm_configuration_id = 436; # 76091797 -> 16612\n\nselect * from contact_roles where contact_id = 10202724;\n\nselect * from stages where team_id = 519; # 18778\n18775\n\nSELECT\n id,\n crm_provider_id,\n stage_id,\n is_closed,\n is_won,\n stage_updated_at,\n updated_at\nFROM opportunities\nWHERE id IN (6211727, 7842553);\n\nSELECT * FROM opportunity_contacts\nWHERE opportunity_id = 6211727 AND contact_id = 10202724;\n\nSELECT id, name, stage_id, is_closed, is_won, updated_at, remotely_created_at\nFROM opportunities\nWHERE account_id = 8179134\nORDER BY updated_at DESC;\n\n\nselect * from text_relays where created_at > '2026-01-01';\nAND id IN (691, 692);\n\nselect * from teams;\n\n# ***************\nSELECT DISTINCT u.id, u.email, u.name, u.softphone_number, COUNT(a.id) as sms_count\nFROM users u\nINNER JOIN activities a ON u.id = a.user_id\nWHERE a.type LIKE 'sms%'\nAND a.created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)\nGROUP BY u.id, u.email, u.name, u.softphone_number\nORDER BY sms_count DESC;\n\nSELECT DISTINCT u.id, u.email, u.name, u.team_id, t.name as team_name,\n t.twilio_sms_sid, t.twilio_messaging_sid\nFROM users u\nINNER JOIN teams t ON u.team_id = t.id\nWHERE (t.twilio_sms_sid IS NOT NULL OR t.twilio_messaging_sid IS NOT NULL)\nAND u.status = 1\nORDER BY t.name, u.email;\n\nSELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, salesforce-admin@tourlane.com\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 = 187 and sa.provider = 'salesforce';\n\nselect * from activities where id = 31264367;\nselect * from contacts where id = 6331639;\nselect * from accounts where id = 4156632;\nselect * from opportunities where id = 4843610;\n# update `activities` set `account_id` = 4156632, `contact_id` = 6331639, `opportunity_id` = 4843610,\n# `stage_id` = 13273, `activities`.`updated_at` = 2026-05-22 07:16:17 where `id` = 31264367)\"\n\nselect * from text_relays where created_at > '2026-05-01';\n\nselect * from activities order by id desc;\n\nselect * from users where name like '%Subra%';\n\nSELECT * FROM opportunities WHERE uuid_to_bin('04a9cfad-2c87-4453-9e72-20aeb78ccf8d') = uuid;\nselect * from teams where id = 555;\nselect * from stages where team_id = 555;\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 = 100 and sa.provider = 'hubspot';","depth":4,"on_screen":true,"value":"SELECT * FROM team_features where team_id = 1;\n\nSELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922\nSELECT * FROM users WHERE team_id = 340; # 12015\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 340\nand sa.provider = 'salesforce';\n# and sa.provider = 'salesloft';\n\nselect * from crm_fields where crm_configuration_id = 270 and object_type = 'event';\n# 125558 - Event Type - Event_Type__c\n# 125552 - Event Status - Event_Status__c\n\nSELECT * FROM sidekick_settings WHERE team_id = 340;\n\nSELECT * FROM crm_field_values WHERE crm_field_id in (125552);\n\nselect * from activities where crm_configuration_id = 270\nand type = 'conference' and crm_provider_id IS NOT NULL\nand actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;\n\nSELECT * FROM activities WHERE id = 20871677;\nSELECT * FROM crm_field_data WHERE activity_id = 20871677;\n\nselect * from crm_layouts where crm_configuration_id = 270;\nselect * from crm_layout_entities where crm_layout_id in (886,887);\n\nSELECT * FROM crm_configurations WHERE id = 270;\n\nselect * from playbooks where team_id = 340; # 1514\nselect * from groups where team_id = 340;\nSELECT * FROM crm_fields WHERE id IN (125393, 125401);\n\nselect g.name as 'team name', p.name as 'playbook name', f.label as 'activity type field' from groups g\njoin playbooks p on g.playbook_id = p.id\njoin crm_fields f on p.activity_field_id = f.id\nwhere g.team_id = 340;\n\nSELECT * FROM activities WHERE uuid_to_bin('0c180357-67d2-419e-a8c3-b832a3490770') = uuid; # 20448716\nselect * from crm_field_data where object_id = 20448716;\n\nselect * from activities where crm_configuration_id = 270 and provider = 'salesloft' order by id desc;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%CybSafe%'; # 343,273,12008\nselect * from opportunities where team_id = 343;\nselect * from opportunities where team_id = 343 and crm_provider_id = '18099102526';\nselect * from opportunities where team_id = 343 and account_id = 945217482;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nselect * from accounts where team_id = 343 order by name asc;\n\nselect * from stages where crm_configuration_id = 273 and type = 'opportunity';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Voyado%'; # 353,283,12143\nSELECT * FROM activities WHERE crm_configuration_id = 283 and account_id = 3777844 order by id desc;\nSELECT * FROM accounts WHERE team_id = 353 AND name LIKE '%Salesloft%';\nSELECT * FROM activities WHERE id = 20717903;\n\nselect * from participants where activity_id IN (20929172,20928605,20928468,20926272,20926271,20926270,20926269,20916499,20916454,20916436,20916435,20900015,20900014,20900013,20897312,20897243,20897241,20897237,20897232,20897229,20893648,20893231,20893230,20893229,20893228,20889784,20885039,20885038,20885037,20885036,20885035,20882728,20882708,20882703,20882702,20869828,20869811,20869806,20869801,20869799,20869798,20869796,20869795,20869794,20869761,20869760,20869759,20868688,20868687,20850340,20847195,20841710,20833967,20827021,20825307,20825305,20825297,20824615,20824400,20823927,20821760,20795588,20794233,20794057,20793710,20785811,20781789,20781394,20781307,20762651,20758453,20758282,20757323,20756643,20756636,20756629,20756627,20756606,20756605,20756604,20756603,20756602,20756600,20756599,20756598,20756595,20756594,20756589,20756587,20756577,20756573,20748918,20748386,20748385,20748384,20748383,20748382,20748381,20748380,20748379,20748377,20748375,20748373,20743301,20717905,20717904,20717903,20717901,20717899);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 353\nand sa.provider = 'salesforce';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%modern world business solutions%'; # 345,275,12016, l.atkinson@mwbsolutions.co.uk\nSELECT * FROM activities WHERE uuid_to_bin('3921d399-3fef-4609-a291-b0097a166d43') = uuid;\n# id: 20940638, user: 12022, contact: 5305871\nSELECT * FROM activity_summary_logs WHERE activity_id = 20940638;\nselect * from contacts where team_id = 345 and crm_provider_id = '30891432415' order by name asc; # 5305871\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 345\nand sa.provider = 'hubspot';\n\nselect * from users where team_id = 345 and id = 12022;\nSELECT * FROM crm_profiles WHERE user_id = 12022;\nSELECT * FROM participants WHERE activity_id = 20940638;\nSELECT * FROM users u\nJOIN crm_profiles cp ON u.id = cp.user_id\nWHERE u.team_id = 345;\n\nselect * from contacts where team_id = 345 and crm_provider_id = '30880813535' order by name desc; # 5305871\n\nselect * from team_features where team_id = 345;\nSELECT * FROM activities WHERE uuid_to_bin('11701e2d-2f82-4dab-a616-1db4fad238df') = uuid; # 21115197\nSELECT * FROM participants WHERE activity_id = 20897406;\n\n\n\nSELECT * FROM activities WHERE uuid_to_bin('63ba55cd-1abc-447d-83da-0137000005b7') = uuid; # 20953912\nSELECT * FROM activities WHERE crm_configuration_id = 275 and provider = 'ringcentral' and title like '%1252629100%';\n\n\nSELECT * FROM activities WHERE id = 20946641;\nSELECT * FROM crm_profiles WHERE user_id = 10211;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120,97,10984, triger@lunio.ai\nSELECT * FROM opportunities WHERE crm_configuration_id = 97 and crm_provider_id = '006N1000006c5PpIAI';\nselect * from stages where crm_configuration_id = 97 and type = 'opportunity';\nselect * from opportunities where team_id = 120;\n\n\nselect * from crm_configurations crm join teams t on crm.id = t.crm_id\nwhere 1=1\nAND t.current_billing_plan IS NOT NULL\nAND crm.auto_sync_activity = 0\nand crm.provider = 'hubspot';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Exclaimer%'; # 270,205,10053,james.lewendon@exclaimer.com\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 270\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('b54df794-2a9a-4957-8d80-09a600ead5f8') = uuid; # 21637956\nSELECT * FROM crm_profiles WHERE user_id = 11446;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Cygnetise%'; # 372,300,12554, alex.chikly@cygnetise.com\nselect * from playbooks where team_id = 372;\nselect * from crm_fields where crm_configuration_id = 300 and object_type = 'event'; # 141340\nSELECT * FROM crm_field_values WHERE crm_field_id = 141340;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 372\nand sa.provider = 'salesforce';\n\nselect * from crm_profiles where crm_configuration_id = 300;\nSELECT * FROM crm_configurations WHERE team_id = 372;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Planday%'; # 291,242,11501,mfa@planday.com\nSELECT * FROM opportunities WHERE team_id = 291 and crm_provider_id = '006bG000005DO86QAG'; # 3207756\nselect * from crm_field_data where object_id = 3207756;\nSELECT * FROM crm_fields WHERE id = 111834;\n\nselect f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value\nFROM crm_fields f\nJOIN crm_field_data fd ON f.id = fd.crm_field_id\nWHERE f.crm_configuration_id = 242\nAND f.object_type = 'opportunity'\nAND fd.object_id IN (3207756)\nORDER BY fd.object_id, fd.updated_at;\n\nSELECT * FROM crm_configurations WHERE auto_connect = 1;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150,salesforce-admin@tourlane.com\nselect * from group_deal_risk_types drgt join groups g on drgt.group_id = g.id\nwhere g.team_id = 187;\n\nselect * from `groups` where team_id = 187;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 187\nand sa.provider = 'salesforce';\n\n# Destination - 98870 - Destination__c\n# Stage - 79014 - StageName\n# Land Arrangement - 98856 - Land_Arrangement__c\n# Flight - 98848 - Flight__c\n# Last activity date - 98812 - LastActivityDate\n# Last modified date - 98809 - LastModifiedDate\n# Last inbound mail timestamp - 99151 - Last_Inbound_Mail_Timestamp__c\n# next call - 98864 - Next_Call__c\n\nselect * from crm_fields where crm_configuration_id = 209 and object_type = 'opportunity';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 209;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;\n\nselect * from opportunities where team_id = 187 and name LIKE'%Muriel Sal%';\nselect * from opportunities where team_id = 187 and user_id = 9951 and is_closed = 0;\nselect * from activities where opportunity_id = 3538248;\n\nSELECT * FROM crm_profiles WHERE user_id = 8150;\n\nselect * from deal_risks where opportunity_id = 3538248;\n\nselect * from teams where crm_id IS NULL;\n\nSELECT opp.id AS opportunity_id,\n u.group_id AS group_id,\n MAX(\n CASE\n WHEN a.type IN (\"sms-inbound\", \"sms-outbound\") THEN a.created_at\n ELSE a.actual_end_time\n END) as last_date\nFROM opportunities opp\nleft join activities a on a.opportunity_id = opp.id\ninner join users u on opp.user_id = u.id\nwhere opp.user_id IN (9951)\n\nAND opp.is_closed = 0\nand a.status IN ('completed', 'received', 'delivered') OR a.status IS NULL\ngroup by opp.id;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Cybsafe%'; # 343,301,12008,polly.morphew@cybsafe.com\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 301;\nSELECT * FROM contacts WHERE id = 6612363;\nSELECT * FROM accounts WHERE id = 4235676;\nSELECT * FROM opportunities WHERE crm_configuration_id = 301 and crm_provider_id = 32983784868;\nselect * from opportunity_stages where opportunity_id = 4503759;\n# SELECT * FROM opportunities WHERE id = 4569937;\n\nselect * from activities where crm_configuration_id = 301;\nSELECT * FROM activities WHERE uuid_to_bin('d3b2b28b-c3d0-4c2d-8ed0-eef42855278a') = uuid; # 26330370\nSELECT * FROM participants WHERE activity_id = 26330370;\n\nSELECT * FROM teams WHERE id = 375;\nselect * from playbooks where team_id = 375;\n\nselect * from stages where crm_configuration_id = 301 and type = 'opportunity';\n\nselect * from teams;\nselect * from contact_roles;\n\nSELECT * FROM opportunities WHERE team_id = 343 and user_id = 12871 and close_date >= '2024-11-01';\n\nselect * from users u join crm_profiles cp on cp.user_id = u.id where u.team_id = 343;\n\nSELECT * FROM crm_field_data WHERE object_id = 3771706;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_fields WHERE crm_configuration_id = 301 and object_type = 'opportunity'\nand crm_provider_id LIKE \"%traffic_light%\";\nSELECT * FROM crm_field_values WHERE crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531);\n\nSELECT fd.* FROM opportunities o\nJOIN crm_field_data fd ON o.id = fd.object_id\nWHERE o.team_id = 343\n# and o.user_id IS NOT NULL\nand fd.crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531)\nand fd.value != ''\norder by value desc\n# group by o.id\n;\n\nSELECT * FROM opportunities WHERE id = 3769843;\n\nSELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150, salesforce-admin@tourlane.com\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 209;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Funding Circle%'; # 220,177,8603,aswini.mishra@fundingcircle.com\nSELECT * FROM activities WHERE uuid_to_bin('7a40e99b-3b37-4bb1-b983-325b81801c01') = uuid; # 23139839\n\n\nSELECT * FROM opportunities WHERE id = 3855992;\n\nSELECT * FROM users WHERE name LIKE '%Angus Pollard%'; # 8988\n\nSELECT * FROM teams WHERE name LIKE '%Story Terrace%'; # 379, 307, 12894\nSELECT * FROM crm_fields WHERE crm_configuration_id = 307 and object_type != 'opportunity';\n\nselect * from contacts where team_id = 379 and name like '%bebro%'; # 5874411, crm: 77229348507\nSELECT * FROM crm_field_data WHERE object_id = 5874411;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 379\nand sa.provider = 'hubspot';\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%mentio%'; # 117, 94, 6371, nikhil.kumar@mention-me.com\nSELECT * FROM activities WHERE uuid_to_bin('82939311-1af0-4506-8546-21e8d1fdf2c1') = uuid;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, salesforce-admin@tourlane.com\nSELECT * FROM opportunities WHERE team_id = 187 and crm_provider_id = '006Se000008xfvNIAQ'; # 3537793\nselect * from generic_ai_prompts where subject_id = 3537793;\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120, 97, 10984, triger@lunio.ai\nSELECT * FROM crm_configurations WHERE id = 97;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 97;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 355;\nSELECT * FROM crm_fields WHERE id = 32682;\n\nselect cfd.value, o.* from opportunities o\njoin crm_field_data cfd on o.id = cfd.object_id and cfd.crm_field_id = 32682\nwhere team_id = 120\nand cfd.value != ''\n;\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 120\nand sa.provider = 'salesforce';\n\nselect * from opportunities where team_id = 120 and crm_provider_id = '006N1000007X8MAIA0';\nSELECT * FROM crm_field_data WHERE object_id = 2313439;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE id = 410;\nSELECT * FROM teams WHERE name LIKE '%Local Business Oxford%';\nselect * from scorecards where team_id = 410;\nselect * from scorecard_rules;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Funding%'; # 220, 177, 8603, aswini.mishra@fundingcircle.com\nselect * from activities a\njoin opportunities o on a.opportunity_id = o.id\njoin users u on o.user_id = u.id\nwhere a.crm_configuration_id = 177 and a.type LIKE '%email-out%'\n# and a.actual_end_time > '2024-12-16 00:00:00'\n# and o.remotely_created_at > '2024-12-01 00:00:00'\n# and u.group_id = 1014\nand u.id = 9021\norder by a.id desc;\nSELECT * FROM opportunities WHERE id in (3981384,4017346);\nSELECT * FROM users WHERE team_id = 220 and id IN (8775, 11435);\n\nselect * from users where id = 9021;\nselect * from inboxes where user_id = 9021;\n\nselect * from inbox_emails where inbox_id = 1349 and email_date > '2024-12-18 00:00:00';\n\nselect * from email_messages where team_id = 220\nand orig_date > '2024-12-16 00:00:00' and orig_date < '2024-12-19 00:00:00'\nand subject LIKE '%Personal%'\n# and 'from' = 'credit@fundingcircle.com'\n;\n\nselect * from activities a\njoin opportunities o on a.opportunity_id = o.id\nwhere a.user_id = 9021 and a.type LIKE '%email-out%'\nand a.actual_end_time > '2024-12-18 00:00:00'\nand o.user_id IS NOT NULL\nand o.remotely_created_at > '2024-12-01 00:00:00'\norder by a.id desc;\n\nSELECT * FROM opportunities WHERE team_id = 220 and name LIKE '%Right Car move Limited%' and id = 3966852;\nselect * from activities where crm_configuration_id = 177 and type LIKE '%email%' and opportunity_id = 3966852 order by id desc;\n\nselect * from team_settings where name IN ('useCloseDate');\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Hurree%'; # 104, 81, 6175, jfarrell@hurree.co\nSELECT * FROM opportunities WHERE team_id = 104 and name = 'PropOp';\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 104\nand sa.provider = 'hubspot';\n\nselect * from crm_configurations where last_synced_at > '2025-01-19 01:00:00'\nselect * from teams where crm_id IS NULL;\n\nselect t.name as 'team', u.name as 'owner', u.email, u.phone\nfrom teams t\njoin activity_providers ap on t.id = ap.team_id\njoin users u on t.owner_id = u.id\nwhere 1=1\n and t.status = 'active'\n and ap.is_enabled = 1\n# and u.status = 1\n and ap.provider = 'ms-teams';\n\nselect * from crm_configurations where provider = 'bullhorn'; # 344\nSELECT * FROM teams WHERE id = 442; # 14293\nselect * from users where team_id = 442;\nselect * from social_accounts sa where sa.sociable_id = 14293;\nselect * from invitations where team_id = 442;\n\n# ********************************************************************************************************\nSELECT * FROM users WHERE email LIKE '%nea.liikamaa@eletive.com%'; # 14022\nSELECT * FROM teams WHERE id = 429;\nselect * from opportunities where team_id = 429 and crm_provider_id IN (16157415775, 22246219645);\nselect * from activities where opportunity_id in (4340436,4353519);\n\nselect * from transcription where activity_id IN (25630961,25381771);\nselect * from generic_ai_prompts where subject_id IN (4353519);\n\nSELECT\n a.id as activity_id,\n a.opportunity_id,\n a.type as activity_type,\n a.language,\n CONCAT(a.title, a.description) AS mail_content,\n e.from AS mail_from,\n e.to AS mail_to,\n e.subject AS mail_subject,\n e.body AS mail_body,\n p.type as prompt_type,\n p.status as prompt_status,\n p.content AS prompt_content,\n a.actual_start_time as created_at\nFROM activities a\n LEFT JOIN ai_prompts p ON a.transcription_id = p.transcription_id AND p.deleted_at IS NULL\n LEFT JOIN email_messages e ON a.id = e.activity_id\nWHERE a.actual_start_time > '2024-01-01 00:00:00'\n AND a.opportunity_id IN (4353519)\n AND a.status IN ('completed', 'received', 'delivered')\n AND a.deleted_at IS NULL\n AND a.type NOT IN ('sms-inbound', 'sms-outbound')\nORDER BY a.opportunity_id ASC, a.id ASC;\n\nSELECT * FROM users WHERE name LIKE '%George Fierstone%'; # 14293\nSELECT * FROM teams WHERE id = 442;\nSELECT * FROM crm_configurations WHERE id = 344;\nselect * from team_features where team_id = 442;\nselect * from groups where team_id = 442;\nselect * from playbooks where team_id = 442;\nselect * from playbook_categories where playbook_id = 1729;\nselect * from crm_fields where crm_configuration_id = 344 and id = 172024;\nSELECT * FROM crm_field_values WHERE crm_field_id = 172024;\nselect * from crm_layouts where crm_configuration_id = 344;\nselect * from playbook_layouts where playbook_id = 1729;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 221, 9444\n\nselect s.*\n# , s.sent_at, u.name, a.*\nfrom activity_summary_logs s\ninner join activities a on a.id = s.activity_id\ninner join users u on u.id = a.user_id\nwhere a.crm_configuration_id = 356\nand s.sent_at > date_sub(now(), interval 60 day)\norder by a.actual_end_time desc;\n\nselect * from activities a\n# inner join activity_summary_logs s on s.activity_id = a.id\nwhere a.crm_configuration_id = 356 and a.actual_end_time > date_sub(now(), interval 60 day)\n# and a.crm_provider_id is not null\n# and provider <> 'ringcentral'\nand status = 'completed'\norder by a.actual_end_time desc;\n\nselect * from teams order by id desc; # 17328, 32, 17830, integration-account@jiminny.com\nSELECT * FROM users;\nSELECT * FROM users where team_id = 260 and status = 1; # 201 - 150 active\nSELECT * FROM teams WHERE id = 260;\nselect * from team_settings where team_id = 260;\nselect * from crm_configurations where team_id = 260;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 356;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1184;\n\nselect * from accounts where crm_configuration_id = 221 order by id desc; # 7000\nselect * from leads where crm_configuration_id = 221 order by id desc; # 0\nselect * from contacts where crm_configuration_id = 221 order by id desc; # 200 000\nselect * from opportunities where crm_configuration_id = 221 order by id desc; # 0\nselect * from crm_profiles where crm_configuration_id = 221 order by id desc; # 23\nselect * from crm_fields where crm_configuration_id = 221;\nselect * from crm_field_values where crm_field_id = 5302 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 221 order by id desc;\nselect * from stages where crm_configuration_id = 221 order by id desc;\n\nselect * from accounts where crm_configuration_id = 356 order by id desc; # 7000\nselect * from leads where crm_configuration_id = 356 order by id desc; # 0\nselect * from contacts where crm_configuration_id = 356 order by id desc; # 200 000\nselect * from opportunities where crm_configuration_id = 356 order by id desc; # 0\nselect * from crm_profiles where crm_configuration_id = 356 order by id desc; # 23\nselect * from crm_fields where crm_configuration_id = 356;\nselect * from crm_field_values where crm_field_id = 5302 order by id desc;\nselect * from crm_layouts where crm_configuration_id = 356 order by id desc;\nselect * from stages where crm_configuration_id = 356 order by id desc;\n\nselect * from playbooks where team_id = 260 order by id desc; # 4 (2 deleted)\nselect * from groups where team_id = 260 order by id desc; # 27 groups, (2 deleted)\nselect * from playbook_layouts where playbook_id IN (1410,1409,1276,1254); # 4\nselect ce.* from calendars c\njoin users u on c.user_id = u.id\njoin calendar_events ce on c.id = ce.calendar_id\nwhere u.team_id = 260\nand (ce.start_time > '2025-02-21 00:00:00')\n;\n# calendar events 1207\n#\n\nselect * from opportunities where team_id = 260;\nSELECT * FROM crm_field_data WHERE object_id = 4696496;\n\nselect * from activities where crm_configuration_id = 356 and crm_provider_id IS NOT NULL;\nselect * from activities where crm_configuration_id IN (221) and provider NOT IN ('ms-teams', 'uploader', 'zoom-bot')\n# and type = 'conference' and status = 'scheduled' and activities.is_internal = 0\nand created_at > '2024-03-01 00:00:00'\norder by id desc; # 880 000, ringcentral, avaya\nSELECT * FROM participants WHERE activity_id = 26371744;\n\n# all activities 942 000 +\n# conference 7385 - scheduled 984 - external 343\n\nselect * from activities where id = 26321812;\nselect * from participants where activity_id = 26321812;\nselect * from participants where activity_id in (26414510,26414514,26414516,26414604,26414653,26414655);\nselect * from leads where id in (720428,689175,731546,645866,621037);\n\nselect * from users where id = 13841;\nselect * from opportunities where user_id = 9541;\nselect * from stages where id = 15900;\n\nselect * from accounts where\n# id IN (4160055,5053725,4965303,4896434)\nid in (4584518,3249934,3218025,3891133,3399450,4172999,4485161,3101785,4587203,3070816,2870343,2870341,3563940,4550846,3424464,3249963,2870342)\n;\n\nselect * from activities where id = 26654935;\nSELECT * FROM opportunities WHERE id = 4803458;\n\nSELECT * FROM opportunities where team_id = 260 and user_id = 13841 AND stage_id = 15900;\nSELECT id, uuid, provider, type, lead_id, account_id, contact_id, opportunity_id, stage_id, status, recording_state, title, actual_start_time, actual_end_time\nFROM activities WHERE user_id = 13841 AND opportunity_id IN (4729783, 4731717, 4731726, 4732064, 4732849, 4803458, 4813213);\n\nSELECT DISTINCT\n o.id, o.stage_id, s.name, a.title,\n a.*\nFROM activities a\n# INNER JOIN tracks t ON a.id = t.activity_id\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams team ON u.team_id = team.id\nINNER JOIN groups g ON u.group_id = g.id\nINNER JOIN opportunities o ON a.opportunity_id = o.id\nINNER JOIN stages s ON o.stage_id = s.id\nWHERE\n a.crm_configuration_id = 356\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n# and a.user_id = 13841\n AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')\n AND team.uuid = uuid_to_bin('a607fba7-452e-4683-b2af-00d6cb52c93c')\n AND g.uuid = uuid_to_bin('b5d69e40-24a0-4c16-810b-5fa462299f94')\n\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND t.type IN ('audio', 'video')\n AND (\n (a.actual_start_time BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59')\n OR\n (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59'\n )\n )\n AND (\n a.is_private = 0\n OR (\n a.is_private = 1\n AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')\n )\n )\n AND (\n# s.id = 15900\n s.uuid = uuid_to_bin('04ca1c26-c666-4268-a129-419c0acffd73')\n OR s.uuid IS NULL -- Include records without opportunity stage\n )\n\nORDER BY a.actual_end_time DESC;\n# ********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Lead Forensics%'; # 190, 162, 8474, willsc@leadforensics.com\nSELECT * FROM users WHERE team_id = 190;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 190\nand sa.provider = 'hubspot';\n\nselect * from role_user where user_id = 8474;\n\nselect * from crm_configurations where provider = 'bullhorn';\n\nSELECT * FROM opportunities WHERE uuid_to_bin('94578249-65ec-4205-90f2-7d1a7d5ab64a') = uuid;\nSELECT * FROM users WHERE uuid_to_bin('26dbadeb-926f-4150-b11b-771b9d4c2f9a') = uuid;\n\nSELECT * FROM opportunities WHERE id = 4732493;\nselect * from activities where opportunity_id = 4732493;\n\n# ********************************************************************************************************\nSELECT * FROM teams WHERE id = 443; # 358, 14315, andrea.romano@correrenaturale.com\nSELECT * FROM opportunities WHERE team_id = 443;\n\nSELECT a.id, a.type, a.user_id, a.status, a.deleted_at, u.name, u.email, u.team_id as activity_team_id, u.status, u.deleted_at, t.name, t.status, s.team_id as stage_team_id\nFROM activities AS a\nJOIN stages AS s ON a.stage_id = s.id\nJOIN users AS u ON u.id = a.user_id\nJOIN teams AS t ON t.id = s.team_id\nWHERE u.team_id <> s.team_id and t.id > 135;\n\n\nSELECT\n crm_configuration_id,\n crm_provider_id,\n COUNT(*) as duplicate_count,\n GROUP_CONCAT(id) as stage_ids,\n GROUP_CONCAT(name) as stage_names\nFROM stages\nGROUP BY crm_configuration_id, crm_provider_id\nHAVING COUNT(*) > 1\nORDER BY duplicate_count DESC;\n\nselect * from stages where id IN (14898,14907);\n\nselect * from business_processes;\n\nSELECT *\nFROM crm_configurations\nWHERE team_id IN (\n SELECT team_id\n FROM crm_configurations\n GROUP BY team_id\n HAVING COUNT(*) > 1\n)\nORDER BY team_id;\n\nSELECT *\nFROM teams\nWHERE crm_id IN (\n SELECT crm_id\n FROM teams\n GROUP BY crm_id\n HAVING COUNT(*) > 1\n)\nORDER BY crm_id;\n\n# ***************************************************************************\nselect * from crm_configurations where provider = 'integration-app';\nSELECT * FROM teams WHERE id = 443; # Correre Naturale 358 14315 andrea.romano@correrenaturale.com\nselect * from activities where crm_configuration_id = 358 order by actual_end_time desc;\nselect id, uuid, actual_end_time, crm_provider_id, is_internal, playbook_category_id, type, user_id, lead_id, contact_id, account_id, opportunity_id, status, title from activities where crm_configuration_id = 358 order by actual_end_time desc;\nselect * from team_features where team_id = 358;\nselect * from activity_summary_logs;\n\nselect * from teams where id = 406;\n\n# ************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Sportfive%'; # 267, 202, 14637, srv.salesforce@sportfive.com\nselect * from activities where crm_configuration_id = 202 order by actual_end_time desc;\n\nSELECT * FROM users where id = 14637;\nSELECT * FROM teams where id = 267;\nSELECT * FROM groups where id = 1118;\n\nselect g.name, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\ninner join groups g on g.id = u.group_id\nwhere a.crm_configuration_id = 202\nand a.is_internal = 0\nand (a.scheduled_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type = 'conference'\nand a.status != 'completed'\nand a.external_id is not null\norder by a.scheduled_start_time desc;\n\nSELECT * FROM activities\nWHERE crm_configuration_id = 202\n AND status IN ('completed', 'failed')\n AND recording_state != 'stopped'\n AND type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n AND (is_private = 0 OR user_id = 14637)\n AND (\n (\n actual_start_time BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n ) OR (\n actual_start_time IS NULL\n AND type IN ('sms-outbound', 'sms-inbound')\n AND created_at BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n )\n )\n AND NOT EXISTS (\n SELECT 1\n FROM tracks\n WHERE\n tracks.activity_id = activities.id\n AND tracks.type IN ('audio', 'video')\n )\nORDER BY actual_end_time DESC;\n\nSELECT DISTINCT\n a.*\nFROM activities a\nINNER JOIN tracks t ON a.id = t.activity_id\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams team ON u.team_id = team.id\nWHERE\n a.crm_configuration_id = 202\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n# and a.user_id = 14637\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND t.type IN ('audio', 'video')\n AND (\n (a.actual_start_time BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59')\n OR\n (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-12 12:00:00' AND '2025-03-24 11:59:59'\n )\n )\n AND (\n a.is_private = 0\n OR (\n a.is_private = 1\n AND a.user_id = 14637\n )\n )\n\nORDER BY a.actual_end_time DESC\n;\n\nSELECT DISTINCT a.*\nFROM activities a\nINNER JOIN users u ON a.user_id = u.id\nINNER JOIN teams t ON u.team_id = t.id\n# INNER JOIN tracks tr ON a.id = tr.activity_id\n# INNER JOIN groups g ON u.group_id = g.id\nWHERE 1=1\n AND t.id = 267\n# AND t.uuid = uuid_to_bin('aed4927b-f1ea-499e-94c3-83762fd233e8')\n AND a.status IN ('completed', 'failed')\n AND a.recording_state != 'stopped'\n AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n# AND tr.type NOT IN ('audio', 'video')\n AND (\n a.is_private = 0\n OR a.user_id = 14637\n )\n AND (\n (a.actual_start_time BETWEEN '2025-03-19 00:00:00' AND '2025-03-21 23:59:59')\n OR (\n a.actual_start_time IS NULL\n AND a.type IN ('sms-outbound', 'sms-inbound')\n AND a.created_at BETWEEN '2025-03-19 00:00:00' AND '2025-03-21 23:59:59'\n )\n )\n# and NOT EXISTS (\n# SELECT 1\n# FROM tracks t\n# WHERE t.activity_id = a.id\n# AND t.type IN ('audio', 'video')\n# )\n\nORDER BY a.actual_end_time DESC;\n\nSELECT * FROM tracks WHERE activity_id = 26485995;\n\nselect a.is_private, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\nwhere a.crm_configuration_id = 202\n# and a.is_internal = 0\nand (a.actual_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type IN (\"softphone\",\"softphone-inbound\",\"conference\",\"sms-inbound\")\nand a.status IN ('completed', 'failed')\n# and a.external_id is not null\norder by a.actual_end_time desc;\n\nselect * from activities a where a.crm_configuration_id = 202\nand a.actual_start_time between '2025-03-20 00:00:00' and '2025-03-21 00:00:00'\n# AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')\n\nselect g.name, a.title, uuid_from_bin(a.uuid), a.external_id, a.status, a.recording_state, a.recording_reason_code, a.scheduled_start_time, a.scheduled_end_time, a.actual_start_time, a.actual_end_time from activities a\ninner join users u on u.id = a.user_id\ninner join groups g on g.id = u.group_id\nwhere a.crm_configuration_id = 202\nand a.is_internal = 0\nand (a.scheduled_start_time between '2025-03-19 00:00:00' and '2025-03-21 00:00:00')\nand a.type = 'conference'\nand a.status != 'completed'\nand a.external_id is not null\norder by a.scheduled_start_time desc;\n\nSELECT * FROM teams WHERE name LIKE '%Tourlane%';\nSELECT * FROM crm_fields WHERE crm_configuration_id = 209 and object_type = 'opportunity';\nSELECT * FROM crm_field_data WHERE crm_field_id = 98809;\n\nselect * from users where status = 1 AND timezone = 'MDT';\n\nselect * from opportunities where id = 3769814;\nselect * from deal_risks where opportunity_id = 3769814;\n\nselect cp.* from crm_profiles cp\njoin users u on cp.user_id = u.id\njoin crm_configurations crm on cp.crm_configuration_id = crm.id\nwhere crm.provider = 'hubspot' AND u.status = 1 AND log_notes != 'none';\n\nselect * from crm_fields where id = 154575;\n\nselect * from team_features where feature = 'SUPPORTS_SYNC_MISSING_CALL_DISPOSITIONS';\nSELECT * FROM teams WHERE id = 176; # crm 148\nselect * from activities where crm_configuration_id = 148 and provider = 'hubspot' order by id desc;\n\nselect * from activity_providers where provider = 'amazon-connect';\n\nselect * from crm_fields cf\njoin crm_configurations crm on crm.id = cf.crm_configuration_id\nwhere crm.provider = 'hubspot' and cf.object_type IN ('account', 'contact');\n\n# *********************************************************************************************\nSELECT * FROM users WHERE id IN (15415, 15418);\nSELECT * FROM groups WHERE id IN (1805,1806);\nSELECT * FROM playbooks WHERE id = 1860;\nSELECT * FROM playbook_categories WHERE id = 38634;\nSELECT * FROM crm_fields WHERE id = 189962;\n\nSELECT * FROM teams WHERE name = 'Pulsar Group'; # 472, 380, 15138 raza.gilani@vuelio.com\n\nSELECT * FROM crm_profiles WHERE user_id = 15415;\nSELECT * FROM social_accounts WHERE sociable_id = 15415 and provider = 'salesforce';\n\nselect * from sidekick_settings where team_id = 472;\n\nSELECT * FROM activities WHERE uuid_to_bin('452c58c7-b87c-4fdd-953e-d7af185e9588') = uuid; # 28617536, user: 15418\nSELECT * FROM activities WHERE uuid_to_bin('399114ee-d3a8-458c-bff5-5f654658db0a') = uuid; # 28344407, user: 15415\nSELECT * FROM activities WHERE uuid_to_bin('f0aa567f-0ab1-4bbb-96aa-37dcf184676b') = uuid; # 28580288, user: 15415\nSELECT * FROM activities WHERE uuid_to_bin('50c086b1-2770-4bca-b5ae-6bac22ec426b') = uuid; # 28566069, user: 15415\n\n# *********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%TeamTailor%'; # 109, 218, 13969, salesforce-integrations@teamtailor.com\nselect * from crm_configurations where id = 218;\nSELECT * FROM activities WHERE uuid_to_bin('e39b5857-7fdb-4f5a-951a-8d3ca69bb1b0') = uuid; # 28338765\nSELECT * FROM users WHERE id IN (13232, 13230);\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\n\n0057R00000EPL5HQAX Inez Ekblad\n\n1091cb81-5ea1-4951-a0ed-f00b568f0140 Triman Kaur\n\nSELECT * FROM crm_profiles WHERE user_id IN (13232, 13230);\n\n############################################################################################\nSELECT * FROM activities WHERE uuid_to_bin('675eeaeb-5681-42db-90bc-54c07a604408') = uuid; # 28655939 00UVg00000FLvnSMAT\nSELECT * FROM crm_field_data WHERE activity_id = 28655939;\nSELECT * FROM crm_fields WHERE id IN (94491,94493,94498);\nSELECT * FROM users WHERE id = 13658;\nSELECT * FROM teams WHERE id = 109;\nSELECT * FROM crm_configurations WHERE id = 218;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Strengthscope%'; # 481, 390, 15420, katy.holden@strengthscope.comk\nSELECT * FROM stages WHERE crm_configuration_id = 390;\nselect * from business_processes where team_id = 481 and crm_configuration_id = 390;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 481\nand sa.provider = 'salesforce';\n\n\nSELECT * FROM users WHERE id = 15780; # team 462\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 462\nand sa.provider = 'hubspot';\n\n\nselect * from teams where id = 495;\nSELECT * FROM users WHERE id = 15794;\nselect * from social_accounts where sociable_id = 15794;\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Flight%'; # 427, 333, 13752\nSELECT * FROM accounts WHERE team_id = 427 and crm_provider_id = '668731000183444517';\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Group GTI%'; # 495, 407, 15794\nSELECT * FROM activities WHERE crm_configuration_id = 407\nand status = 'completed' and type = 'conference'\norder by id desc;\n\nselect ru.*, pr.*, p.* from users u join role_user ru on ru.user_id = u.id\njoin permission_role pr on pr.role_id = ru.role_id\n join permissions p on p.id = pr.permission_id\nwhere team_id = 495 and p.name IN ('dial');\n\nselect * from permission_role;\n\nselect * from activities where crm_configuration_id = 407 and status = 'completed' order by id desc;\nSELECT * FROM activities WHERE id = 29512773;\nSELECT * FROM activities WHERE id IN (29042721,28991325,29002874);\n\nSELECT al.* from activity_summary_logs al join activities a on a.id = al.activity_id\nwhere a.crm_configuration_id = 407\n# and a.id IN (29042721,28991325,29002874);\n\nSELECT * FROM users WHERE id = 15794;\nSELECT * FROM users WHERE team_id = 495;\nSELECT * FROM social_accounts WHERE sociable_id = 15794;\nSELECT * FROM opportunities WHERE team_id = 495 and name like '%OC:%';\nSELECT * FROM contacts WHERE team_id = 495;\nSELECT * FROM leads WHERE team_id = 495;\nSELECT * FROM accounts WHERE team_id = 495;\nSELECT * FROM crm_profiles WHERE crm_configuration_id = 407;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 407;\nSELECT * FROM crm_configurations WHERE id = 407;\nSELECT * FROM opportunities WHERE team_id = 495 and close_date BETWEEN '2025-06-01' AND '2025-07-01'\nand user_id IS NOT NULL and is_closed = 1 and is_won = 1;\n\n# ********************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Hamilton Court FX LLP%'; # 249, 187, 10103\nSELECT * FROM activities WHERE uuid_to_bin('4659c2bb-9a49-484e-9327-a3d66f1e028c') = uuid; # 28951064\nSELECT * FROM crm_fields WHERE crm_configuration_id = 187 and object_type IN ('tasks', 'event');\n\n# *********************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Checkstep%'; # 325, 256, 11753\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 325\nand sa.provider = 'hubspot';\n\nSELECT * FROM activities WHERE uuid_to_bin('7be372e2-1916-4d79-a2f3-ca3db1346db3') = uuid; # 28611085\nSELECT * FROM activities WHERE uuid_to_bin('980f0336-840b-4185-a5a9-30cf8b0749a8') = uuid; # 28719733\nSELECT * FROM activity_summary_logs where activity_id = 28719733;\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 356, 9444\nSELECT * FROM activity_summary_logs where sent_at BETWEEN '2025-06-09 11:38:00' AND '2025-06-09 11:40:00';\nSELECT * FROM leads WHERE crm_configuration_id = 356 and crm_provider_id = '230045001502770504'; # 823630\nselect * from activities where crm_configuration_id = 356 and lead_id = 841732;\n\nSELECT * from activity_summary_logs al join activities a on a.id = al.activity_id\nwhere a.crm_configuration_id = 356;\n\nselect * from activities where crm_configuration_id = 356\nand actual_end_time between '2025-06-09 11:00:00' and '2025-06-09 12:00:00'\norder by id desc;\n\nselect * from accounts where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\nselect * from leads where crm_configuration_id = 356 and crm_provider_id = '230045001514275654' order by id desc;\nselect * from contacts where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\nselect * from opportunities where crm_configuration_id = 356 and crm_provider_id = '230045001514403366' order by id desc;\n\nselect * from team_features where team_id = 260;\nselect * from features where id IN (1,2,4,6,18,19,20,9,10,3,23,24,25,26,27);\n\nSELECT * FROM activities WHERE uuid_to_bin('7be372e2-1916-4d79-a2f3-ca3db1346db3') = uuid;\n\nselect * from crm_fields;\nselect * from crm_layout_entities;\n\nSELECT * FROM teams WHERE name LIKE '%Optable%';\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Teamtailor%'; # 109, 218, 13969\nSELECT * FROM crm_configurations WHERE id = 218;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 109\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('675eeaeb-5681-42db-90bc-54c07a604408') = uuid; # 28655939\nSELECT * FROM crm_field_data WHERE activity_id = 28655939;\nSELECT * FROM crm_fields WHERE id in (94491,94493,94498);\n\nselect * from teams where crm_id IS NULL;\n\nSELECT * FROM activities WHERE uuid_to_bin('71aa8a0c-9652-4ff6-bee7-d98ae60abef6') = uuid;\n\n# *************************************************************************************************\nselect * from team_domains where team_id = 399;\nSELECT * FROM teams WHERE name LIKE '%Rydoo%'; # 399, 318, 13207\n\nselect * from calendar_events where id = 5163781;\nSELECT * FROM activities WHERE uuid_to_bin('be2cbc52-7fda-46a0-9ae0-25d9553eafc0') = uuid; # 29443896\nSELECT * FROM participants WHERE activity_id = 29443896;\nselect * from contacts where crm_configuration_id = 318 and email = 'marianne.westeng@strawberry.no';\nselect * from leads where crm_configuration_id = 318 and email = 'marianne.westeng@strawberry.no';\n\nselect * from activities where user_id = 14937 order by created_at ;\n\nselect * from users where id = 14937;\n\nselect * from contacts where crm_configuration_id = 318 and email LIKE '%@strawberry.se';\nselect * from opportunities where crm_configuration_id = 318 and crm_provider_id = '006Sf00000D1WOAIA3';\n\nselect * from activities a join participants p on a.id = p.activity_id\nwhere crm_configuration_id = 318 and a.updated_at > '2025-06-23T08:18:43Z';\n\n# *************************************************************************************************\nSELECT * FROM opportunities WHERE team_id = 379 and crm_provider_id = '39334518886';\nSELECT * FROM opportunities WHERE team_id = 379 order by id desc;\nSELECT * FROM teams WHERE id = 379;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 379 and sociable_id = 13852\nand sa.provider = 'hubspot';\n\nSELECT * FROM crm_configurations WHERE id = 307;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 307;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1027;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 307\n and id IN (144750,144855,145158,155227);\n\nSELECT * FROM activities;\n\n\nselect * from activities\nwhere created_at > '2025-07-01 00:00:00'\n# and created_at < '2025-08-01 00:00:00'\nand type not in ('email-outbound', 'email-inbound')\nand account_id is null\nand contact_id is null\nand lead_id is null\nand opportunity_id is not null\n;\nSELECT * FROM activities WHERE id IN (25344155, 25344296, 25501909, 28692187);\nSELECT * FROM crm_configurations WHERE id in (335,301,200);\n\nselect * from crm_fields where crm_configuration_id = 230 and crm_provider_id = 'Age2__c';\n\nSELECT * FROM teams WHERE name LIKE '%Resights%';\nselect * from crm_fields where crm_configuration_id = 1 and object_type = 'opportunity';\n\nselect * from crm_configurations where provider = 'bullhorn'; # 344\nselect * from teams where id IN (442);\n\nselect * from activities\nwhere crm_configuration_id = 177\nand provider = 'amazon-connect'\n order by id desc;\n# and source <> 'gong';\n\nselect * from activity_providers where provider = 'amazon-connect';\n\nSELECT * FROM activities WHERE uuid_to_bin('cec1993b-a7e5-4164-b74d-d680ea51d2f2') = uuid;\n\n\nselect * from crm_configurations where store_transcript = 1;\nSELECT * FROM teams WHERE id IN (80);\n\n# *************************************************************************************************\nSELECT * FROM teams WHERE name LIKE '%Sedna%'; # 277, 213, 12594\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 277\nand sa.provider = 'salesforce';\n\nselect * from activities where crm_configuration_id = 213 and account_id = 2511502;\n\nselect * from crm_configurations where id = 213;\n\nSELECT * FROM activities WHERE uuid_to_bin('35aa790a-8569-4544-8268-66f9a4a26804') = uuid; # 33981604\nSELECT * FROM participants WHERE activity_id = 33981604;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 337 and object_type = 'task';\n\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 431\nand sa.provider = 'salesforce';\nSELECT * FROM activities WHERE uuid_to_bin('b5476c7d-19a8-491b-869d-676ea1e857b6') = uuid; # 33997223\nselect * from activity_summary_logs where activity_id = 33997223;\nselect * from activity_notes where activity_id = 33997223;\n\n# ***********************************\nSELECT * FROM teams WHERE name LIKE '%Abode%';\n\n\nselect * from features;\nselect * from teams t\nwhere t.status = 'active'\nand id NOT IN (select team_id from team_features where feature_id = 9)\n;\n\n\nselect * from playbook_layouts where playbook_id = 1725;\nSELECT * FROM activities WHERE uuid_to_bin('65cc283c-4849-49e6-927f-4c281c8fea19') = uuid; # 34297473\nselect * from teams where id = 318;\nselect * from crm_configurations where team_id = 318;\nselect * from playbooks where team_id = 318;\nSELECT * FROM crm_layouts where crm_configuration_id = 381;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1259;\nSELECT * FROM crm_fields WHERE id IN (192938,192936,192939);\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1266;\nSELECT * FROM crm_fields WHERE id IN (192980,192991,192997,192998,193064,193067);\n\nSELECT * FROM activities WHERE uuid_to_bin('a902289b-285c-48eb-9cc2-6ad6c5d938f5') = uuid; # 34297533\n\n\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 927;\nSELECT * FROM crm_fields WHERE id IN (131668,131669,131670,131671,131676,131797);\n\nSELECT * FROM teams WHERE name LIKE '%Peripass%'; # 351, 281, 12124\nselect * from crm_layouts where crm_configuration_id = 281;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 927;\nselect * from crm_fields where crm_configuration_id = 281 and id in (131668,131669,131670,131671,131676,131797);\nselect * from opportunities where crm_configuration_id = 281;\n\nSELECT * FROM activities WHERE id IN (34211315, 34130075);\nSELECT * FROM crm_field_data WHERE object_id IN (34211315, 34130075);\n\nselect cf.crm_configuration_id, cle.crm_layout_id, cle.id, cf.id from crm_field_data cfd\njoin crm_layout_entities cle on cle.id = cfd.crm_layout_entity_id\njoin crm_fields cf on cle.crm_field_id = cf.id\nwhere cf.deleted_at IS NOT NULL\nGROUP BY cle.id, cf.id;\n\nselect * from crm_layouts where id IN (355);\nselect u.email, t.crm_id, t.* from teams t\njoin users u on u.id = t.owner_id\nwhere crm_id IN (97);\n\nSELECT * FROM crm_fields WHERE id = 96492;\n\nselect * from permissions;\nselect * from permission_role where permission_id = 247;\nselect * from roles;\n\nselect * from migrations;\n# *****************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('291e3c21-11cc-4728-aee7-6e4bedf86d72') = uuid; # 34262174\nSELECT * FROM crm_configurations WHERE id = 301;\nSELECT * FROM teams WHERE id = 343;\nselect * from social_accounts sa\njoin users u on sa.sociable_id = u.id\nwhere u.team_id = 343\nand sa.provider = 'hubspot';\n\nselect * from participants where activity_id = 34262174;\n\nselect * from contacts where crm_configuration_id = 301 and id = 6976326;\nselect * from accounts where crm_configuration_id = 301 and id IN (4647626, 4815829); # 30761335403\n\nselect * from activity_summary_logs where activity_id = 34262174;\n\nselect * from users where status = 1 AND timezone = 'EST';\n\n# ****************************************************************************\nSELECT * FROM users WHERE id = 13869;\nSELECT * FROM crm_configurations WHERE id = 320;\nSELECT * FROM teams WHERE id = 401;\n\nSELECT * FROM activities WHERE uuid_to_bin('2228c16f-10be-48d5-90d4-67385219dc01') = uuid; # 29670601\n\nSELECT * FROM accounts WHERE id = 7761483;\nSELECT * FROM opportunities WHERE id = 6051814;\n\nSELECT * FROM teams WHERE name LIKE '%Seedlegals%';\n\n;select * from opportunities where updated_at > '2025-10-11' AND crm_provider_id = '34713761166';\n\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 177;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 577;\nSELECT * FROM crm_fields WHERE id IN (68458,68459,68480,68497,68524,68530,68554,68618,68662,68781,68810,68898,68981,69049,97467);\n\nSELECT t.id, crm.id, t.name, crm.sync_objects, crm.provider, crm.last_synced_at FROM crm_configurations crm join teams t on t.crm_id = crm.id\nwhere t.status = 'active' AND crm.provider = 'hubspot' AND crm.last_synced_at < '2025-10-22 00:00:00';\n\nSELECT * FROM activities WHERE uuid_to_bin('fa09449f-cba9-496a-b8f3-865cd3c72351') = uuid;\nSELECT * FROM crm_configurations where id = 184;\nSELECT * FROM teams WHERE id = 246;\nSELECT * FROM social_accounts WHERE sociable_id = 9259 and provider = 'hubspot';\n\nSELECT * FROM users WHERE email LIKE '%rhian.old@bud.co.uk%'; # 17700\nSELECT * FROM teams WHERE id = 551;\n\nSELECT * FROM crm_configurations WHERE id = 471;\nSELECT * FROM activities WHERE crm_configuration_id = 471 and crm_provider_id IS NOT NULL;\nSELECT * FROM crm_fields WHERE crm_configuration_id = 471;\nSELECT * FROM crm_fields WHERE id = 307260;\nSELECT * FROM crm_field_values WHERE crm_field_id = 307260;\n\nselect * from crm_layouts where crm_configuration_id = 471;\n\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1547;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1548;\n\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 = 551 and sa.provider = 'hubspot';\n\nSELECT * FROM teams WHERE name LIKE '%$PCS%';\n\n# ********************************************************************************************************\nselect * from crm_configurations crm\njoin teams t on t.crm_id = crm.id\nwhere t.status = 'active'\nand crm.provider = 'hubspot';\n\n# $slug = 'HUBSPOT_WEBHOOK_SYNC';\n# $team = Jiminny\\Models\\Team::find(2);\n# $feature = Feature::query()->where('slug', $slug)->first();\n# TeamFeature::query()->create(['feature_id' => $feature->getId(),'team_id' => $team->getId()]);\n\n# hubspot_webhook_metrics\n\nselect * from crm_configurations where id = 331; # 416\nSELECT * FROM teams WHERE id = 416;\nSELECT * FROM opportunities WHERE team_id = 190;\n\nSELECT * FROM teams WHERE name LIKE '%Lead Forensics%';\nSELECT sa.id,\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 = 190 and sa.provider = 'hubspot';\n\n\n\nSELECT * FROM teams WHERE name LIKE '%Rapaport%'; # 431, 337\nSELECT * FROM teams where id = 431;\nSELECT * FROM crm_configurations where team_id = 431;\nSELECT * FROM activity_providers where team_id = 431;\nSELECT * FROM activities where crm_configuration_id = 337 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\nSELECT sa.id,\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 = 431 and sa.provider = 'salesforce';\n\nSELECT * FROM teams WHERE name LIKE '%BiP%'; # 401, 320\nSELECT * FROM teams where id = 401;\nSELECT * FROM crm_configurations where team_id = 401;\nSELECT * FROM activity_providers where team_id = 401;\nSELECT * FROM activities where crm_configuration_id = 320 and type IN ('softphone', 'softphone-outbound')\nand provider NOT IN ('hubspot', 'aircall')\n# and telephony_provider_id = '019c1131-a22f-4792-b9ea-20adf6a02ed0'\norder by id desc;\nSELECT sa.id,\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 = 401 and sa.provider = 'salesforce';\n\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 307; # 379 - Story Terrace Inc , portalId: 3921157\nSELECT * FROM contacts WHERE team_id = 379 and updated_at > '2026-01-31 11:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 379 and updated_at > '2026-02-01 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 379 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\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 = 379 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 485; # 563 - LATUS Group (ad94d501-5d09-44fd-878f-ca3a9f8865c3) , portalId: 3904501\nSELECT * FROM opportunities WHERE team_id = 563 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 563 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 338; # 432 - Formalize , portalId: 9214205\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 = 432 and sa.provider = 'hubspot';\nSELECT * FROM opportunities WHERE team_id = 432 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 432 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 436; # 519 - Moxso , portalId: 25531989\nSELECT * FROM opportunities WHERE team_id = 519 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 519 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 96; # 119 - Nourish Care , portalId: 26617984\nSELECT * FROM opportunities WHERE team_id = 119 and updated_at > '2026-02-02 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 119 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 331; # 416 - The National College , portalId: 7213852\nSELECT * FROM opportunities WHERE team_id = 416 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 416 and updated_at > '2026-02-04 11:00:00' order by updated_at desc;\n\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 308; # 380 - Foodles , portalId: 7723616\nSELECT * FROM opportunities WHERE team_id = 380 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 380 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 379; # 471 - imat-uve , portalId: 9177354\nSELECT * FROM opportunities WHERE team_id = 471 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 471 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 465; # 545 - Spotler , portalId: 144759271\nSELECT * FROM opportunities WHERE team_id = 545 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 545 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 455; # 537 - indevis , portalId: 25666868\nSELECT * FROM opportunities WHERE team_id = 537 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 537 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 200; # 265 - Jobadder , portalId: 6426676\nSELECT * FROM opportunities WHERE team_id = 265 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 265 and updated_at > '2026-02-06 10:30:00' order by updated_at desc;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 335; # 429 - Eletive , portalId: 6110563\nSELECT * FROM opportunities WHERE team_id = 429 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 429 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 363; # 456 - Global Group , portalId: 8901981\nSELECT * FROM opportunities WHERE team_id = 456 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 456 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 297; # 369 - Unbiased , portalId: 9229005\nSELECT * FROM opportunities WHERE team_id = 369 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 369 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 353; # 449 - Fuuse , portalId: 25781745\nSELECT * FROM opportunities WHERE team_id = 449 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 449 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 487; # 566 - Nimbus , portalId: 39982590\nSELECT * FROM opportunities WHERE team_id = 566 and updated_at > '2026-02-04 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 566 and updated_at > '2026-02-09 10:30:00' order by updated_at desc;\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 487;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1630;\nselect * from crm_fields where crm_configuration_id = 487 and\n(uuid_to_bin('4c6b2971-64d4-45b8-b377-427be758b5a5') = uuid or uuid_to_bin('59e368d8-65a0-4b77-b611-db37c99fbe68') = uuid);\nSELECT * FROM crm_field_values WHERE crm_field_id = 375177;\n# ********************************************************************\nSELECT * FROM crm_configurations where id = 420; # 506 - voiio , portalId: 145629154\nSELECT * FROM opportunities WHERE team_id = 506 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 506 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 479; # 558 - Momice , portalId: 535962\nSELECT * FROM opportunities WHERE team_id = 558 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 558 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 59; # 80 - Storyclash GmbH , portalId: 4268479\nSELECT * FROM opportunities WHERE team_id = 80 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 80 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 175; # 203 - Team iAM , portalId: 5534732\nSELECT * FROM opportunities WHERE team_id = 203 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 203 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\nSELECT * FROM crm_configurations where id = 368; # 460 - OneTouch Health , portalId: 5534732183355\nSELECT * FROM opportunities WHERE team_id = 460 and updated_at > '2026-02-10 00:00:00' order by updated_at desc;\nSELECT * FROM opportunities WHERE team_id = 460 and updated_at > '2026-02-10 15:00:00' order by updated_at desc;\n\n\n\nselect * from users where id = 29643;\nSELECT * FROM crm_field_values WHERE crm_field_id = 375177;\n# ********************************************************************\nSELECT * FROM teams WHERE name LIKE '%Buynomics%'; # 462, 482, 14910\nSELECT * FROM activities WHERE crm_configuration_id = 482\nand type NOT IN ('email-inbound', 'email-outbound')\n# and description like '%The call focused on understanding Welch%'\norder by id desc;\n\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 = 462 and sa.provider = 'salesforce';\n\nselect * from contacts where crm_configuration_id = 482 and name = 'Cyndall Hill'; # 15504749\nselect * from contacts where id = 10891096; # 482\nSELECT * FROM activities WHERE crm_configuration_id = 482\nand type NOT IN ('email-inbound', 'email-outbound')\nand contact_id = 15504749\norder by id desc;\n\nselect * from activities where id = 36793003; # 96cc7bc1-8622-4d27-92f4-baf664fc1a56, 00UOf00000PDdOXMA1\nselect * from transcription where id = 7646782;\nselect * from ai_prompts where transcription_id = 7646782;\n\n# ********************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('7a8471a3-847e-4822-802b-ddf426bbc252') = uuid; # 37370018\nSELECT * FROM activity_summary_logs WHERE activity_id = 37370018;\nSELECT * FROM teams WHERE id = 555;\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 = 555 and sa.provider = 'hubspot';\n\n# ********************************************************************\nSELECT * FROM activities WHERE uuid_to_bin('7c17b8aa-09df-4f85-a0f7-51f47afd712d') = uuid; # 37395250\nSELECT * FROM activities WHERE uuid_to_bin('14d60388-260d-494b-aa0d-63fdb1c78026') = uuid; # 37395250\n\nSELECT a.* FROM activities a JOIN crm_configurations c on c.id = a.crm_configuration_id\nwhere a.type IN ('softphone', 'softphone-outbound') and c.provider = 'hubspot'\nand a.provider NOT IN ('hubspot')\n# and a.provider IN ('salesloft')\n# and c.id NOT IN (70)\n# and a.duration > 30\n# and actual_start_time > '2026-02-05 00:00:00'\norder by a.id desc;\n\nSELECT * FROM activities WHERE id = 37549787;\nSELECT * FROM crm_profiles WHERE user_id = 17613;\n\nSELECT * FROM crm_configurations WHERE id = 70;\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 = 93 and sa.provider = 'hubspot';\n\nSELECT asf.activity_search_id, asf.id, asf.value\nFROM activity_search_filters asf\nWHERE asf.filter = 'group_id'\nAND asf.value IN (\n SELECT CONCAT(\n HEX(SUBSTR(uuid, 5, 4)), '-',\n HEX(SUBSTR(uuid, 3, 2)), '-',\n HEX(SUBSTR(uuid, 1, 2)), '-',\n HEX(SUBSTR(uuid, 9, 2)), '-',\n HEX(SUBSTR(uuid, 11))\n )\n FROM groups\n WHERE deleted_at IS NOT NULL\n);\n\nSELECT * FROM crm_configurations WHERE id = 373; # KPSBremen.de 465 # - no social account\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 = 465 and sa.provider = 'hubspot';\n\nselect * from crm_configurations where id = 494;\n\nSELECT * FROM teams WHERE name LIKE '%splose%'; # 572, 495, 18708\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 = 572 and sa.provider = 'pipedrive';\n\nselect * from opportunities where team_id = 572\n# and name like '%Onebright%'\n# and is_closed = 1 and is_won = 0\n order by id desc;\n\n\nselect * from users where deleted_at is null and status = 2;\n\nselect * from contacts where id = 17900517;\nselect * from accounts where id = 10109838;\nselect * from opportunities where id = 6955880;\n\nselect * from opportunity_contacts where opportunity_id = 6955880;\nselect * from opportunity_contacts where contact_id = 17900517;\n\nselect * from contact_roles cr join crm_configurations crm on cr.crm_configuration_id = crm.id\nwhere crm.provider != 'salesforce';\n\nSELECT * FROM activities WHERE uuid_to_bin('adcb8331-5988-4353-834e-383a355abba2') = uuid; # 38056424, crm 104659682404\nselect * from teams where id = 456;\nSELECT * FROM crm_configurations WHERE id = 363;\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 = 456 and sa.provider = 'hubspot';\n\nselect * from crm_layouts where crm_configuration_id = 363;\nSELECT * FROM crm_layout_entities WHERE crm_layout_id IN (1203, 1204, 1635);\nSELECT * FROM crm_fields WHERE id IN (181536, 181538, 213455);\n\nSELECT * FROM teams WHERE name LIKE '%Electric%'; # 342, 272, 12767\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 = 342 and sa.provider = 'pipedrive';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 and name like 'NORTHUMBRIA POL%'; # and updated_at > '2025-07-01 00:00:00';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 order by remotely_created_at asc; # and updated_at > '2025-07-01 00:00:00';\nSELECT * FROM opportunities WHERE crm_configuration_id = 272 and updated_at > '2026-01-01 00:00:00';\nSELECT * FROM crm_fields WHERE crm_configuration_id = 272 and object_type = 'opportunity';\nSELECT * FROM crm_field_values WHERE crm_field_id = 127164;\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 = 342 and sa.provider = 'pipedrive';\n\nSELECT * FROM teams WHERE id = 472;\nSELECT * FROM crm_configurations WHERE id = 380;\nselect * from activities where id = 38285673; # 38285673\nSELECT * FROM users WHERE id = 16942;\nSELECT * FROM groups WHERE id = 1964;\nSELECT * FROM playbooks WHERE id = 2033;\n\nselect * from teams where created_at > '2026-03-09';\nSELECT * FROM crm_layouts WHERE crm_configuration_id = 499; # 1065\nSELECT * FROM crm_layout_entities WHERE crm_layout_id = 1678;\n\nSELECT * FROM teams WHERE id = 575;\nselect * from opportunities where team_id = 575;\n\nSELECT * FROM activities WHERE uuid_to_bin('96b1261f-2357-49f9-ab38-23ce12008ea0') = uuid;\n\nselect * from contacts c\nwhere c.crm_configuration_id = 370 order by c.updated_at desc;\n\nSELECT * FROM participants where activity_id = 38833541;\nSELECT * FROM participants where activity_id = 39216301;\nSELECT * FROM activity_summary_logs where activity_id = 39216301;\nSELECT * FROM activities WHERE uuid_to_bin('c7d99fbe-1fb1-41f2-8f4d-52e2bf70e1e9') = uuid; # 38833541, crm 478116564181\nSELECT * FROM activities WHERE uuid_to_bin('2e6ff4d3-9faa-447a-a8c1-9acde4d885ae') = uuid; # 39216301, crm 480171536586\nselect * from crm_profiles where crm_configuration_id = 319 and crm_provider_id = 525785080;\nselect * from opportunities where crm_configuration_id = 319 and crm_provider_id = 410150124747;\nselect * from accounts where crm_configuration_id = 319 and crm_provider_id = 47150650569;\nselect * from contacts where crm_configuration_id = 319 and crm_provider_id IN ('665587441856', '742723347700');\n# owner 13236 525785080\n# contact 1 16779180 665587441856 - activity - Alex Howes alex@supportroom.com created 2026-01-26\n# contact 2 19247563 742723347700 - ash@supportroom.com 2026-03-24\n# company 4176133 47150650569\n# deal 7100953 410150124747\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 = 400 and sa.provider = 'hubspot';\n\nselect * from features;\nselect * from team_features where feature_id = 40;\n\nselect * from teams where id = 556; # owner: 18101, crm: 477\nselect * from crm_configurations where id = 477;\nSELECT * FROM users WHERE id = 18101;\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 = 556 and sa.provider = 'integration-app';\n\nselect * from opportunities where id = 7594349;\nselect * from opportunity_stages where opportunity_id = 7594349 order by created_at desc;\nselect * from business_processes where id = 6024;\nselect * from business_process_stages where stage_id = 16352;\nselect * from business_process_stages where business_process_id = 6024;\nselect * from stages where team_id = 459;\nselect * from teams where id = 459;\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 = 459 and sa.provider = 'hubspot';\n\nSELECT os.stage_id, s.crm_provider_id, s.name, COUNT(*) as cnt\nFROM opportunity_stages os\nJOIN stages s ON s.id = os.stage_id\nWHERE os.opportunity_id = 7594349\nGROUP BY os.stage_id, s.crm_provider_id, s.name\nORDER BY cnt DESC;\n\nSELECT s.id, s.crm_provider_id, s.name, s.team_id, s.crm_configuration_id\nFROM stages s\nJOIN business_process_stages bps ON bps.stage_id = s.id\nWHERE bps.business_process_id = 6024\nAND s.crm_provider_id = 'contractsent';\n\nselect * from stages where id IN (16352,20612,18281,7344,16378,16309,5036,15223,14535,6293,12098,11607)\n\nSELECT * FROM teams WHERE name LIKE '%Pulsar Group%'; # 472, 380, 15138, raza.gilani@vuelio.com\nselect * from playbooks where team_id = 472; # event 226147\nSELECT * FROM playbook_categories WHERE playbook_id = 2288;\nSELECT * FROM crm_fields WHERE id = 226147;\nSELECT * FROM crm_field_values WHERE crm_field_id = 226147;\n\nSELECT * FROM crm_configurations WHERE id = 380;\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 = 472 and sa.provider = 'salesforce';\n\nselect * from activities where id = 58081273;\n\nselect * from automated_report_results where media_type = 'pdf' and status = 2;\n\nSELECT * FROM users WHERE name LIKE '%Neil Hoyle%'; # 17651\nSELECT * FROM social_accounts WHERE sociable_id = 17651;\n\nSELECT * FROM activities WHERE uuid_to_bin('975c6830-7d49-4c1e-b2e9-ac80c10a738a') = uuid;\nSELECT * FROM opportunities WHERE id IN (7842553, 6211727);\nSELECT * FROM contacts WHERE id IN (10202724, 6211727);\nSELECT * FROM opportunity_stages WHERE opportunity_id = 7842553;\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 = 519 and sa.provider = 'hubspot';\n\nselect * from crm_configurations where id = 436;\nselect * from crm_profiles where crm_configuration_id = 436; # 76091797 -> 16612\n\nselect * from contact_roles where contact_id = 10202724;\n\nselect * from stages where team_id = 519; # 18778\n18775\n\nSELECT\n id,\n crm_provider_id,\n stage_id,\n is_closed,\n is_won,\n stage_updated_at,\n updated_at\nFROM opportunities\nWHERE id IN (6211727, 7842553);\n\nSELECT * FROM opportunity_contacts\nWHERE opportunity_id = 6211727 AND contact_id = 10202724;\n\nSELECT id, name, stage_id, is_closed, is_won, updated_at, remotely_created_at\nFROM opportunities\nWHERE account_id = 8179134\nORDER BY updated_at DESC;\n\n\nselect * from text_relays where created_at > '2026-01-01';\nAND id IN (691, 692);\n\nselect * from teams;\n\n# ***************\nSELECT DISTINCT u.id, u.email, u.name, u.softphone_number, COUNT(a.id) as sms_count\nFROM users u\nINNER JOIN activities a ON u.id = a.user_id\nWHERE a.type LIKE 'sms%'\nAND a.created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)\nGROUP BY u.id, u.email, u.name, u.softphone_number\nORDER BY sms_count DESC;\n\nSELECT DISTINCT u.id, u.email, u.name, u.team_id, t.name as team_name,\n t.twilio_sms_sid, t.twilio_messaging_sid\nFROM users u\nINNER JOIN teams t ON u.team_id = t.id\nWHERE (t.twilio_sms_sid IS NOT NULL OR t.twilio_messaging_sid IS NOT NULL)\nAND u.status = 1\nORDER BY t.name, u.email;\n\nSELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, salesforce-admin@tourlane.com\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 = 187 and sa.provider = 'salesforce';\n\nselect * from activities where id = 31264367;\nselect * from contacts where id = 6331639;\nselect * from accounts where id = 4156632;\nselect * from opportunities where id = 4843610;\n# update `activities` set `account_id` = 4156632, `contact_id` = 6331639, `opportunity_id` = 4843610,\n# `stage_id` = 13273, `activities`.`updated_at` = 2026-05-22 07:16:17 where `id` = 31264367)\"\n\nselect * from text_relays where created_at > '2026-05-01';\n\nselect * from activities order by id desc;\n\nselect * from users where name like '%Subra%';\n\nSELECT * FROM opportunities WHERE uuid_to_bin('04a9cfad-2c87-4453-9e72-20aeb78ccf8d') = uuid;\nselect * from teams where id = 555;\nselect * from stages where team_id = 555;\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 = 100 and sa.provider = 'hubspot';","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.011968086,"top":0.047885075,"width":0.024268618,"height":0.024740623},"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}]...
|
6342989898062187878
|
2074961217668396653
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground
jiminny
Code changed:
Hide
Sync Changes
Hide This Notification
31
9
29
3
109
Previous Highlighted Error
Next Highlighted Error
SELECT * FROM team_features where team_id = 1;
SELECT * FROM teams WHERE name LIKE '%Vixio%'; # 340,270,11922
SELECT * FROM users WHERE team_id = 340; # 12015
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 340
and sa.provider = 'salesforce';
# and sa.provider = 'salesloft';
select * from crm_fields where crm_configuration_id = 270 and object_type = 'event';
# 125558 - Event Type - Event_Type__c
# 125552 - Event Status - Event_Status__c
SELECT * FROM sidekick_settings WHERE team_id = 340;
SELECT * FROM crm_field_values WHERE crm_field_id in (125552);
select * from activities where crm_configuration_id = 270
and type = 'conference' and crm_provider_id IS NOT NULL
and actual_start_time > '2024-09-16 09:00:00' order by scheduled_start_time;
SELECT * FROM activities WHERE id = 20871677;
SELECT * FROM crm_field_data WHERE activity_id = 20871677;
select * from crm_layouts where crm_configuration_id = 270;
select * from crm_layout_entities where crm_layout_id in (886,887);
SELECT * FROM crm_configurations WHERE id = 270;
select * from playbooks where team_id = 340; # 1514
select * from groups where team_id = 340;
SELECT * FROM crm_fields WHERE id IN (125393, 125401);
select g.name as 'team name', p.name as 'playbook name', f.label as 'activity type field' from groups g
join playbooks p on g.playbook_id = p.id
join crm_fields f on p.activity_field_id = f.id
where g.team_id = 340;
SELECT * FROM activities WHERE uuid_to_bin('0c180357-67d2-419e-a8c3-b832a3490770') = uuid; # 20448716
select * from crm_field_data where object_id = 20448716;
select * from activities where crm_configuration_id = 270 and provider = 'salesloft' order by id desc;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%CybSafe%'; # 343,273,12008
select * from opportunities where team_id = 343;
select * from opportunities where team_id = 343 and crm_provider_id = '18099102526';
select * from opportunities where team_id = 343 and account_id = 945217482;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
select * from accounts where team_id = 343 order by name asc;
select * from stages where crm_configuration_id = 273 and type = 'opportunity';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Voyado%'; # 353,283,12143
SELECT * FROM activities WHERE crm_configuration_id = 283 and account_id = 3777844 order by id desc;
SELECT * FROM accounts WHERE team_id = 353 AND name LIKE '%Salesloft%';
SELECT * FROM activities WHERE id = 20717903;
select * from participants where activity_id IN (20929172,20928605,20928468,20926272,20926271,20926270,20926269,20916499,20916454,20916436,20916435,20900015,20900014,20900013,20897312,20897243,20897241,20897237,20897232,20897229,20893648,20893231,20893230,20893229,20893228,20889784,20885039,20885038,20885037,20885036,20885035,20882728,20882708,20882703,20882702,20869828,20869811,20869806,20869801,20869799,20869798,20869796,20869795,20869794,20869761,20869760,20869759,20868688,20868687,20850340,20847195,20841710,20833967,20827021,20825307,20825305,20825297,20824615,20824400,20823927,20821760,20795588,20794233,20794057,20793710,20785811,20781789,20781394,20781307,20762651,20758453,20758282,20757323,20756643,20756636,20756629,20756627,20756606,20756605,20756604,20756603,20756602,20756600,20756599,20756598,20756595,20756594,20756589,20756587,20756577,20756573,20748918,20748386,20748385,20748384,20748383,20748382,20748381,20748380,20748379,20748377,20748375,20748373,20743301,20717905,20717904,20717903,20717901,20717899);
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 353
and sa.provider = 'salesforce';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%modern world business solutions%'; # 345,275,12016, [EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('3921d399-3fef-4609-a291-b0097a166d43') = uuid;
# id: 20940638, user: 12022, contact: 5305871
SELECT * FROM activity_summary_logs WHERE activity_id = 20940638;
select * from contacts where team_id = 345 and crm_provider_id = '30891432415' order by name asc; # 5305871
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 345
and sa.provider = 'hubspot';
select * from users where team_id = 345 and id = 12022;
SELECT * FROM crm_profiles WHERE user_id = 12022;
SELECT * FROM participants WHERE activity_id = 20940638;
SELECT * FROM users u
JOIN crm_profiles cp ON u.id = cp.user_id
WHERE u.team_id = 345;
select * from contacts where team_id = 345 and crm_provider_id = '30880813535' order by name desc; # 5305871
select * from team_features where team_id = 345;
SELECT * FROM activities WHERE uuid_to_bin('11701e2d-2f82-4dab-a616-1db4fad238df') = uuid; # 21115197
SELECT * FROM participants WHERE activity_id = 20897406;
SELECT * FROM activities WHERE uuid_to_bin('63ba55cd-1abc-447d-83da-0137000005b7') = uuid; # 20953912
SELECT * FROM activities WHERE crm_configuration_id = 275 and provider = 'ringcentral' and title like '%1252629100%';
SELECT * FROM activities WHERE id = 20946641;
SELECT * FROM crm_profiles WHERE user_id = 10211;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120,97,10984, [EMAIL]
SELECT * FROM opportunities WHERE crm_configuration_id = 97 and crm_provider_id = '006N1000006c5PpIAI';
select * from stages where crm_configuration_id = 97 and type = 'opportunity';
select * from opportunities where team_id = 120;
select * from crm_configurations crm join teams t on crm.id = t.crm_id
where 1=1
AND t.current_billing_plan IS NOT NULL
AND crm.auto_sync_activity = 0
and crm.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Exclaimer%'; # 270,205,10053,[EMAIL]
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 270
and sa.provider = 'salesforce';
SELECT * FROM activities WHERE uuid_to_bin('b54df794-2a9a-4957-8d80-09a600ead5f8') = uuid; # 21637956
SELECT * FROM crm_profiles WHERE user_id = 11446;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Cygnetise%'; # 372,300,12554, [EMAIL]
select * from playbooks where team_id = 372;
select * from crm_fields where crm_configuration_id = 300 and object_type = 'event'; # 141340
SELECT * FROM crm_field_values WHERE crm_field_id = 141340;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 372
and sa.provider = 'salesforce';
select * from crm_profiles where crm_configuration_id = 300;
SELECT * FROM crm_configurations WHERE team_id = 372;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Planday%'; # 291,242,11501,[EMAIL]
SELECT * FROM opportunities WHERE team_id = 291 and crm_provider_id = '006bG000005DO86QAG'; # 3207756
select * from crm_field_data where object_id = 3207756;
SELECT * FROM crm_fields WHERE id = 111834;
select f.id, f.crm_provider_id AS field_name, f.label, fd.object_id AS dealId, fd.value
FROM crm_fields f
JOIN crm_field_data fd ON f.id = fd.crm_field_id
WHERE f.crm_configuration_id = 242
AND f.object_type = 'opportunity'
AND fd.object_id IN (3207756)
ORDER BY fd.object_id, fd.updated_at;
SELECT * FROM crm_configurations WHERE auto_connect = 1;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150,[EMAIL]
select * from group_deal_risk_types drgt join groups g on drgt.group_id = g.id
where g.team_id = 187;
select * from `groups` where team_id = 187;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 187
and sa.provider = 'salesforce';
# Destination - 98870 - Destination__c
# Stage - 79014 - StageName
# Land Arrangement - 98856 - Land_Arrangement__c
# Flight - 98848 - Flight__c
# Last activity date - 98812 - LastActivityDate
# Last modified date - 98809 - LastModifiedDate
# Last inbound mail timestamp - 99151 - Last_Inbound_Mail_Timestamp__c
# next call - 98864 - Next_Call__c
select * from crm_fields where crm_configuration_id = 209 and object_type = 'opportunity';
SELECT * FROM crm_layouts WHERE crm_configuration_id = 209;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;
select * from opportunities where team_id = 187 and name LIKE'%Muriel Sal%';
select * from opportunities where team_id = 187 and user_id = 9951 and is_closed = 0;
select * from activities where opportunity_id = 3538248;
SELECT * FROM crm_profiles WHERE user_id = 8150;
select * from deal_risks where opportunity_id = 3538248;
select * from teams where crm_id IS NULL;
SELECT opp.id AS opportunity_id,
u.group_id AS group_id,
MAX(
CASE
WHEN a.type IN ("sms-inbound", "sms-outbound") THEN a.created_at
ELSE a.actual_end_time
END) as last_date
FROM opportunities opp
left join activities a on a.opportunity_id = opp.id
inner join users u on opp.user_id = u.id
where opp.user_id IN (9951)
AND opp.is_closed = 0
and a.status IN ('completed', 'received', 'delivered') OR a.status IS NULL
group by opp.id;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Cybsafe%'; # 343,301,12008,[EMAIL]
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
SELECT * FROM crm_profiles WHERE crm_configuration_id = 301;
SELECT * FROM contacts WHERE id = 6612363;
SELECT * FROM accounts WHERE id = 4235676;
SELECT * FROM opportunities WHERE crm_configuration_id = 301 and crm_provider_id = 32983784868;
select * from opportunity_stages where opportunity_id = 4503759;
# SELECT * FROM opportunities WHERE id = 4569937;
select * from activities where crm_configuration_id = 301;
SELECT * FROM activities WHERE uuid_to_bin('d3b2b28b-c3d0-4c2d-8ed0-eef42855278a') = uuid; # 26330370
SELECT * FROM participants WHERE activity_id = 26330370;
SELECT * FROM teams WHERE id = 375;
select * from playbooks where team_id = 375;
select * from stages where crm_configuration_id = 301 and type = 'opportunity';
select * from teams;
select * from contact_roles;
SELECT * FROM opportunities WHERE team_id = 343 and user_id = 12871 and close_date >= '2024-11-01';
select * from users u join crm_profiles cp on cp.user_id = u.id where u.team_id = 343;
SELECT * FROM crm_field_data WHERE object_id = 3771706;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 343
and sa.provider = 'hubspot';
SELECT * FROM crm_fields WHERE crm_configuration_id = 301 and object_type = 'opportunity'
and crm_provider_id LIKE "%traffic_light%";
SELECT * FROM crm_field_values WHERE crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531);
SELECT fd.* FROM opportunities o
JOIN crm_field_data fd ON o.id = fd.object_id
WHERE o.team_id = 343
# and o.user_id IS NOT NULL
and fd.crm_field_id IN (144020,144048,144111,144113,144126,144481,144508,144531)
and fd.value != ''
order by value desc
# group by o.id
;
SELECT * FROM opportunities WHERE id = 3769843;
SELECT * FROM teams WHERE name LIKE '%Tour%'; # 187,209,8150, [EMAIL]
SELECT * FROM crm_layouts WHERE crm_configuration_id = 209;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 682;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Funding Circle%'; # 220,177,8603,[EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('7a40e99b-3b37-4bb1-b983-325b81801c01') = uuid; # 23139839
SELECT * FROM opportunities WHERE id = 3855992;
SELECT * FROM users WHERE name LIKE '%Angus Pollard%'; # 8988
SELECT * FROM teams WHERE name LIKE '%Story Terrace%'; # 379, 307, 12894
SELECT * FROM crm_fields WHERE crm_configuration_id = 307 and object_type != 'opportunity';
select * from contacts where team_id = 379 and name like '%bebro%'; # 5874411, crm: 77229348507
SELECT * FROM crm_field_data WHERE object_id = 5874411;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 379
and sa.provider = 'hubspot';
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%mentio%'; # 117, 94, 6371, [EMAIL]
SELECT * FROM activities WHERE uuid_to_bin('82939311-1af0-4506-8546-21e8d1fdf2c1') = uuid;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Tourlane%'; # 187, 209, 8150, [EMAIL]
SELECT * FROM opportunities WHERE team_id = 187 and crm_provider_id = '006Se000008xfvNIAQ'; # 3537793
select * from generic_ai_prompts where subject_id = 3537793;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lunio%'; # 120, 97, 10984, [EMAIL]
SELECT * FROM crm_configurations WHERE id = 97;
SELECT * FROM crm_layouts WHERE crm_configuration_id = 97;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 355;
SELECT * FROM crm_fields WHERE id = 32682;
select cfd.value, o.* from opportunities o
join crm_field_data cfd on o.id = cfd.object_id and cfd.crm_field_id = 32682
where team_id = 120
and cfd.value != ''
;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 120
and sa.provider = 'salesforce';
select * from opportunities where team_id = 120 and crm_provider_id = '006N1000007X8MAIA0';
SELECT * FROM crm_field_data WHERE object_id = 2313439;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE id = 410;
SELECT * FROM teams WHERE name LIKE '%Local Business Oxford%';
select * from scorecards where team_id = 410;
select * from scorecard_rules;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Funding%'; # 220, 177, 8603, [EMAIL]
select * from activities a
join opportunities o on a.opportunity_id = o.id
join users u on o.user_id = u.id
where a.crm_configuration_id = 177 and a.type LIKE '%email-out%'
# and a.actual_end_time > '2024-12-16 00:00:00'
# and o.remotely_created_at > '2024-12-01 00:00:00'
# and u.group_id = 1014
and u.id = 9021
order by a.id desc;
SELECT * FROM opportunities WHERE id in (3981384,4017346);
SELECT * FROM users WHERE team_id = 220 and id IN (8775, 11435);
select * from users where id = 9021;
select * from inboxes where user_id = 9021;
select * from inbox_emails where inbox_id = 1349 and email_date > '2024-12-18 00:00:00';
select * from email_messages where team_id = 220
and orig_date > '2024-12-16 00:00:00' and orig_date < '2024-12-19 00:00:00'
and subject LIKE '%Personal%'
# and 'from' = '[EMAIL]'
;
select * from activities a
join opportunities o on a.opportunity_id = o.id
where a.user_id = 9021 and a.type LIKE '%email-out%'
and a.actual_end_time > '2024-12-18 00:00:00'
and o.user_id IS NOT NULL
and o.remotely_created_at > '2024-12-01 00:00:00'
order by a.id desc;
SELECT * FROM opportunities WHERE team_id = 220 and name LIKE '%Right Car move Limited%' and id = 3966852;
select * from activities where crm_configuration_id = 177 and type LIKE '%email%' and opportunity_id = 3966852 order by id desc;
select * from team_settings where name IN ('useCloseDate');
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Hurree%'; # 104, 81, 6175, [EMAIL]
SELECT * FROM opportunities WHERE team_id = 104 and name = 'PropOp';
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 104
and sa.provider = 'hubspot';
select * from crm_configurations where last_synced_at > '2025-01-19 01:00:00'
select * from teams where crm_id IS NULL;
select t.name as 'team', u.name as 'owner', u.email, u.phone
from teams t
join activity_providers ap on t.id = ap.team_id
join users u on t.owner_id = u.id
where 1=1
and t.status = 'active'
and ap.is_enabled = 1
# and u.status = 1
and ap.provider = 'ms-teams';
select * from crm_configurations where provider = 'bullhorn'; # 344
SELECT * FROM teams WHERE id = 442; # 14293
select * from users where team_id = 442;
select * from social_accounts sa where sa.sociable_id = 14293;
select * from invitations where team_id = 442;
# [PASSWORD_DOTS]
SELECT * FROM users WHERE email LIKE '%[EMAIL]%'; # 14022
SELECT * FROM teams WHERE id = 429;
select * from opportunities where team_id = 429 and crm_provider_id IN (16157415775, 22246219645);
select * from activities where opportunity_id in (4340436,4353519);
select * from transcription where activity_id IN (25630961,25381771);
select * from generic_ai_prompts where subject_id IN (4353519);
SELECT
a.id as activity_id,
a.opportunity_id,
a.type as activity_type,
a.language,
CONCAT(a.title, a.description) AS mail_content,
e.from AS mail_from,
e.to AS mail_to,
e.subject AS mail_subject,
e.body AS mail_body,
p.type as prompt_type,
p.status as prompt_status,
p.content AS prompt_content,
a.actual_start_time as created_at
FROM activities a
LEFT JOIN ai_prompts p ON a.transcription_id = p.transcription_id AND p.deleted_at IS NULL
LEFT JOIN email_messages e ON a.id = e.activity_id
WHERE a.actual_start_time > '2024-01-01 00:00:00'
AND a.opportunity_id IN (4353519)
AND a.status IN ('completed', 'received', 'delivered')
AND a.deleted_at IS NULL
AND a.type NOT IN ('sms-inbound', 'sms-outbound')
ORDER BY a.opportunity_id ASC, a.id ASC;
SELECT * FROM users WHERE name LIKE '%George Fierstone%'; # 14293
SELECT * FROM teams WHERE id = 442;
SELECT * FROM crm_configurations WHERE id = 344;
select * from team_features where team_id = 442;
select * from groups where team_id = 442;
select * from playbooks where team_id = 442;
select * from playbook_categories where playbook_id = 1729;
select * from crm_fields where crm_configuration_id = 344 and id = 172024;
SELECT * FROM crm_field_values WHERE crm_field_id = 172024;
select * from crm_layouts where crm_configuration_id = 344;
select * from playbook_layouts where playbook_id = 1729;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Learning%'; # 260, 221, 9444
select s.*
# , s.sent_at, u.name, a.*
from activity_summary_logs s
inner join activities a on a.id = s.activity_id
inner join users u on u.id = a.user_id
where a.crm_configuration_id = 356
and s.sent_at > date_sub(now(), interval 60 day)
order by a.actual_end_time desc;
select * from activities a
# inner join activity_summary_logs s on s.activity_id = a.id
where a.crm_configuration_id = 356 and a.actual_end_time > date_sub(now(), interval 60 day)
# and a.crm_provider_id is not null
# and provider <> 'ringcentral'
and status = 'completed'
order by a.actual_end_time desc;
select * from teams order by id desc; # 17328, 32, 17830, [EMAIL]
SELECT * FROM users;
SELECT * FROM users where team_id = 260 and status = 1; # 201 - 150 active
SELECT * FROM teams WHERE id = 260;
select * from team_settings where team_id = 260;
select * from crm_configurations where team_id = 260;
SELECT * FROM crm_layouts WHERE crm_configuration_id = 356;
SELECT * FROM crm_layout_entities WHERE crm_layout_id = 1184;
select * from accounts where crm_configuration_id = 221 order by id desc; # 7000
select * from leads where crm_configuration_id = 221 order by id desc; # 0
select * from contacts where crm_configuration_id = 221 order by id desc; # 200 000
select * from opportunities where crm_configuration_id = 221 order by id desc; # 0
select * from crm_profiles where crm_configuration_id = 221 order by id desc; # 23
select * from crm_fields where crm_configuration_id = 221;
select * from crm_field_values where crm_field_id = 5302 order by id desc;
select * from crm_layouts where crm_configuration_id = 221 order by id desc;
select * from stages where crm_configuration_id = 221 order by id desc;
select * from accounts where crm_configuration_id = 356 order by id desc; # 7000
select * from leads where crm_configuration_id = 356 order by id desc; # 0
select * from contacts where crm_configuration_id = 356 order by id desc; # 200 000
select * from opportunities where crm_configuration_id = 356 order by id desc; # 0
select * from crm_profiles where crm_configuration_id = 356 order by id desc; # 23
select * from crm_fields where crm_configuration_id = 356;
select * from crm_field_values where crm_field_id = 5302 order by id desc;
select * from crm_layouts where crm_configuration_id = 356 order by id desc;
select * from stages where crm_configuration_id = 356 order by id desc;
select * from playbooks where team_id = 260 order by id desc; # 4 (2 deleted)
select * from groups where team_id = 260 order by id desc; # 27 groups, (2 deleted)
select * from playbook_layouts where playbook_id IN (1410,1409,1276,1254); # 4
select ce.* from calendars c
join users u on c.user_id = u.id
join calendar_events ce on c.id = ce.calendar_id
where u.team_id = 260
and (ce.start_time > '2025-02-21 00:00:00')
;
# calendar events 1207
#
select * from opportunities where team_id = 260;
SELECT * FROM crm_field_data WHERE object_id = 4696496;
select * from activities where crm_configuration_id = 356 and crm_provider_id IS NOT NULL;
select * from activities where crm_configuration_id IN (221) and provider NOT IN ('ms-teams', 'uploader', 'zoom-bot')
# and type = 'conference' and status = 'scheduled' and activities.is_internal = 0
and created_at > '2024-03-01 00:00:00'
order by id desc; # 880 000, ringcentral, avaya
SELECT * FROM participants WHERE activity_id = 26371744;
# all activities 942 000 +
# conference 7385 - scheduled 984 - external 343
select * from activities where id = 26321812;
select * from participants where activity_id = 26321812;
select * from participants where activity_id in (26414510,26414514,26414516,26414604,26414653,26414655);
select * from leads where id in (720428,689175,731546,645866,621037);
select * from users where id = 13841;
select * from opportunities where user_id = 9541;
select * from stages where id = 15900;
select * from accounts where
# id IN (4160055,5053725,4965303,4896434)
id in (4584518,3249934,3218025,3891133,3399450,4172999,4485161,3101785,4587203,3070816,2870343,2870341,3563940,4550846,3424464,3249963,2870342)
;
select * from activities where id = 26654935;
SELECT * FROM opportunities WHERE id = 4803458;
SELECT * FROM opportunities where team_id = 260 and user_id = 13841 AND stage_id = 15900;
SELECT id, uuid, provider, type, lead_id, account_id, contact_id, opportunity_id, stage_id, status, recording_state, title, actual_start_time, actual_end_time
FROM activities WHERE user_id = 13841 AND opportunity_id IN (4729783, 4731717, 4731726, 4732064, 4732849, 4803458, 4813213);
SELECT DISTINCT
o.id, o.stage_id, s.name, a.title,
a.*
FROM activities a
# INNER JOIN tracks t ON a.id = t.activity_id
INNER JOIN users u ON a.user_id = u.id
INNER JOIN teams team ON u.team_id = team.id
INNER JOIN groups g ON u.group_id = g.id
INNER JOIN opportunities o ON a.opportunity_id = o.id
INNER JOIN stages s ON o.stage_id = s.id
WHERE
a.crm_configuration_id = 356
AND a.status IN ('completed', 'failed')
AND a.recording_state != 'stopped'
# and a.user_id = 13841
AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')
AND team.uuid = uuid_to_bin('a607fba7-452e-4683-b2af-00d6cb52c93c')
AND g.uuid = uuid_to_bin('b5d69e40-24a0-4c16-810b-5fa462299f94')
AND a.type IN ('softphone', 'softphone-inbound', 'conference', 'sms-inbound', 'sms-outbound')
# AND t.type IN ('audio', 'video')
AND (
(a.actual_start_time BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59')
OR
(
a.actual_start_time IS NULL
AND a.type IN ('sms-outbound', 'sms-inbound')
AND a.created_at BETWEEN '2025-03-13 00:00:00' AND '2025-03-18 07:59:59'
)
)
AND (
a.is_private = 0
OR (
a.is_private = 1
AND u.uuid = uuid_to_bin('6f40e4b8-c340-4059-b4ac-1728e87ea99e')
)
)
AND (
# s.id = 15900
s.uuid = uuid_to_bin('04ca1c26-c666-4268-a129-419c0acffd73')
OR s.uuid IS NULL -- Include records without opportunity stage
)
ORDER BY a.actual_end_time DESC;
# [PASSWORD_DOTS]
SELECT * FROM teams WHERE name LIKE '%Lead Forensics%'; # 190, 162, 8474, [EMAIL]
SELECT * FROM users WHERE team_id = 190;
select * from social_accounts sa
join users u on sa.sociable_id = u.id
where u.team_id = 190
and sa.provider = 'hubspot';
select * from role_user where user_id = 8474;
select * from crm_configurations where provider = 'bullhorn';
SELECT * FROM opportunities WHERE uuid_to_bin('94578249-65ec-4205-90f2-7d1a7d5ab64a') = uuid;
SELECT * FROM users WHERE uuid_to_bin('26dbadeb-926f-4150-b11b-771b9d4c2f9a') = uuid;
SELECT * FROM opportunities ...
|
87822
|
NULL
|
NULL
|
NULL
|
|
87923
|
3000
|
62
|
2026-05-28T16:30:10.379357+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985810379_m1.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"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,"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,"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,"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,"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,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","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\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
7140308640360186306
|
1349907984874158724
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87921
|
3000
|
61
|
2026-05-28T16:30:02.603050+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985802603_m1.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"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,"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,"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,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-824022620702545522
|
-9103533727753729596
|
typing_pause
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
iTerm2ShellEditViewSessionScriptsProfilesWindowHelp‹ >0 lol100% CDOCKER₴81DEV (-zsh)O 82Version 2023.11.20260427:Version 2023.11.20260505:Version2023.11.20260509:Version2023.11.20260511:Version2023.11.20260514:Version 2023.11.20260526:Run"/usr/bin/dnf check-release-update"#_####_\ #####\\###||\#/v~'Amazon Linux 2023 (ECS Optimized)-zshN3ec2-user@ip-10-20-31-146:~ffmpeg84-zshX5ec2-user@ip-10-30-129-...8• Thu 28 May 19:30:02181ec2-user@ip-10-20-31-1...·7for full release and version update infom/For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name-ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: : run Memory usage before starting command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryPeakBeforeCommandInMb":118.03 {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcBc-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity for Cognitive Credit[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcDc-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591, "provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generatingaccess token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id" :"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity 494058190045...[2026-05-28 16:20:08] production.INF0: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Synced Centiva Capital - EU HY/IG to 7601423[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: :run Memory usage for command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryAfterCommandInMB": 126.0, "memoryPeakBeforeCommandInMb" : 118.0, "memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id" : "1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}root@170a323e43a4:/home/jiminny# |...
|
87919
|
NULL
|
NULL
|
NULL
|
|
87919
|
3000
|
60
|
2026-05-28T16:29:58.744316+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985798744_m1.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
8569994499127135030
|
-3986301007428073024
|
typing_pause
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
iTerm2ShellEditViewSessionScriptsProfilesWindowHelp‹ >0 lol100% CDOCKER₴81DEV (-zsh)O 82Version 2023.11.20260427:Version 2023.11.20260505:Version2023.11.20260509:Version2023.11.20260511:Version2023.11.20260514:Version 2023.11.20260526:Run"/usr/bin/dnf check-release-update"#_####_\ #####\\###||\#/v~'Amazon Linux 2023 (ECS Optimized)-zshN3ec2-user@ip-10-20-31-146:~ffmpeg84-zshX5ec2-user@ip-10-30-129-...8• Thu 28 May 19:29:58181ec2-user@ip-10-20-31-1...·7for full release and version update infom/For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name-ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: : run Memory usage before starting command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryPeakBeforeCommandInMb":118.03 {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcBc-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity for Cognitive Credit[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcDc-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591, "provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generatingaccess token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id" :"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity 494058190045...[2026-05-28 16:20:08] production.INF0: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Synced Centiva Capital - EU HY/IG to 7601423[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: :run Memory usage for command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryAfterCommandInMB": 126.0, "memoryPeakBeforeCommandInMb" : 118.0, "memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id" : "1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}root@170a323e43a4:/home/jiminny# |...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87917
|
3000
|
59
|
2026-05-28T16:29:55.397565+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985795397_m1.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.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,"on_screen":true,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
8043719072324535154
|
-8628527368849355612
|
typing_pause
|
hybrid
|
NULL
|
Project: faVsco.js, menu
iTerm2ShellEditViewSessio Project: faVsco.js, menu
iTerm2ShellEditViewSessionScriptsProfilesWindowHelp‹ >0 lol100% CDOCKER₴81DEV (-zsh)O 82Version 2023.11.20260427:Version 2023.11.20260505:Version2023.11.20260509:Version2023.11.20260511:Version2023.11.20260514:Version 2023.11.20260526:Run"/usr/bin/dnf check-release-update"#_####_\ #####\\###||\#/v~'Amazon Linux 2023 (ECS Optimized)-zshN3ec2-user@ip-10-20-31-146:~screenpipe"-84-zshX5ec2-user@ip-10-30-129-...8• Thu 28 May 19:29:55181ec2-user@ip-10-20-31-1...·7for full release and version update infom/For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name-ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: : run Memory usage before starting command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryPeakBeforeCommandInMb":118.03 {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcBc-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity for Cognitive Credit[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcDc-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591, "provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generatingaccess token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id" :"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity 494058190045...[2026-05-28 16:20:08] production.INF0: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Synced Centiva Capital - EU HY/IG to 7601423[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: :run Memory usage for command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryAfterCommandInMB": 126.0, "memoryPeakBeforeCommandInMb" : 118.0, "memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id" : "1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}root@170a323e43a4:/home/jiminny# |...
|
87916
|
NULL
|
NULL
|
NULL
|
|
87916
|
3000
|
58
|
2026-05-28T16:29:52.007494+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985792007_m1.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"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,"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,"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,"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,"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,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","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\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","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":"22","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"8","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\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","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,"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}]...
|
3808456254828495905
|
5959254332685757060
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87915
|
3000
|
57
|
2026-05-28T16:29:48.694557+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985788694_m1.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"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,"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,"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,"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,"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,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","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\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","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}]...
|
917752225679264075
|
1347656189355440772
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes...
|
87914
|
NULL
|
NULL
|
NULL
|
|
87914
|
3000
|
56
|
2026-05-28T16:29:46.473334+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985786473_m1.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"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,"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,"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,"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,"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,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","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\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","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":"22","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"8","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\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","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,"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}]...
|
3808456254828495905
|
5959254332685757060
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87913
|
3000
|
55
|
2026-05-28T16:29:42.876025+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985782876_m1.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"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,"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,"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,"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,"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,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","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\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","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":"22","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"8","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\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","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,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-8532334682058705032
|
5959254332685757060
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project...
|
87911
|
NULL
|
NULL
|
NULL
|
|
87911
|
3000
|
54
|
2026-05-28T16:29:37.486439+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985777486_m1.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"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,"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,"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,"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,"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,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","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\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","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":"22","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"8","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\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","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,"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}]...
|
3808456254828495905
|
5959254332685757060
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87910
|
3000
|
53
|
2026-05-28T16:29:35.760828+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985775760_m1.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"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,"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,"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,"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,"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,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","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\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","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":"22","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"8","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}]...
|
-6823557678216596867
|
1347515451867085444
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error...
|
87908
|
NULL
|
NULL
|
NULL
|
|
87908
|
3000
|
52
|
2026-05-28T16:29:31.300624+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985771300_m1.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-5925516468550469094
|
-8643040614315223040
|
typing_pause
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
iTerm2ShellEditViewSessionScriptsProfilesWindowHelp‹ >0 lol100% CDOCKER₴81DEV (-zsh)O 82Version 2023.11.20260427:Version 2023.11.20260505:Version2023.11.20260509:Version2023.11.20260511:Version2023.11.20260514:Version 2023.11.20260526:Run"/usr/bin/dnf check-release-update"#_####_\ #####\\###||\#/v~'Amazon Linux 2023 (ECS Optimized)-zshN3ec2-user@ip-10-20-31-146:~screenpipe"84-zshX5ec2-user@ip-10-30-129-...8• Thu 28 May 19:29:31181ec2-user@ip-10-20-31-1...·7for full release and version update infom/For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name-ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: : run Memory usage before starting command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryPeakBeforeCommandInMb":118.03 {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcBc-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity for Cognitive Credit[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcDc-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591, "provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generatingaccess token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id" :"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity 494058190045...[2026-05-28 16:20:08] production.INF0: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Synced Centiva Capital - EU HY/IG to 7601423[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: :run Memory usage for command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryAfterCommandInMB": 126.0, "memoryPeakBeforeCommandInMb" : 118.0, "memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id" : "1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}root@170a323e43a4:/home/jiminny# |...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87906
|
3000
|
51
|
2026-05-28T16:29:29.122495+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985769122_m1.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-8030868166066345329
|
-8630655715339954048
|
typing_pause
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
iTerm2ShellEditViewSessionScriptsProfilesWindowHelp‹ >0 lol100% CDOCKER₴81DEV (-zsh)O 82Version 2023.11.20260427:Version 2023.11.20260505:Version2023.11.20260509:Version2023.11.20260511:Version2023.11.20260514:Version 2023.11.20260526:Run"/usr/bin/dnf check-release-update"#_####_\ #####\\###||\#/v~'Amazon Linux 2023 (ECS Optimized)-zshN3ec2-user@ip-10-20-31-146:~screenpipe"84-zshX5ec2-user@ip-10-30-129-...8• Thu 28 May 19:29:29181ec2-user@ip-10-20-31-1...·7for full release and version update infom/For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name-ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: : run Memory usage before starting command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryPeakBeforeCommandInMb":118.03 {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcBc-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity for Cognitive Credit[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcDc-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591, "provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generatingaccess token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id" :"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity 494058190045...[2026-05-28 16:20:08] production.INF0: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Synced Centiva Capital - EU HY/IG to 7601423[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: :run Memory usage for command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryAfterCommandInMB": 126.0, "memoryPeakBeforeCommandInMb" : 118.0, "memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id" : "1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}root@170a323e43a4:/home/jiminny# |...
|
87905
|
NULL
|
NULL
|
NULL
|
|
87905
|
3000
|
50
|
2026-05-28T16:29:23.124413+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985763124_m1.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"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,"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,"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,"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,"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,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","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\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","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":"22","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"8","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\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","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,"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}]...
|
3808456254828495905
|
5959254332685757060
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}
Project
Project
New File or Directory…
Expand Selected
Collapse All
Options
Hide...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87903
|
3000
|
49
|
2026-05-28T16:29:14.665793+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985754665_m1.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"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,"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,"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,"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,"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,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","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\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","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":"22","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"8","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\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\Webhook;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncCollector;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\OpportunityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\FieldDataRepository;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\LayoutEntity;\n\nreadonly class PropertyChangeManager\n{\n private const string OBJECT_TYPE_DEAL = 'deal';\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n\n private const array SUPPORTED_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL,\n self::OBJECT_TYPE_CONTACT,\n self::OBJECT_TYPE_COMPANY,\n ];\n\n /**\n * Contact fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update contact.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_CONTACT_FIELDS = [\n 'firstname',\n 'lastname',\n 'email',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'country',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Company fields that webhooks are subscribed to in HubSpot.\n *\n * IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.\n * When updating this list, you must also update the HubSpot webhook subscriptions:\n * 1. Go to HubSpot App Settings → Webhooks\n * 2. Update company.propertyChange subscriptions to match this list\n * 3. Ensure all fields listed here are subscribed, and vice versa\n *\n * This constant serves as documentation of the current webhook configuration.\n * Since HubSpot filters webhooks server-side, we should only receive events for these properties.\n */\n private const array APPLICABLE_COMPANY_FIELDS = [\n 'name',\n 'phone',\n 'domain',\n 'country',\n 'industry',\n 'hubspot_owner_id',\n 'hs_avatar_filemanager_key',\n ];\n\n /**\n * Properties that support direct database updates (without full sync).\n * These are simple properties that can be updated immediately without recalculating other fields.\n */\n private const array DB_OBJECT_UPDATE_PROPERTIES = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname',\n 'description',\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact properties that support direct update\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company properties that support direct update\n ],\n ];\n\n /**\n * Mapping from HubSpot property names to Jiminny model property names.\n * Used when updating the main model (Opportunity, Contact, Account) directly.\n * Only needed when HubSpot property name differs from Jiminny property name.\n */\n private const array OBJECT_PROPERTY_MAPPINGS = [\n self::OBJECT_TYPE_DEAL => [\n 'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'\n ],\n self::OBJECT_TYPE_CONTACT => [\n // Add contact property mappings if needed\n ],\n self::OBJECT_TYPE_COMPANY => [\n // Add company property mappings if needed\n ],\n ];\n\n // Field object types mapping\n private const array FIELD_OBJECT_TYPES = [\n self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,\n self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,\n self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,\n ];\n\n public function __construct(\n private BatchSyncCollector $batchCollector,\n private OpportunityRepository $opportunityRepository,\n private CrmEntityRepository $crmEntityRepository,\n private FieldRepository $fieldRepository,\n private FieldDataRepository $fieldDataRepository,\n private HubspotWebhookMetricsService $metricsService,\n ) {\n }\n\n /**\n * Get contact fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableContactFields(): array\n {\n return self::APPLICABLE_CONTACT_FIELDS;\n }\n\n /**\n * Get company fields that webhooks are subscribed to in HubSpot.\n * This serves as documentation of the current webhook configuration.\n *\n * @return array<int, string>\n */\n public function getApplicableCompanyFields(): array\n {\n return self::APPLICABLE_COMPANY_FIELDS;\n }\n\n /**\n * Process property change with intelligent routing\n */\n public function processPropertyChange(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n Log::warning('[HubSpot Property Change Manager] Unsupported object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n ]);\n\n return;\n }\n\n $this->metricsService->recordWebhookMetrics(\n $configuration,\n $objectType,\n 'property_change',\n $propertyName\n );\n\n if ($this->isDirectUpdateSupported($objectType, $propertyName) &&\n $this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {\n\n return;\n }\n\n $this->handleObjectSync($objectType, $objectId, $configuration);\n }\n\n /**\n * Legacy method for backward compatibility - assumes deal object type\n *\n * @deprecated Use processPropertyChange with objectType parameter\n */\n public function processPropertyChangeForDeal(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): void {\n $this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);\n }\n\n /**\n * Check if object type is supported\n */\n private function isObjectTypeSupported(string $objectType): bool\n {\n return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);\n }\n\n /**\n * Check if property can be updated without additional calculation on other properties.\n */\n private function isDirectUpdateSupported(string $objectType, string $propertyName): bool\n {\n $supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];\n\n return in_array($propertyName, $supportedProperties, true);\n }\n\n /**\n * Handle properties that support direct database updates\n */\n private function handleDirectUpdate(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n try {\n return match ($objectType) {\n self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),\n default => false,\n };\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error handling direct update property', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'property_name' => $propertyName,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n /**\n * Handle direct updates for deal objects\n */\n private function handleDealDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(\n $configuration,\n $objectId\n );\n\n if (! $opportunity instanceof Opportunity) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->opportunityRepository->updateOrCreate(\n $configuration,\n $objectId,\n [$propertyMappings[$propertyName] => $propertyValue]\n );\n }\n\n // Update field data\n $this->importObjectFieldData(\n self::OBJECT_TYPE_DEAL,\n $opportunity->getId(),\n $configuration,\n [$propertyName => $propertyValue]\n );\n\n return true;\n }\n\n /**\n * Handle direct updates for contact objects\n *\n * Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.\n */\n private function handleContactDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);\n\n if ($contact === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importContact($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Handle direct updates for company objects\n *\n * Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.\n * Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.\n */\n private function handleCompanyDirectUpdate(\n string $objectId,\n Configuration $configuration,\n string $propertyName,\n string $propertyValue\n ): bool {\n $company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);\n\n if ($company === null) {\n return false;\n }\n\n // Update model property if mapping exists\n $propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];\n if (isset($propertyMappings[$propertyName])) {\n $this->crmEntityRepository->importAccount($configuration, [\n 'crm_provider_id' => $objectId,\n $propertyMappings[$propertyName] => $propertyValue,\n ]);\n }\n\n return true;\n }\n\n /**\n * Import field data for any object type\n */\n private function importObjectFieldData(\n string $objectType,\n int $objectId,\n Configuration $configuration,\n array $data\n ): void {\n $fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;\n if (! $fieldObjectType) {\n Log::warning('[HubSpot Property Change Manager] Unknown field object type', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n ]);\n\n return;\n }\n\n foreach ($data as $crmField => $value) {\n $field = $this->fieldRepository->findFieldByCrmIdAndObjectType(\n $configuration,\n $crmField,\n $fieldObjectType\n );\n\n if (! $field instanceof Field) {\n continue;\n }\n\n $entities = $field->getEntities();\n if ($entities->isEmpty()) {\n continue;\n }\n\n if ($entities->count() > 1) {\n continue;\n }\n\n /** @var LayoutEntity|null $entity */\n $entity = $entities->first();\n if (! $entity instanceof LayoutEntity) {\n continue;\n }\n\n $this->fieldDataRepository->updateOrCreateFieldData(\n $entity,\n $objectId,\n (string) $value,\n );\n }\n }\n\n private function handleObjectSync(\n string $objectType,\n string $objectId,\n Configuration $configuration,\n ): void {\n if (! $this->isObjectTypeSupported($objectType)) {\n return;\n }\n\n try {\n $this->batchCollector->collectForBatch(\n objectType: $objectType,\n crmProviderId: $objectId,\n configurationId: $configuration->getId(),\n eventType: 'property_change'\n );\n } catch (\\Exception $e) {\n Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [\n 'object_type' => $objectType,\n 'object_id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-8584229028334691180
|
5959254332685757060
|
visual_change
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\Webhook;
use Illuminate\Support\Facades\Log;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Services\Crm\Hubspot\BatchSyncCollector;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\OpportunityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\FieldDataRepository;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\LayoutEntity;
readonly class PropertyChangeManager
{
private const string OBJECT_TYPE_DEAL = 'deal';
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const array SUPPORTED_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL,
self::OBJECT_TYPE_CONTACT,
self::OBJECT_TYPE_COMPANY,
];
/**
* Contact fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update contact.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_CONTACT_FIELDS = [
'firstname',
'lastname',
'email',
'phone',
'mobilephone',
'jobtitle',
'country',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
'hs_avatar_filemanager_key',
];
/**
* Company fields that webhooks are subscribed to in HubSpot.
*
* IMPORTANT: These fields MUST match the webhook subscriptions configured in HubSpot.
* When updating this list, you must also update the HubSpot webhook subscriptions:
* 1. Go to HubSpot App Settings → Webhooks
* 2. Update company.propertyChange subscriptions to match this list
* 3. Ensure all fields listed here are subscribed, and vice versa
*
* This constant serves as documentation of the current webhook configuration.
* Since HubSpot filters webhooks server-side, we should only receive events for these properties.
*/
private const array APPLICABLE_COMPANY_FIELDS = [
'name',
'phone',
'domain',
'country',
'industry',
'hubspot_owner_id',
'hs_avatar_filemanager_key',
];
/**
* Properties that support direct database updates (without full sync).
* These are simple properties that can be updated immediately without recalculating other fields.
*/
private const array DB_OBJECT_UPDATE_PROPERTIES = [
self::OBJECT_TYPE_DEAL => [
'dealname',
'description',
],
self::OBJECT_TYPE_CONTACT => [
// Add contact properties that support direct update
],
self::OBJECT_TYPE_COMPANY => [
// Add company properties that support direct update
],
];
/**
* Mapping from HubSpot property names to Jiminny model property names.
* Used when updating the main model (Opportunity, Contact, Account) directly.
* Only needed when HubSpot property name differs from Jiminny property name.
*/
private const array OBJECT_PROPERTY_MAPPINGS = [
self::OBJECT_TYPE_DEAL => [
'dealname' => 'name', // HubSpot 'dealname' maps to Opportunity 'name'
],
self::OBJECT_TYPE_CONTACT => [
// Add contact property mappings if needed
],
self::OBJECT_TYPE_COMPANY => [
// Add company property mappings if needed
],
];
// Field object types mapping
private const array FIELD_OBJECT_TYPES = [
self::OBJECT_TYPE_DEAL => Field::OBJECT_OPPORTUNITY,
self::OBJECT_TYPE_CONTACT => Field::OBJECT_CONTACT,
self::OBJECT_TYPE_COMPANY => Field::OBJECT_ACCOUNT,
];
public function __construct(
private BatchSyncCollector $batchCollector,
private OpportunityRepository $opportunityRepository,
private CrmEntityRepository $crmEntityRepository,
private FieldRepository $fieldRepository,
private FieldDataRepository $fieldDataRepository,
private HubspotWebhookMetricsService $metricsService,
) {
}
/**
* Get contact fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableContactFields(): array
{
return self::APPLICABLE_CONTACT_FIELDS;
}
/**
* Get company fields that webhooks are subscribed to in HubSpot.
* This serves as documentation of the current webhook configuration.
*
* @return array<int, string>
*/
public function getApplicableCompanyFields(): array
{
return self::APPLICABLE_COMPANY_FIELDS;
}
/**
* Process property change with intelligent routing
*/
public function processPropertyChange(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
if (! $this->isObjectTypeSupported($objectType)) {
Log::warning('[HubSpot Property Change Manager] Unsupported object type', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
]);
return;
}
$this->metricsService->recordWebhookMetrics(
$configuration,
$objectType,
'property_change',
$propertyName
);
if ($this->isDirectUpdateSupported($objectType, $propertyName) &&
$this->handleDirectUpdate($objectType, $objectId, $configuration, $propertyName, $propertyValue)) {
return;
}
$this->handleObjectSync($objectType, $objectId, $configuration);
}
/**
* Legacy method for backward compatibility - assumes deal object type
*
* @deprecated Use processPropertyChange with objectType parameter
*/
public function processPropertyChangeForDeal(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): void {
$this->processPropertyChange(self::OBJECT_TYPE_DEAL, $objectId, $configuration, $propertyName, $propertyValue);
}
/**
* Check if object type is supported
*/
private function isObjectTypeSupported(string $objectType): bool
{
return in_array($objectType, self::SUPPORTED_OBJECT_TYPES);
}
/**
* Check if property can be updated without additional calculation on other properties.
*/
private function isDirectUpdateSupported(string $objectType, string $propertyName): bool
{
$supportedProperties = self::DB_OBJECT_UPDATE_PROPERTIES[$objectType] ?? [];
return in_array($propertyName, $supportedProperties, true);
}
/**
* Handle properties that support direct database updates
*/
private function handleDirectUpdate(
string $objectType,
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
try {
return match ($objectType) {
self::OBJECT_TYPE_DEAL => $this->handleDealDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_CONTACT => $this->handleContactDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
self::OBJECT_TYPE_COMPANY => $this->handleCompanyDirectUpdate($objectId, $configuration, $propertyName, $propertyValue),
default => false,
};
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error handling direct update property', [
'object_type' => $objectType,
'object_id' => $objectId,
'property_name' => $propertyName,
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Handle direct updates for deal objects
*/
private function handleDealDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$opportunity = $this->opportunityRepository->findByConfigAndCrmProviderId(
$configuration,
$objectId
);
if (! $opportunity instanceof Opportunity) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_DEAL] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->opportunityRepository->updateOrCreate(
$configuration,
$objectId,
[$propertyMappings[$propertyName] => $propertyValue]
);
}
// Update field data
$this->importObjectFieldData(
self::OBJECT_TYPE_DEAL,
$opportunity->getId(),
$configuration,
[$propertyName => $propertyValue]
);
return true;
}
/**
* Handle direct updates for contact objects
*
* Updates Contact model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[CONTACT] to enable direct updates.
*/
private function handleContactDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$contact = $this->crmEntityRepository->findContactByExternalId($configuration, $objectId);
if ($contact === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_CONTACT] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importContact($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Handle direct updates for company objects
*
* Updates Account model properties via OBJECT_PROPERTY_MAPPINGS.
* Add mappings to OBJECT_PROPERTY_MAPPINGS[COMPANY] to enable direct updates.
*/
private function handleCompanyDirectUpdate(
string $objectId,
Configuration $configuration,
string $propertyName,
string $propertyValue
): bool {
$company = $this->crmEntityRepository->findAccountByExternalId($configuration, $objectId);
if ($company === null) {
return false;
}
// Update model property if mapping exists
$propertyMappings = self::OBJECT_PROPERTY_MAPPINGS[self::OBJECT_TYPE_COMPANY] ?? [];
if (isset($propertyMappings[$propertyName])) {
$this->crmEntityRepository->importAccount($configuration, [
'crm_provider_id' => $objectId,
$propertyMappings[$propertyName] => $propertyValue,
]);
}
return true;
}
/**
* Import field data for any object type
*/
private function importObjectFieldData(
string $objectType,
int $objectId,
Configuration $configuration,
array $data
): void {
$fieldObjectType = self::FIELD_OBJECT_TYPES[$objectType] ?? null;
if (! $fieldObjectType) {
Log::warning('[HubSpot Property Change Manager] Unknown field object type', [
'object_type' => $objectType,
'object_id' => $objectId,
]);
return;
}
foreach ($data as $crmField => $value) {
$field = $this->fieldRepository->findFieldByCrmIdAndObjectType(
$configuration,
$crmField,
$fieldObjectType
);
if (! $field instanceof Field) {
continue;
}
$entities = $field->getEntities();
if ($entities->isEmpty()) {
continue;
}
if ($entities->count() > 1) {
continue;
}
/** @var LayoutEntity|null $entity */
$entity = $entities->first();
if (! $entity instanceof LayoutEntity) {
continue;
}
$this->fieldDataRepository->updateOrCreateFieldData(
$entity,
$objectId,
(string) $value,
);
}
}
private function handleObjectSync(
string $objectType,
string $objectId,
Configuration $configuration,
): void {
if (! $this->isObjectTypeSupported($objectType)) {
return;
}
try {
$this->batchCollector->collectForBatch(
objectType: $objectType,
crmProviderId: $objectId,
configurationId: $configuration->getId(),
eventType: 'property_change'
);
} catch (\Exception $e) {
Log::error('[HubSpot Property Change Manager] Error adding to sync batch', [
'object_type' => $objectType,
'object_id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
}...
|
87901
|
NULL
|
NULL
|
NULL
|
|
87901
|
3000
|
48
|
2026-05-28T16:29:06.692308+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985746692_m1.jpg...
|
Alfred
|
Alfred
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
ts 1779301965775
|
[{"role":"AXTextField","text [{"role":"AXTextField","text":"ts 1779301965775","depth":1,"bounds":{"left":0.26180556,"top":0.16777778,"width":0.4763889,"height":0.05888889},"on_screen":true,"value":"ts 1779301965775","help_text":"Alfred Search","role_description":"text field","is_enabled":true,"is_focused":true}]...
|
-5636280577917379171
|
1424425352641761951
|
typing_pause
|
hybrid
|
NULL
|
ts 1779301965775
iTerm2ShellEditViewSessionScripts ts 1779301965775
iTerm2ShellEditViewSessionScriptsProfilesWindowHelp‹>0 (|DOCKER₴81DEV (-zsh)O 82Version 2023.11.20260427:Version2023.11.20260505:Version2023.11.20260509:Version2023.11.20260511:Version2023.11.20260514:Version 2023.11.20260526:tsRun"/usr/bin/dnf check-release-update"for#_####_#####\\###||\#/v~'Amazon Linux 2023 (E(S Optimized)-zshN3ec2-user@ip-10-20-31-146:~screenpipe"O ₴4-zshX5ec2-user@ip-10-30-129-...100% <78• Thu 28 May 19:29:06181ec2-user@ip-10-20-31-1...·7Time on SteroidsPlease enter now, timestamp and formatted date+For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name-ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: : run Memory usage before starting command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryPeakBeforeCommandInMb":118.03 {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcBc-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity for Cognitive Credit[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcDc-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591, "provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generatingaccess token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id" :"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity 494058190045...[2026-05-28 16:20:08] production.INF0: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Synced Centiva Capital - EU HY/IG to 7601423[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: :run Memory usage for command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryAfterCommandInMB": 126.0, "memoryPeakBeforeCommandInMb" : 118.0, "memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id" : "1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}root@170a323e43a4:/home/jiminny# |...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87899
|
3000
|
47
|
2026-05-28T16:29:04.423226+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985744423_m1.jpg...
|
iTerm2
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
iTerm2ShellEditViewSessionScriptsProfilesWindowHel iTerm2ShellEditViewSessionScriptsProfilesWindowHelp‹>0 lolDOCKER₴81DEV (-zsh)O 82Version 2023.11.20260427:Version 2023.11.20260505:Version2023.11.20260509:Version2023.11.20260511:Version2023.11.20260514:Version 2023.11.20260526:Run"/usr/bin/dnf check-release-update"#_####_\ #####\\###||\#/v~'Amazon Linux 2023 (ECS Optimized)-zshN3ec2-user@ip-10-20-31-146:~screenpipe"-zshX5ec2-user@ip-10-30-129-...ec2-user@ip-10-20-31-1...100% (8• Thu 28 May 19:29:04181·7for full release and version update infom/For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name-ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: : run Memory usage before starting command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryPeakBeforeCommandInMb":118.03 {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcBc-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity for Cognitive Credit[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcDc-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591, "provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generatingaccess token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id" :"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity 494058190045...[2026-05-28 16:20:08] production.INF0: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Synced Centiva Capital - EU HY/IG to 7601423[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: :run Memory usage for command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryAfterCommandInMB": 126.0, "memoryPeakBeforeCommandInMb" : 118.0, "memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id" : "1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}root@170a323e43a4:/home/jiminny# |...
|
NULL
|
-7869934841991256604
|
NULL
|
typing_pause
|
ocr
|
NULL
|
iTerm2ShellEditViewSessionScriptsProfilesWindowHel iTerm2ShellEditViewSessionScriptsProfilesWindowHelp‹>0 lolDOCKER₴81DEV (-zsh)O 82Version 2023.11.20260427:Version 2023.11.20260505:Version2023.11.20260509:Version2023.11.20260511:Version2023.11.20260514:Version 2023.11.20260526:Run"/usr/bin/dnf check-release-update"#_####_\ #####\\###||\#/v~'Amazon Linux 2023 (ECS Optimized)-zshN3ec2-user@ip-10-20-31-146:~screenpipe"-zshX5ec2-user@ip-10-30-129-...ec2-user@ip-10-20-31-1...100% (8• Thu 28 May 19:29:04181·7for full release and version update infom/For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name-ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: : run Memory usage before starting command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryPeakBeforeCommandInMb":118.03 {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcBc-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity for Cognitive Credit[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcDc-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591, "provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generatingaccess token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id" :"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity 494058190045...[2026-05-28 16:20:08] production.INF0: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Synced Centiva Capital - EU HY/IG to 7601423[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: :run Memory usage for command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryAfterCommandInMB": 126.0, "memoryPeakBeforeCommandInMb" : 118.0, "memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id" : "1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}root@170a323e43a4:/home/jiminny# |...
|
87898
|
NULL
|
NULL
|
NULL
|
|
87898
|
3000
|
46
|
2026-05-28T16:29:00.905168+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985740905_m1.jpg...
|
iTerm2
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
iTerm2ShellEditViewSessionScriptsProfilesWindowHel iTerm2ShellEditViewSessionScriptsProfilesWindowHelp‹ >0 lol100% CDOCKER₴81DEV (-zsh)O 82Version 2023.11.20260427:Version 2023.11.20260505:Version2023.11.20260509:Version2023.11.20260511:Version2023.11.20260514:Version 2023.11.20260526:Run"/usr/bin/dnf check-release-update"#_####_\ #####\\###||\#/v~'Amazon Linux 2023 (ECS Optimized)-zshN3ec2-user@ip-10-20-31-146:~screenpipe"O &4-zshX5ec2-user@ip-10-30-129-...8 • Thu 28 May 19:29:00181ec2-user@ip-10-20-31-1...·7for full release and version update infom/For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name-ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: : run Memory usage before starting command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryPeakBeforeCommandInMb":118.03 {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcBc-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity for Cognitive Credit[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcDc-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591, "provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generatingaccess token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id" :"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity 494058190045...[2026-05-28 16:20:08] production.INF0: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Synced Centiva Capital - EU HY/IG to 7601423[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: :run Memory usage for command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryAfterCommandInMB": 126.0, "memoryPeakBeforeCommandInMb" : 118.0, "memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id" : "1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}root@170a323e43a4:/home/jiminny# |...
|
NULL
|
-3066283853955425739
|
NULL
|
click
|
ocr
|
NULL
|
iTerm2ShellEditViewSessionScriptsProfilesWindowHel iTerm2ShellEditViewSessionScriptsProfilesWindowHelp‹ >0 lol100% CDOCKER₴81DEV (-zsh)O 82Version 2023.11.20260427:Version 2023.11.20260505:Version2023.11.20260509:Version2023.11.20260511:Version2023.11.20260514:Version 2023.11.20260526:Run"/usr/bin/dnf check-release-update"#_####_\ #####\\###||\#/v~'Amazon Linux 2023 (ECS Optimized)-zshN3ec2-user@ip-10-20-31-146:~screenpipe"O &4-zshX5ec2-user@ip-10-30-129-...8 • Thu 28 May 19:29:00181ec2-user@ip-10-20-31-1...·7for full release and version update infom/For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name-ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: : run Memory usage before starting command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryPeakBeforeCommandInMb":118.03 {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcBc-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity for Cognitive Credit[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcDc-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591, "provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generatingaccess token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id" :"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity 494058190045...[2026-05-28 16:20:08] production.INF0: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Synced Centiva Capital - EU HY/IG to 7601423[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: :run Memory usage for command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryAfterCommandInMB": 126.0, "memoryPeakBeforeCommandInMb" : 118.0, "memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id" : "1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}root@170a323e43a4:/home/jiminny# |...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87894
|
3000
|
45
|
2026-05-28T16:28:42.943864+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985722943_m1.jpg...
|
iTerm2
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
iTerm2ShellEditViewSessionScriptsProfilesWindowHel iTerm2ShellEditViewSessionScriptsProfilesWindowHelp‹ >0 lol100% CDOCKER₴81DEV (-zsh)O 82Version 2023.11.20260427:Version 2023.11.20260505:Version2023.11.20260509:Version2023.11.20260511:Version2023.11.20260514:Version 2023.11.20260526:Run"/usr/bin/dnf check-release-update"#_####_\ #####\\###||\#/v~'Amazon Linux 2023 (ECS Optimized)-zshN3ec2-user@ip-10-20-31-146:~screenpipe"84-zshX5ec2-user@ip-10-30-129-...8• Thu 28 May 19:28:42181ec2-user@ip-10-20-31-1...·7for full release and version update infom/For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name-ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: : run Memory usage before starting command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryPeakBeforeCommandInMb":118.03 {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcBc-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity for Cognitive Credit[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcDc-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591, "provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generatingaccess token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id" :"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity 494058190045...[2026-05-28 16:20:08] production.INF0: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Synced Centiva Capital - EU HY/IG to 7601423[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: :run Memory usage for command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryAfterCommandInMB": 126.0, "memoryPeakBeforeCommandInMb" : 118.0, "memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id" : "1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}root@170a323e43a4:/home/jiminny# |...
|
NULL
|
5096012192353817444
|
NULL
|
click
|
ocr
|
NULL
|
iTerm2ShellEditViewSessionScriptsProfilesWindowHel iTerm2ShellEditViewSessionScriptsProfilesWindowHelp‹ >0 lol100% CDOCKER₴81DEV (-zsh)O 82Version 2023.11.20260427:Version 2023.11.20260505:Version2023.11.20260509:Version2023.11.20260511:Version2023.11.20260514:Version 2023.11.20260526:Run"/usr/bin/dnf check-release-update"#_####_\ #####\\###||\#/v~'Amazon Linux 2023 (ECS Optimized)-zshN3ec2-user@ip-10-20-31-146:~screenpipe"84-zshX5ec2-user@ip-10-30-129-...8• Thu 28 May 19:28:42181ec2-user@ip-10-20-31-1...·7for full release and version update infom/For documentation, visit [URL_WITH_CREDENTIALS] ~]$ docker exec -it $(docker ps --format "{{.ID}}" --filter "name-ecs-worker" | head -1) /bin/bash -c "cd /home/jiminny && bash"root@170a323e43a4:/home/jiminny# php artisan crm:sync-opportunity --teamId 555 --opportunityId 494058190045[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: : run Memory usage before starting command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryPeakBeforeCommandInMb":118.03 {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcBc-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity for Cognitive Credit[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Fetching token {"socialAccountId":30591,"provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bcDc-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [SocialAccountService] Token retrieved {"socialAccountId":30591, "provider": "hubspot"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"'}[2026-05-28 16:20:08] production.INFO: [EncryptedTokenManager] Generatingaccess token. {"mode":"legacy"} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id" :"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Syncing opportunity 494058190045...[2026-05-28 16:20:08] production.INF0: [ReindexForOpportunityListener] Schedule reindexing job {"opportunity_id":7601423} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8","trace_id":"1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}Synced Centiva Capital - EU HY/IG to 7601423[2026-05-28 16:20:08] production.INF0: Jiminny\Console\Commands\Command: :run Memory usage for command {"command": "crm:sync-opportunity", "memoryBeforeCommandInMb" : 118.0, "memoryAfterCommandInMB": 126.0, "memoryPeakBeforeCommandInMb" : 118.0, "memoryPeakAfterCommandInMB":126.0} {"correlation_id":"0a531c45-bc24-4ea8-b3c9-d90f79590da8", "trace_id" : "1723bc0c-9f67-4ec7-b8c3-d09361d5879d"}root@170a323e43a4:/home/jiminny# |...
|
87893
|
NULL
|
NULL
|
NULL
|
|
87893
|
3000
|
44
|
2026-05-28T16:28:32.513812+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985712513_m1.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"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,"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,"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,"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,"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,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","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\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","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":"22","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"8","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}]...
|
-6823557678216596867
|
1347515451867085444
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error...
|
NULL
|
NULL
|
NULL
|
NULL
|
|
87891
|
3000
|
43
|
2026-05-28T16:28:30.710981+00:00
|
/Users/lukas/.screenpipe/data/data/2026-05-28/1779 /Users/lukas/.screenpipe/data/data/2026-05-28/1779985710710_m1.jpg...
|
PhpStorm
|
faVsco.js – PropertyChangeManager.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"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":"#12121 on JY-20963-fix-import-on-deleted-entity, menu","depth":5,"on_screen":true,"help_text":"Pull request #12121 exists for current branch JY-20963-fix-import-on-deleted-entity, but pull request details loading failed","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,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"ServiceTest","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'ServiceTest'","depth":6,"on_screen":true,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'ServiceTest'","depth":6,"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,"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,"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,"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,"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,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"25","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\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","depth":4,"on_screen":true,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Psr\\Log\\LoggerInterface;\n\nclass PayloadBuilder\n{\n public const int MAX_SEARCH_REQUEST_LIMIT = 200;\n\n private const int MAX_FILTER_SIZE = 100;\n\n private const string SORT_PROPERTY = 'hs_timestamp';\n private const string ENGAGEMENT_MEETINGS = 'meetings';\n\n public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($engagementType === self::ENGAGEMENT_MEETINGS) {\n $payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_timestamp',\n 'hs_activity_type',\n ];\n } else {\n $payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp'];\n }\n\n return $payload;\n }\n\n public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array\n {\n $lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array\n {\n $lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';\n\n $payload = [\n 'filters' => [\n [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'GT',\n 'value' => $since->getPreciseTimestamp(3),\n ],\n [\n 'propertyName' => 'hubspot_owner_id',\n 'operator' => 'EQ',\n 'value' => $crmId,\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_object_id',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($to) {\n $payload['filters'][] = [\n 'propertyName' => $lastUpdateDate,\n 'operator' => 'LT',\n 'value' => $to->getPreciseTimestamp(3),\n ];\n }\n\n $payload['properties'] = $properties;\n\n return $payload;\n }\n\n private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array\n {\n $filters = [];\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'IN',\n 'values' => ['SCHEDULED', 'RESCHEDULED'],\n ],\n ],\n ];\n\n $filters[] = [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n [\n 'propertyName' => 'hs_meeting_outcome',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ],\n ];\n\n return $filters;\n }\n\n private function buildTaskFiltersForLinkToTask($objectType, $objectId): array\n {\n return [\n [\n 'filters' => [\n $this->getAssociatedObjectFilter($objectType, $objectId),\n ],\n ],\n ];\n }\n\n private function getAssociatedObjectFilter(string $objectType, string $objectId): array\n {\n return [\n 'propertyName' => 'associations.' . $objectType,\n 'operator' => 'EQ',\n 'value' => $objectId,\n ];\n }\n\n public function generatePlaybackURLSearchPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $activityProvider,\n ],\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'operator' => 'BETWEEN',\n 'value' => intval($from->getPreciseTimestamp(3)),\n 'highValue' => intval($to->getPreciseTimestamp(3)),\n ],\n ],\n 'sorts' => [\n [\n 'propertyName' => 'hs_timestamp',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $this->getSearchCallAttributes(),\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n 'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n }\n\n public function getSearchCallAttributes(): array\n {\n return [\n 'hs_timestamp',\n 'hs_call_recording_url',\n 'hs_call_body',\n 'hs_call_status',\n 'hs_call_to_number',\n 'hs_call_from_number',\n 'hs_call_duration',\n 'hs_call_disposition',\n 'hs_call_title',\n 'hs_call_direction',\n 'hubspot_owner_id',\n 'hs_activity_type',\n 'hs_call_external_id',\n 'hs_call_source',\n ];\n }\n\n public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array\n {\n $updateObjectsData = [];\n\n foreach ($crmUpdateData as $data) {\n $updateObjectsData[] = [\n 'id' => $data['crm_id'],\n 'properties' => [\n 'hs_call_body' => $data['hs_call_body'] .\n '<p><span style=\"font-size: 13.3333px; line-height: 16px;\">' .\n '<a href=\"' . $data['playback_url'] . '\" target=\"_blank\">Review in Jiminny</a> ▶️</span></p>',\n ],\n ];\n }\n\n return ['inputs' => $updateObjectsData];\n }\n\n public function generateSearchCallByTokenPayload(string $playbackURLToken): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => 'hs_call_recording_url',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $playbackURLToken,\n ],\n ],\n 'properties' => [\n 'hs_call_recording_url',\n 'hs_call_body',\n ],\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload for phone search based on the specified parameters.\n *\n * @param string $phone The phone number to search.\n * @param bool $isAlternativeSearch Indicates if an alternative search should be performed\n * if the first search fails to find a match. The first search request should cover most of the cases.\n */\n public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array\n {\n $filterPropertyNames = $isAlternativeSearch ?\n ['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :\n ['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];\n\n $filterGroups = array_map(function ($propertyName) use ($phone) {\n return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);\n }, $filterPropertyNames);\n\n $properties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n\n return $this->createPayload($filterGroups, $properties);\n }\n\n /**\n * Creates a filter group with the specified parameters.\n */\n private function createFilterGroup(string $propertyName, string $operator, $value): array\n {\n return [\n 'filters' => [\n [\n 'propertyName' => $propertyName,\n 'operator' => $operator,\n 'value' => $value,\n ],\n ],\n ];\n }\n\n /**\n * Creates a payload with the specified filter groups and properties.\n */\n private function createPayload(array $filterGroups, array $properties): array\n {\n return [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n 'properties' => $properties,\n 'limit' => 1,\n ];\n }\n\n /**\n * Generates a payload to find related activities based on the specified data and object type.\n * The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)\n * and are associated with any of the provided prospect types (contact or company).\n *\n * @param array $data An associative array containing the following keys:\n * - 'from': The start time for the activity search (timestamp).\n * - 'to': The end time for the activity search (timestamp).\n * - 'contact': (optional) The ID of the associated contact.\n * - 'company': (optional) The ID of the associated company.\n * @param string $objectType The type of engagement to search for (meeting or other type like call).\n *\n * @return array The payload array to be used for searching related activities.\n */\n public function getFindRelatedActivityPayload(array $data, string $objectType): array\n {\n $payload = [\n 'sorts' => [\n [\n 'propertyName' => self::SORT_PROPERTY,\n 'direction' => 'DESCENDING',\n ],\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n if ($objectType === self::ENGAGEMENT_MEETINGS) {\n $payload['properties'] = [\n 'hs_meeting_title',\n 'hs_meeting_outcome',\n 'hs_activity_type',\n 'hs_timestamp',\n 'hubspot_owner_id',\n 'hs_meeting_body',\n 'hs_internal_meeting_notes',\n 'hs_meeting_location',\n 'hs_meeting_start_time',\n 'hs_meeting_end_time',\n ];\n } else {\n $payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];\n }\n\n $timeFiltersWithEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'LTE',\n 'value' => $data['to'],\n ],\n ];\n\n $timeFiltersWithoutEndTime = [\n [\n 'propertyName' => 'hs_meeting_start_time',\n 'operator' => 'GTE',\n 'value' => $data['from'],\n ],\n [\n 'propertyName' => 'hs_meeting_end_time',\n 'operator' => 'NOT_HAS_PROPERTY',\n ],\n ];\n\n $payload['filterGroups'] = [];\n\n $associationTypes = ['contact', 'company'];\n foreach ($associationTypes as $type) {\n if (! empty($data[$type])) {\n $filterGroupWithEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithEndTime;\n\n $filterGroupWithoutEndTime = [\n 'filters' => array_merge(\n $timeFiltersWithoutEndTime,\n [$this->getAssociatedObjectFilter($type, $data[$type])]\n ),\n ];\n $payload['filterGroups'][] = $filterGroupWithoutEndTime ;\n }\n }\n\n return $payload;\n }\n\n /** Parameters\n * [\n * 'accountId' => $crmAccountId,\n * 'sortBy' => $sortBy,\n * 'sortDir' => $sortDir,\n * 'onlyOpen' => $onlyOpen,\n * 'closedStages' => $this->getClosedDealStages(),\n * 'userId' => $userId,\n * ];\n */\n public function generateOpportunitiesSearchPayload(\n Configuration $config,\n string $crmAccountId,\n array $closedStages,\n ): array {\n $closedFilters = [];\n $filterGroups = [];\n $onlyOpen = true;\n\n switch ($config->getOpportunityAssignmentRule()) {\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'DESCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:\n $sortBy = 'createdate';\n $sortDir = 'ASCENDING';\n\n break;\n\n case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:\n default:\n $sortBy = 'modifieddate';\n $sortDir = 'DESCENDING';\n $onlyOpen = false;\n }\n\n $baseFilters = [\n [\n 'propertyName' => 'associations.company',\n 'operator' => 'EQ',\n 'value' => $crmAccountId,\n ],\n ];\n\n // Handle closed stages in chunks\n if ($onlyOpen) {\n foreach (['won', 'lost'] as $key) {\n if (! empty($closedStages[$key])) {\n $chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);\n foreach ($chunks as $chunk) {\n $closedFilters[] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $chunk,\n ];\n }\n }\n }\n }\n\n $filterGroups[] = [\n 'filters' => array_merge($baseFilters, $closedFilters),\n ];\n\n $payload = [\n 'filterGroups' => $filterGroups,\n 'sorts' => [\n [\n 'propertyName' => $sortBy,\n 'direction' => $sortDir,\n ],\n ],\n 'properties' => [\n 'dealname',\n 'amount',\n 'hubspot_owner_id',\n 'pipeline',\n 'dealstage',\n 'closedate',\n 'deal_currency_code',\n ],\n 'limit' => self::MAX_SEARCH_REQUEST_LIMIT,\n ];\n\n $logger = app(LoggerInterface::class);\n $logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * Converts v1 payload data to v3\n */\n public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array\n {\n // Use this mapping until the whole Hubspot V1 is dropped.\n $properties = [\n 'hubspot_owner_id' => $engagement['ownerId'],\n 'hs_timestamp' => $engagement['timestamp'],\n ];\n\n // $engagement['activityType'] is $activity->category->name\n if (isset($engagement['activityType'])) {\n $properties['hs_activity_type'] = $engagement['activityType'];\n }\n\n $metadataKeyMap = [\n 'hs_meeting_outcome' => 'meetingOutcome',\n 'hs_meeting_title' => 'title',\n 'hs_meeting_start_time' => 'startTime',\n 'hs_meeting_end_time' => 'endTime',\n 'hs_meeting_body' => 'body',\n 'hs_internal_meeting_notes' => 'internalMeetingNotes',\n ];\n\n foreach ($metadataKeyMap as $newKey => $oldKey) {\n if (isset($metadata[$oldKey])) {\n $properties[$newKey] = $metadata[$oldKey];\n unset($metadata[$oldKey]);\n }\n }\n\n $properties = [\n ...$properties,\n ...$metadata, // custom fields\n ];\n\n $response = [\n 'properties' => $properties,\n ];\n\n if (! empty($associations)) {\n $response['associations'] = $associations;\n }\n\n return $response;\n }\n\n /**\n * Generate a payload to search for contacts by name.\n * The search is a token search in firstname or lastname\n */\n public function generateSearchContactsByNamePayload(string $name, array $fields): array\n {\n $firstNameFilter = [\n 'propertyName' => 'firstname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n $lastNameFilter = [\n 'propertyName' => 'lastname',\n 'operator' => 'CONTAINS_TOKEN',\n 'value' => $name,\n ];\n\n return [\n 'filterGroups' => [\n [\n 'filters' => [$firstNameFilter],\n ],\n [\n 'filters' => [$lastNameFilter],\n ],\n ],\n 'properties' => $fields,\n 'sorts' => [\n [\n 'propertyName' => 'lastmodifieddate',\n 'direction' => 'DESCENDING',\n ],\n ],\n ];\n }\n\n public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array\n {\n $inputs = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $inputs[] = [\n 'from' => [\n 'id' => $crmId,\n ],\n 'to' => [\n 'id' => (string) $id,\n ],\n 'types' => [\n [\n 'associationCategory' => 'HUBSPOT_DEFINED',\n 'associationTypeId' => $associationType,\n ],\n ],\n ];\n }\n\n return ['inputs' => $inputs];\n }\n\n public function buildRemoveAssociationPayload(string $crmId, array $ids): array\n {\n $toArray = [];\n foreach ($ids as $id) {\n if ($id === null || $id === '') {\n continue;\n }\n\n $toArray[] = ['id' => (string) $id];\n }\n\n return [\n 'inputs' => [\n [\n 'from' => ['id' => $crmId],\n 'to' => $toArray,\n ],\n ],\n ];\n }\n\n public function addClosedStageFilters(array &$payload, array $closedStages): void\n {\n if (! empty($closedStages['won'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['won'],\n ];\n }\n\n if (! empty($closedStages['lost'])) {\n $payload['filters'][] = [\n 'propertyName' => 'dealstage',\n 'operator' => 'NOT_IN',\n 'values' => $closedStages['lost'],\n ];\n }\n }\n\n public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void\n {\n $payload['filters'][] = [\n 'propertyName' => 'createdate',\n 'operator' => 'GT',\n 'value' => $createdAfter->getPreciseTimestamp(3),\n ];\n }\n\n public function getDealsInBulkPayload(array $dealIds): array\n {\n return [\n 'filterGroups' => [\n [\n 'filters' => [\n [\n 'propertyName' => 'hs_object_id',\n 'operator' => 'IN',\n 'values' => $dealIds,\n ],\n ],\n ],\n ],\n 'limit' => self::MAX_FILTER_SIZE,\n ];\n }\n}","role_description":"text entry area","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":"22","depth":4,"on_screen":true,"role_description":"text"},{"role":"AXStaticText","text":"8","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}]...
|
4825528308983474919
|
1347515447572118148
|
typing_pause
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#12121 on JY-20963-fix-im Project: faVsco.js, menu
#12121 on JY-20963-fix-import-on-deleted-entity, menu
Start Listening for PHP Debug Connections
ServiceTest
Run 'ServiceTest'
Debug 'ServiceTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
25
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Jiminny\Models\Crm\Configuration;
use Psr\Log\LoggerInterface;
class PayloadBuilder
{
public const int MAX_SEARCH_REQUEST_LIMIT = 200;
private const int MAX_FILTER_SIZE = 100;
private const string SORT_PROPERTY = 'hs_timestamp';
private const string ENGAGEMENT_MEETINGS = 'meetings';
public function getLinkToTaskPayload(string $objectType, string $objectId, string $engagementType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($engagementType === self::ENGAGEMENT_MEETINGS) {
$payload['filterGroups'] = $this->buildMeetingFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_timestamp',
'hs_activity_type',
];
} else {
$payload['filterGroups'] = $this->buildTaskFiltersForLinkToTask($objectType, $objectId);
$payload['properties'] = ['hs_task_subject', 'hs_timestamp'];
}
return $payload;
}
public function getRecentlyUpdatedSearchPayload(Carbon $since, ?Carbon $to, array $properties): array
{
$lastUpdateDate = in_array('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
public function getByProfileSearchPayload(string $crmId, array $properties, Carbon $since, ?Carbon $to): array
{
$lastUpdateDate = array_key_exists('firstname', $properties) ? 'lastmodifieddate' : 'hs_lastmodifieddate';
$payload = [
'filters' => [
[
'propertyName' => $lastUpdateDate,
'operator' => 'GT',
'value' => $since->getPreciseTimestamp(3),
],
[
'propertyName' => 'hubspot_owner_id',
'operator' => 'EQ',
'value' => $crmId,
],
],
'sorts' => [
[
'propertyName' => 'hs_object_id',
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($to) {
$payload['filters'][] = [
'propertyName' => $lastUpdateDate,
'operator' => 'LT',
'value' => $to->getPreciseTimestamp(3),
];
}
$payload['properties'] = $properties;
return $payload;
}
private function buildMeetingFiltersForLinkToTask($objectType, $objectId): array
{
$filters = [];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'IN',
'values' => ['SCHEDULED', 'RESCHEDULED'],
],
],
];
$filters[] = [
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
[
'propertyName' => 'hs_meeting_outcome',
'operator' => 'NOT_HAS_PROPERTY',
],
],
];
return $filters;
}
private function buildTaskFiltersForLinkToTask($objectType, $objectId): array
{
return [
[
'filters' => [
$this->getAssociatedObjectFilter($objectType, $objectId),
],
],
];
}
private function getAssociatedObjectFilter(string $objectType, string $objectId): array
{
return [
'propertyName' => 'associations.' . $objectType,
'operator' => 'EQ',
'value' => $objectId,
];
}
public function generatePlaybackURLSearchPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
public function generateGetCallsPayload(Carbon $from, Carbon $to, string $activityProvider, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $activityProvider,
],
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function generateSearchCallsByPeriodPayload(Carbon $from, Carbon $to, $page): array
{
return [
'filters' => [
[
'propertyName' => 'hs_timestamp',
'operator' => 'BETWEEN',
'value' => intval($from->getPreciseTimestamp(3)),
'highValue' => intval($to->getPreciseTimestamp(3)),
],
],
'sorts' => [
[
'propertyName' => 'hs_timestamp',
'direction' => 'DESCENDING',
],
],
'properties' => $this->getSearchCallAttributes(),
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
'after' => ($page - 1) * self::MAX_SEARCH_REQUEST_LIMIT,
];
}
public function getSearchCallAttributes(): array
{
return [
'hs_timestamp',
'hs_call_recording_url',
'hs_call_body',
'hs_call_status',
'hs_call_to_number',
'hs_call_from_number',
'hs_call_duration',
'hs_call_disposition',
'hs_call_title',
'hs_call_direction',
'hubspot_owner_id',
'hs_activity_type',
'hs_call_external_id',
'hs_call_source',
];
}
public function generatePlaybackAddUrlBatchPayload(array $crmUpdateData): array
{
$updateObjectsData = [];
foreach ($crmUpdateData as $data) {
$updateObjectsData[] = [
'id' => $data['crm_id'],
'properties' => [
'hs_call_body' => $data['hs_call_body'] .
'<p><span style="font-size: 13.3333px; line-height: 16px;">' .
'<a href="' . $data['playback_url'] . '" target="_blank">Review in Jiminny</a> ▶️</span></p>',
],
];
}
return ['inputs' => $updateObjectsData];
}
public function generateSearchCallByTokenPayload(string $playbackURLToken): array
{
return [
'filters' => [
[
'propertyName' => 'hs_call_recording_url',
'operator' => 'CONTAINS_TOKEN',
'value' => $playbackURLToken,
],
],
'properties' => [
'hs_call_recording_url',
'hs_call_body',
],
'limit' => 1,
];
}
/**
* Generates a payload for phone search based on the specified parameters.
*
* @param string $phone The phone number to search.
* @param bool $isAlternativeSearch Indicates if an alternative search should be performed
* if the first search fails to find a match. The first search request should cover most of the cases.
*/
public function generatePhoneSearchPayload(string $phone, bool $isAlternativeSearch = false): array
{
$filterPropertyNames = $isAlternativeSearch ?
['hs_searchable_calculated_mobile_number', 'phone', 'mobilephone'] :
['hs_searchable_calculated_phone_number', 'hs_calculated_phone_number', 'hs_calculated_mobile_number'];
$filterGroups = array_map(function ($propertyName) use ($phone) {
return $this->createFilterGroup($propertyName, 'CONTAINS_TOKEN', $phone);
}, $filterPropertyNames);
$properties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
return $this->createPayload($filterGroups, $properties);
}
/**
* Creates a filter group with the specified parameters.
*/
private function createFilterGroup(string $propertyName, string $operator, $value): array
{
return [
'filters' => [
[
'propertyName' => $propertyName,
'operator' => $operator,
'value' => $value,
],
],
];
}
/**
* Creates a payload with the specified filter groups and properties.
*/
private function createPayload(array $filterGroups, array $properties): array
{
return [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => 'modifieddate',
'direction' => 'DESCENDING',
],
],
'properties' => $properties,
'limit' => 1,
];
}
/**
* Generates a payload to find related activities based on the specified data and object type.
* The search looks for activities that match the specified time range (starttime - endtime or only starttime with endtime not set)
* and are associated with any of the provided prospect types (contact or company).
*
* @param array $data An associative array containing the following keys:
* - 'from': The start time for the activity search (timestamp).
* - 'to': The end time for the activity search (timestamp).
* - 'contact': (optional) The ID of the associated contact.
* - 'company': (optional) The ID of the associated company.
* @param string $objectType The type of engagement to search for (meeting or other type like call).
*
* @return array The payload array to be used for searching related activities.
*/
public function getFindRelatedActivityPayload(array $data, string $objectType): array
{
$payload = [
'sorts' => [
[
'propertyName' => self::SORT_PROPERTY,
'direction' => 'DESCENDING',
],
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
if ($objectType === self::ENGAGEMENT_MEETINGS) {
$payload['properties'] = [
'hs_meeting_title',
'hs_meeting_outcome',
'hs_activity_type',
'hs_timestamp',
'hubspot_owner_id',
'hs_meeting_body',
'hs_internal_meeting_notes',
'hs_meeting_location',
'hs_meeting_start_time',
'hs_meeting_end_time',
];
} else {
$payload['properties'] = ['hs_task_subject', 'hs_timestamp', 'hubspot_owner_id', 'hs_call_body'];
}
$timeFiltersWithEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'LTE',
'value' => $data['to'],
],
];
$timeFiltersWithoutEndTime = [
[
'propertyName' => 'hs_meeting_start_time',
'operator' => 'GTE',
'value' => $data['from'],
],
[
'propertyName' => 'hs_meeting_end_time',
'operator' => 'NOT_HAS_PROPERTY',
],
];
$payload['filterGroups'] = [];
$associationTypes = ['contact', 'company'];
foreach ($associationTypes as $type) {
if (! empty($data[$type])) {
$filterGroupWithEndTime = [
'filters' => array_merge(
$timeFiltersWithEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithEndTime;
$filterGroupWithoutEndTime = [
'filters' => array_merge(
$timeFiltersWithoutEndTime,
[$this->getAssociatedObjectFilter($type, $data[$type])]
),
];
$payload['filterGroups'][] = $filterGroupWithoutEndTime ;
}
}
return $payload;
}
/** Parameters
* [
* 'accountId' => $crmAccountId,
* 'sortBy' => $sortBy,
* 'sortDir' => $sortDir,
* 'onlyOpen' => $onlyOpen,
* 'closedStages' => $this->getClosedDealStages(),
* 'userId' => $userId,
* ];
*/
public function generateOpportunitiesSearchPayload(
Configuration $config,
string $crmAccountId,
array $closedStages,
): array {
$closedFilters = [];
$filterGroups = [];
$onlyOpen = true;
switch ($config->getOpportunityAssignmentRule()) {
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_UPDATED:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_RECENTLY_CREATED:
$sortBy = 'createdate';
$sortDir = 'DESCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_OPEN_OLDEST_CREATED:
$sortBy = 'createdate';
$sortDir = 'ASCENDING';
break;
case Configuration::OPP_ASSIGNMENT_ALL_RECENTLY_UPDATED:
default:
$sortBy = 'modifieddate';
$sortDir = 'DESCENDING';
$onlyOpen = false;
}
$baseFilters = [
[
'propertyName' => 'associations.company',
'operator' => 'EQ',
'value' => $crmAccountId,
],
];
// Handle closed stages in chunks
if ($onlyOpen) {
foreach (['won', 'lost'] as $key) {
if (! empty($closedStages[$key])) {
$chunks = array_chunk($closedStages[$key], self::MAX_FILTER_SIZE);
foreach ($chunks as $chunk) {
$closedFilters[] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $chunk,
];
}
}
}
}
$filterGroups[] = [
'filters' => array_merge($baseFilters, $closedFilters),
];
$payload = [
'filterGroups' => $filterGroups,
'sorts' => [
[
'propertyName' => $sortBy,
'direction' => $sortDir,
],
],
'properties' => [
'dealname',
'amount',
'hubspot_owner_id',
'pipeline',
'dealstage',
'closedate',
'deal_currency_code',
],
'limit' => self::MAX_SEARCH_REQUEST_LIMIT,
];
$logger = app(LoggerInterface::class);
$logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
return $payload;
}
/**
* Converts v1 payload data to v3
*/
public function getV3MeetingPayload(array $engagement, array $metadata, array $associations = []): array
{
// Use this mapping until the whole Hubspot V1 is dropped.
$properties = [
'hubspot_owner_id' => $engagement['ownerId'],
'hs_timestamp' => $engagement['timestamp'],
];
// $engagement['activityType'] is $activity->category->name
if (isset($engagement['activityType'])) {
$properties['hs_activity_type'] = $engagement['activityType'];
}
$metadataKeyMap = [
'hs_meeting_outcome' => 'meetingOutcome',
'hs_meeting_title' => 'title',
'hs_meeting_start_time' => 'startTime',
'hs_meeting_end_time' => 'endTime',
'hs_meeting_body' => 'body',
'hs_internal_meeting_notes' => 'internalMeetingNotes',
];
foreach ($metadataKeyMap as $newKey => $oldKey) {
if (isset($metadata[$oldKey])) {
$properties[$newKey] = $metadata[$oldKey];
unset($metadata[$oldKey]);
}
}
$properties = [
...$properties,
...$metadata, // custom fields
];
$response = [
'properties' => $properties,
];
if (! empty($associations)) {
$response['associations'] = $associations;
}
return $response;
}
/**
* Generate a payload to search for contacts by name.
* The search is a token search in firstname or lastname
*/
public function generateSearchContactsByNamePayload(string $name, array $fields): array
{
$firstNameFilter = [
'propertyName' => 'firstname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
$lastNameFilter = [
'propertyName' => 'lastname',
'operator' => 'CONTAINS_TOKEN',
'value' => $name,
];
return [
'filterGroups' => [
[
'filters' => [$firstNameFilter],
],
[
'filters' => [$lastNameFilter],
],
],
'properties' => $fields,
'sorts' => [
[
'propertyName' => 'lastmodifieddate',
'direction' => 'DESCENDING',
],
],
];
}
public function buildAddAssociationPayload(string $crmId, array $ids, int $associationType): array
{
$inputs = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$inputs[] = [
'from' => [
'id' => $crmId,
],
'to' => [
'id' => (string) $id,
],
'types' => [
[
'associationCategory' => 'HUBSPOT_DEFINED',
'associationTypeId' => $associationType,
],
],
];
}
return ['inputs' => $inputs];
}
public function buildRemoveAssociationPayload(string $crmId, array $ids): array
{
$toArray = [];
foreach ($ids as $id) {
if ($id === null || $id === '') {
continue;
}
$toArray[] = ['id' => (string) $id];
}
return [
'inputs' => [
[
'from' => ['id' => $crmId],
'to' => $toArray,
],
],
];
}
public function addClosedStageFilters(array &$payload, array $closedStages): void
{
if (! empty($closedStages['won'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['won'],
];
}
if (! empty($closedStages['lost'])) {
$payload['filters'][] = [
'propertyName' => 'dealstage',
'operator' => 'NOT_IN',
'values' => $closedStages['lost'],
];
}
}
public function addCreatedDateFilters(array &$payload, Carbon $createdAfter): void
{
$payload['filters'][] = [
'propertyName' => 'createdate',
'operator' => 'GT',
'value' => $createdAfter->getPreciseTimestamp(3),
];
}
public function getDealsInBulkPayload(array $dealIds): array
{
return [
'filterGroups' => [
[
'filters' => [
[
'propertyName' => 'hs_object_id',
'operator' => 'IN',
'values' => $dealIds,
],
],
],
],
'limit' => self::MAX_FILTER_SIZE,
];
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
22
8
Previous Highlighted Error
Next Highlighted Error...
|
87890
|
NULL
|
NULL
|
NULL
|