|
43849
|
NULL
|
0
|
2026-04-17T08:23:31.475871+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776414211475_m1.jpg...
|
Firefox
|
Developer Overview | HubSpot — Work
|
1
|
app.hubspot.com/developer-overview/2752939
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Workers | Datadog
Developer Overview | HubSpot
Dev Workers | Datadog
Developer Overview | HubSpot
Developer Overview | HubSpot
Close tab
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
New Tab
Customize sidebar
Open Google Gemini (⌃X)
Tabs from other devices
Open history (⇧⌘H)
Open bookmarks (⌘B)
HubSpot logo
Find or Ask
⌘
K
Create new
Scroll up
Scroll down
Development
Development
Overview
Projects
Legacy Apps
MCP Auth Apps BETA...
|
[{"role":"AXRadioButton","text [{"role":"AXRadioButton","text":"Workers | Datadog","depth":4,"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXRadioButton","text":"Developer Overview | HubSpot","depth":4,"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":true},{"role":"AXStaticText","text":"Developer Overview | HubSpot","depth":5,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Close tab","depth":5,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXRadioButton","text":"Inbox (1,574) - lukas.kovalik@jiminny.com - Jiminny Mail","depth":4,"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Inbox (1,574) - lukas.kovalik@jiminny.com - Jiminny Mail","depth":5,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXRadioButton","text":"Inbox (3,737) - integration-account@jiminny.com - Jiminny Mail","depth":4,"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Inbox (3,737) - integration-account@jiminny.com - Jiminny Mail","depth":5,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"New Tab","depth":4,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Customize sidebar","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open Google Gemini (⌃X)","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Tabs from other devices","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open history (⇧⌘H)","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open bookmarks (⌘B)","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXLink","text":"HubSpot logo","depth":9,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXTextField","text":"Find or Ask","depth":11,"help_text":"","role_description":"search text field","subrole":"AXSearchField","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"⌘","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"K","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXMenuButton","text":"Create new","depth":9,"help_text":"","role_description":"menu button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXButton","text":"Scroll up","depth":9,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXButton","text":"Scroll down","depth":9,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXHeading","text":"Development","depth":11,"help_text":"","role_description":"heading","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Development","depth":12,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Overview","depth":15,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":true},{"role":"AXButton","text":"Projects","depth":15,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Legacy Apps","depth":15,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"MCP Auth Apps BETA","depth":15,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-2009434685097271836
|
-4842062826464464508
|
visual_change
|
accessibility
|
NULL
|
Workers | Datadog
Developer Overview | HubSpot
Dev Workers | Datadog
Developer Overview | HubSpot
Developer Overview | HubSpot
Close tab
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
New Tab
Customize sidebar
Open Google Gemini (⌃X)
Tabs from other devices
Open history (⇧⌘H)
Open bookmarks (⌘B)
HubSpot logo
Find or Ask
⌘
K
Create new
Scroll up
Scroll down
Development
Development
Overview
Projects
Legacy Apps
MCP Auth Apps BETA...
|
43848
|
|
43851
|
929
|
0
|
2026-04-17T08:23:32.886658+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776414212886_m1.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
FirefoxFileEditViewHistoryBookmarksProfilesToolsWi FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelpmeet.google.com/xpx-omah-rkn‹$0lthlBackend Chapter • 7 m left100% <78 • Fri 17 Apr 11:23:326=+llian Kyuchukov (Presenting, annotating)BraveProfilesHelp• • Q 8• Fri17 Apr 11:23.turee outino orat ohl te poo@ DEV Jiminny© PROD Jminehttps//us-east-2.console.aws.amazon.com/cloudwatch/home?regionsus-east-2#logsV2:logs-insights53FqueryDetallS3D-(en…O PROD EU JiminnyQ My PRSQ Assigned• To Review( Jminny Prophet W. Pipelines - jminny- JRA OpenAl Platform83 Confluence(7 Service-Desk - Qu l Sentry@ AWS|aws[Option+S) ©4United States (Ohio) •[ All Bookmarkst ID: 4103-4619-5943n.View_Only @ inCloudWatchLogs Insights >Generall.. Id0416|oeréoeneU4io0417o4170417Q Filter toble resutts (cose insensitive).ftinestomoPnessogePentity.KeyAttributes.EnvironnentRons.occount|fons.regionedota_fornotcoos anannyoopproopetanadee43034015491us-east-2Defaultedata_sounce_nomeedoto_sounce_typeUnknownPenelty-Attributes.Ans, servi cenohesource servertonko tefentity.Attributes.ECS.ClusterJiminny-app-prod-optinizedfentity.Attributes.PlatfornTypeANS: :ECSFingestionTine1776413247734Plog410346195943:php-app#logGroupld9d68361f-1701-4851-95b0-7632885a496ePlogStreomphp-app/php-app/0603550686Sc449dada89efd23893ece LelogStreanid90683611-1781-4851-9506-76328856496e:12C3e66555bbac260103252781862cc®ecBect7663bctf8796e9ce1S011798083:11776411877725enessogeNOTICE: PHP nessage: (2926-84-17 08:07:26] production.INFO: [HubSpot Webhook] Event received ("payload":(("event]d": 2959662780, "subscription]d":5810880, "portalI6"':3364459, "app1d": 38484, "occurredAt":1776413118936, "subscriptionType":"contact-propertyChange", "attenptNunber":0, "objectld" :216060749891, "pro("eventId":4242069661, "subscription]d": 5810869, "portalId": 395241, "appId": 38484, "occurredAt":1776413235382, "subscriptionType":"contact-propertyChange", "attenptNumber":8, "objectId":216874968493, "prope("eventId": 3655207192, "subscriptionid":5810871, "portalId":21336723, "appId": 38484, "occurredAt* :1776413245878, "subscriptionType":"contact,propertyChange", "attenptNunber":0, "objectId":216135984687, "prc("eventId" :912983653, "subscription]d":5810874, "portal6" :21336723, "app16":38484, "occurredAt" :1776413245876, "subscriptionType" :"contact-propertyChange", "attenptNunber" :0, "objectid" :216135984687, "pror("eventId": 366780809, "subscriptionid": 5810866, "portalId":21336723, "app1d":38484, "occurredAt":1776413245878, "subscriptionType":"contact-propertyChange", "attenptNumber":0, "objectid":216135984687, "pror("eventI": 2816766982, "subscription1d": 5810889, "portal16*:21306723, "app1d":38484, "occurredAt":1776413245870, "subscriptionType":"contact,creation", "attenptNunber":0,"objectI6":216133984687, "changefle("eventId":1594195957, *subscriptionId*: 5810867, "portalId":21336723, "app1d": 38484, "occurredAt* :1776413245870, "subscriptionType":"contact,propertyChange", "attemptNunber*:0, "objectld":216135984687, "pre("eventId" : 3736157241, "subscription]d":S810884, "portalI6":8383935, "app1d": 38484, "occurredAt*:1776413246190, "subscriptionType":"company-propertyChange", "attenptNunber":8, "object1d" :9366149545, "proper("eventId" :947911117, "subscription]d*:5810882, "portalI6"':8883935, "appId" : 38484, "occurredAt*11776413246128, "subscriptionType":"company-propertyChange", "attenptNunber*:8, *objectI6° :15431137609, "propen("correlation_1d":*9d3cS1Sc-f131-48cf-Bacf-15923b8cc887*, "trace_1d":"b134acde-d433-4a8e-886d-796d588de21a*)|41104834903E CloudShell2026-84-17711:07:26.383+-2026-04-17T11:02:28.674+-FeedbackNOTICE: PHP messoge: (2826-04-17 88:87:26) production. INFO:[HubSpot, Mebhook) Event received ("paylood":[("event.Id"' :2130317583, "subscriptionid"': 5810880, "portolId" : 6649755, "opp1a" : 38434, "occurredat* :177641- €NOTICE: PHP messoge:[2826-04-17 08:82:28] production. INFO:(HubSpot, Mebhook] Event received ("paylood": [["eventId" :1311683594, "subscriptionId": S818869, "portalId" : 3364459, "oppla' :38484, "occurredAt* : 177641 €© 2026, Amazon Web Services, Inc. or its affilates.2024-11_6.56.png...NVasil Vasilevllian KyuchukovMihail MihaylovNikolay NikolovLukas Kovalik11:23 AM | Daily - ProcessingLộ3...
|
NULL
|
-6393224708905149227
|
NULL
|
click
|
ocr
|
NULL
|
FirefoxFileEditViewHistoryBookmarksProfilesToolsWi FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelpmeet.google.com/xpx-omah-rkn‹$0lthlBackend Chapter • 7 m left100% <78 • Fri 17 Apr 11:23:326=+llian Kyuchukov (Presenting, annotating)BraveProfilesHelp• • Q 8• Fri17 Apr 11:23.turee outino orat ohl te poo@ DEV Jiminny© PROD Jminehttps//us-east-2.console.aws.amazon.com/cloudwatch/home?regionsus-east-2#logsV2:logs-insights53FqueryDetallS3D-(en…O PROD EU JiminnyQ My PRSQ Assigned• To Review( Jminny Prophet W. Pipelines - jminny- JRA OpenAl Platform83 Confluence(7 Service-Desk - Qu l Sentry@ AWS|aws[Option+S) ©4United States (Ohio) •[ All Bookmarkst ID: 4103-4619-5943n.View_Only @ inCloudWatchLogs Insights >Generall.. Id0416|oeréoeneU4io0417o4170417Q Filter toble resutts (cose insensitive).ftinestomoPnessogePentity.KeyAttributes.EnvironnentRons.occount|fons.regionedota_fornotcoos anannyoopproopetanadee43034015491us-east-2Defaultedata_sounce_nomeedoto_sounce_typeUnknownPenelty-Attributes.Ans, servi cenohesource servertonko tefentity.Attributes.ECS.ClusterJiminny-app-prod-optinizedfentity.Attributes.PlatfornTypeANS: :ECSFingestionTine1776413247734Plog410346195943:php-app#logGroupld9d68361f-1701-4851-95b0-7632885a496ePlogStreomphp-app/php-app/0603550686Sc449dada89efd23893ece LelogStreanid90683611-1781-4851-9506-76328856496e:12C3e66555bbac260103252781862cc®ecBect7663bctf8796e9ce1S011798083:11776411877725enessogeNOTICE: PHP nessage: (2926-84-17 08:07:26] production.INFO: [HubSpot Webhook] Event received ("payload":(("event]d": 2959662780, "subscription]d":5810880, "portalI6"':3364459, "app1d": 38484, "occurredAt":1776413118936, "subscriptionType":"contact-propertyChange", "attenptNunber":0, "objectld" :216060749891, "pro("eventId":4242069661, "subscription]d": 5810869, "portalId": 395241, "appId": 38484, "occurredAt":1776413235382, "subscriptionType":"contact-propertyChange", "attenptNumber":8, "objectId":216874968493, "prope("eventId": 3655207192, "subscriptionid":5810871, "portalId":21336723, "appId": 38484, "occurredAt* :1776413245878, "subscriptionType":"contact,propertyChange", "attenptNunber":0, "objectId":216135984687, "prc("eventId" :912983653, "subscription]d":5810874, "portal6" :21336723, "app16":38484, "occurredAt" :1776413245876, "subscriptionType" :"contact-propertyChange", "attenptNunber" :0, "objectid" :216135984687, "pror("eventId": 366780809, "subscriptionid": 5810866, "portalId":21336723, "app1d":38484, "occurredAt":1776413245878, "subscriptionType":"contact-propertyChange", "attenptNumber":0, "objectid":216135984687, "pror("eventI": 2816766982, "subscription1d": 5810889, "portal16*:21306723, "app1d":38484, "occurredAt":1776413245870, "subscriptionType":"contact,creation", "attenptNunber":0,"objectI6":216133984687, "changefle("eventId":1594195957, *subscriptionId*: 5810867, "portalId":21336723, "app1d": 38484, "occurredAt* :1776413245870, "subscriptionType":"contact,propertyChange", "attemptNunber*:0, "objectld":216135984687, "pre("eventId" : 3736157241, "subscription]d":S810884, "portalI6":8383935, "app1d": 38484, "occurredAt*:1776413246190, "subscriptionType":"company-propertyChange", "attenptNunber":8, "object1d" :9366149545, "proper("eventId" :947911117, "subscription]d*:5810882, "portalI6"':8883935, "appId" : 38484, "occurredAt*11776413246128, "subscriptionType":"company-propertyChange", "attenptNunber*:8, *objectI6° :15431137609, "propen("correlation_1d":*9d3cS1Sc-f131-48cf-Bacf-15923b8cc887*, "trace_1d":"b134acde-d433-4a8e-886d-796d588de21a*)|41104834903E CloudShell2026-84-17711:07:26.383+-2026-04-17T11:02:28.674+-FeedbackNOTICE: PHP messoge: (2826-04-17 88:87:26) production. INFO:[HubSpot, Mebhook) Event received ("paylood":[("event.Id"' :2130317583, "subscriptionid"': 5810880, "portolId" : 6649755, "opp1a" : 38434, "occurredat* :177641- €NOTICE: PHP messoge:[2826-04-17 08:82:28] production. INFO:(HubSpot, Mebhook] Event received ("paylood": [["eventId" :1311683594, "subscriptionId": S818869, "portalId" : 3364459, "oppla' :38484, "occurredAt* : 177641 €© 2026, Amazon Web Services, Inc. or its affilates.2024-11_6.56.png...NVasil Vasilevllian KyuchukovMihail MihaylovNikolay NikolovLukas Kovalik11:23 AM | Daily - ProcessingLộ3...
|
NULL
|
|
43865
|
NULL
|
0
|
2026-04-17T08:23:51.034927+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776414231034_m1.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
FirefoxFileEditViewHistoryBookmarksProfilesToolsWi FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelp‹$0lthlBackend Chapter • 7 m left100% <478 • Fri 17 Apr 11:23:50meet.google.com/xpx-omah-rkn6+llian Kyuchukov (Presenting, annotating)BraveViewProfilesHelp• Q 88• Fri17 Apr 11:23.ttreounino orateroldeoeCloudWatch | us-east-2@ DEV Jiminmyhttps//us-east-2.console.aws.amazon.com/cloudwatch/home?regionsus-east-2#logsV2:logs-insightsS3FqueryDetallS3D-(enO PROD EU JiminnyQ My PRS• Assigned• To ReviewJiminny Prophet W.Pipelines - jiminey- JRAOpenAl Platform83 Confluence(7 Service-Desk - Qu.Sentry@ AWS|[ All Bookmarksaws(Option+S) ©4United States (Ohio) •2.Vien_Only ® IgLogs InsightsOeneral• Query definition30mCustom (1d) ECompare (Off)Local timezoneStart tailingQuery scopeProperty selectorSelect up to 50 log groupsBrowse. Log Groups Pacets Lookup tablesCicar allE Show more chosen log groups (+1)|fields etinestanp, enessage, elogStrean, elogI filter @nessage like ""portalId":3364459'sorteestaso descVasil Vasilevllian KyuchukovLogs Insights QL½ Query generatorQ Fields_ Saveo ano sampie queniesRun queryCancelupoate seycocuery• Completed. Query executed for 2 log groups. ©Schedule queryLogs (159)Logs (159)04/16®CoudshulPatterns (32)04/16© Query commandsMihail MihaylovNikolay NikolovShowing 159 of 159 records matched O6,391,331 records (2.0 GB) scanned in 4.3s @ 1,480,502 records/s (465.6 MB/s)|04/16омль04/7604/1604/17E Share results04/17|04/17O zotl, Amazon Weo Services, Inc, of its amdates04/1704/17Setssnthot2024-11.6.56.pngLukas Kovalik11:23 AM | Daily - Processing...
|
NULL
|
2988071006371002638
|
NULL
|
click
|
ocr
|
NULL
|
FirefoxFileEditViewHistoryBookmarksProfilesToolsWi FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelp‹$0lthlBackend Chapter • 7 m left100% <478 • Fri 17 Apr 11:23:50meet.google.com/xpx-omah-rkn6+llian Kyuchukov (Presenting, annotating)BraveViewProfilesHelp• Q 88• Fri17 Apr 11:23.ttreounino orateroldeoeCloudWatch | us-east-2@ DEV Jiminmyhttps//us-east-2.console.aws.amazon.com/cloudwatch/home?regionsus-east-2#logsV2:logs-insightsS3FqueryDetallS3D-(enO PROD EU JiminnyQ My PRS• Assigned• To ReviewJiminny Prophet W.Pipelines - jiminey- JRAOpenAl Platform83 Confluence(7 Service-Desk - Qu.Sentry@ AWS|[ All Bookmarksaws(Option+S) ©4United States (Ohio) •2.Vien_Only ® IgLogs InsightsOeneral• Query definition30mCustom (1d) ECompare (Off)Local timezoneStart tailingQuery scopeProperty selectorSelect up to 50 log groupsBrowse. Log Groups Pacets Lookup tablesCicar allE Show more chosen log groups (+1)|fields etinestanp, enessage, elogStrean, elogI filter @nessage like ""portalId":3364459'sorteestaso descVasil Vasilevllian KyuchukovLogs Insights QL½ Query generatorQ Fields_ Saveo ano sampie queniesRun queryCancelupoate seycocuery• Completed. Query executed for 2 log groups. ©Schedule queryLogs (159)Logs (159)04/16®CoudshulPatterns (32)04/16© Query commandsMihail MihaylovNikolay NikolovShowing 159 of 159 records matched O6,391,331 records (2.0 GB) scanned in 4.3s @ 1,480,502 records/s (465.6 MB/s)|04/16омль04/7604/1604/17E Share results04/17|04/17O zotl, Amazon Weo Services, Inc, of its amdates04/1704/17Setssnthot2024-11.6.56.pngLukas Kovalik11:23 AM | Daily - Processing...
|
43863
|
|
43866
|
NULL
|
0
|
2026-04-17T08:23:53.471124+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776414233471_m2.jpg...
|
Firefox
|
API Call Usage — Work
|
1
|
app.hubspot.com/api-call-usage/2752939
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Workers | Datadog
API Call Usage
API Call Usage
Cl Workers | Datadog
API Call Usage
API Call Usage
Close tab
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
New Tab
Customize sidebar
Open Google Gemini (⌃X)
Tabs from other devices
Open history (⇧⌘H)
Open bookmarks (⌘B)
Development
Development
Loading
API Call Usage
API Call Usage
The number of API calls made in the past 24 hours by privately distributed apps and service keys on this account.
Loading data
Loading
Loading
Read static.hsappstatic.net...
|
[{"role":"AXRadioButton","text [{"role":"AXRadioButton","text":"Workers | Datadog","depth":4,"bounds":{"left":0.00234375,"top":0.045138888,"width":0.0890625,"height":0.028472222},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXRadioButton","text":"API Call Usage","depth":4,"bounds":{"left":0.0,"top":0.08263889,"width":0.09375,"height":0.028472222},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":true},{"role":"AXStaticText","text":"API Call Usage","depth":5,"bounds":{"left":0.015625,"top":0.09236111,"width":0.030078124,"height":0.009722223},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Close tab","depth":5,"bounds":{"left":0.07890625,"top":0.08888889,"width":0.009375,"height":0.016666668},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXRadioButton","text":"Inbox (1,574) - lukas.kovalik@jiminny.com - Jiminny Mail","depth":4,"bounds":{"left":0.0,"top":0.11111111,"width":0.09375,"height":0.028472222},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Inbox (1,574) - lukas.kovalik@jiminny.com - Jiminny Mail","depth":5,"bounds":{"left":0.015625,"top":0.12083333,"width":0.11445312,"height":0.009722223},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXRadioButton","text":"Inbox (3,737) - integration-account@jiminny.com - Jiminny Mail","depth":4,"bounds":{"left":0.0,"top":0.13958333,"width":0.09375,"height":0.028472222},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Inbox (3,737) - integration-account@jiminny.com - Jiminny Mail","depth":5,"bounds":{"left":0.015625,"top":0.14930555,"width":0.1296875,"height":0.009722223},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"New Tab","depth":4,"bounds":{"left":0.003125,"top":0.16944444,"width":0.08710937,"height":0.022222223},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Customize sidebar","depth":6,"bounds":{"left":0.003125,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open Google Gemini (⌃X)","depth":6,"bounds":{"left":0.01640625,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Tabs from other devices","depth":6,"bounds":{"left":0.029296875,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open history (⇧⌘H)","depth":6,"bounds":{"left":0.0421875,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open bookmarks (⌘B)","depth":6,"bounds":{"left":0.05546875,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXHeading","text":"Development","depth":10,"bounds":{"left":0.13125,"top":0.103472225,"width":0.075,"height":0.016666668},"help_text":"","role_description":"heading","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Development","depth":11,"bounds":{"left":0.13125,"top":0.103472225,"width":0.0515625,"height":0.017361112},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Loading","depth":12,"bounds":{"left":0.16875,"top":0.16111112,"width":0.019921875,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXHeading","text":"API Call Usage","depth":11,"bounds":{"left":0.25507814,"top":0.10555556,"width":0.055078126,"height":0.016666668},"help_text":"","role_description":"heading","subrole":"AXUnknown"},{"role":"AXStaticText","text":"API Call Usage","depth":12,"bounds":{"left":0.25507814,"top":0.10555556,"width":0.055078126,"height":0.017361112},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"The number of API calls made in the past 24 hours by privately distributed apps and service keys on this account.","depth":12,"bounds":{"left":0.25507814,"top":0.15625,"width":0.2878906,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Loading data","depth":13,"bounds":{"left":0.48828125,"top":0.20902778,"width":0.033203125,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Loading","depth":13,"bounds":{"left":0.25820312,"top":0.2534722,"width":0.019921875,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Loading","depth":13,"bounds":{"left":0.5097656,"top":0.2534722,"width":0.019921875,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Read static.hsappstatic.net","depth":5,"bounds":{"left":0.0953125,"top":0.98888886,"width":0.055859376,"height":0.009722223},"help_text":"","role_description":"text","subrole":"AXUnknown"}]...
|
5178420899094594917
|
-7475432564107955260
|
visual_change
|
accessibility
|
NULL
|
Workers | Datadog
API Call Usage
API Call Usage
Cl Workers | Datadog
API Call Usage
API Call Usage
Close tab
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
New Tab
Customize sidebar
Open Google Gemini (⌃X)
Tabs from other devices
Open history (⇧⌘H)
Open bookmarks (⌘B)
Development
Development
Loading
API Call Usage
API Call Usage
The number of API calls made in the past 24 hours by privately distributed apps and service keys on this account.
Loading data
Loading
Loading
Read static.hsappstatic.net...
|
43864
|
|
43867
|
931
|
0
|
2026-04-17T08:23:56.670865+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776414236670_m1.jpg...
|
Firefox
|
API Call Usage — Work
|
1
|
app.hubspot.com/api-call-usage/2752939
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Workers | Datadog
API Call Usage
API Call Usage
Cl Workers | Datadog
API Call Usage
API Call Usage
Close tab
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
New Tab
Customize sidebar
Open Google Gemini (⌃X)
Tabs from other devices
Open history (⇧⌘H)
Open bookmarks (⌘B)
HubSpot logo
Find or Ask
⌘
K
Create new
Scroll up
Scroll down
Development
Development
Overview
Projects
Legacy Apps
MCP Auth Apps BETA
MCP Auth Apps
BETA
Design Manager
Monitoring
Monitoring
Logs
API Call Usage
Keys
Testing
Domain
App Listings
Technology Partner
Documentation
Documentation
API Call Usage
API Call Usage
The number of API calls made in the past 24 hours by privately distributed apps and service keys on this account.
0/250,000
calls
0%
API call counts reset at midnight
Last updated
in a few seconds
.
Apps & Service Keys Built Here
Apps & Service Keys Built Here
0
0%
Third Party Apps
Third Party Apps
0
0%...
|
[{"role":"AXRadioButton","text [{"role":"AXRadioButton","text":"Workers | Datadog","depth":4,"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXRadioButton","text":"API Call Usage","depth":4,"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":true},{"role":"AXStaticText","text":"API Call Usage","depth":5,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Close tab","depth":5,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXRadioButton","text":"Inbox (1,574) - lukas.kovalik@jiminny.com - Jiminny Mail","depth":4,"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Inbox (1,574) - lukas.kovalik@jiminny.com - Jiminny Mail","depth":5,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXRadioButton","text":"Inbox (3,737) - integration-account@jiminny.com - Jiminny Mail","depth":4,"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Inbox (3,737) - integration-account@jiminny.com - Jiminny Mail","depth":5,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"New Tab","depth":4,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Customize sidebar","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open Google Gemini (⌃X)","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Tabs from other devices","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open history (⇧⌘H)","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open bookmarks (⌘B)","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXLink","text":"HubSpot logo","depth":9,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXTextField","text":"Find or Ask","depth":11,"help_text":"","role_description":"search text field","subrole":"AXSearchField","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"⌘","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"K","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXMenuButton","text":"Create new","depth":9,"help_text":"","role_description":"menu button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXButton","text":"Scroll up","depth":9,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXButton","text":"Scroll down","depth":9,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXHeading","text":"Development","depth":11,"help_text":"","role_description":"heading","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Development","depth":12,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Overview","depth":15,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Projects","depth":15,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Legacy Apps","depth":15,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"MCP Auth Apps BETA","depth":15,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"MCP Auth Apps","depth":16,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"BETA","depth":17,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Design Manager","depth":15,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Monitoring","depth":15,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":true},{"role":"AXStaticText","text":"Monitoring","depth":16,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Logs","depth":18,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"API Call Usage","depth":18,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":true},{"role":"AXButton","text":"Keys","depth":15,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Testing","depth":15,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Domain","depth":15,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"App Listings","depth":15,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Technology Partner","depth":15,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Documentation","depth":15,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Documentation","depth":16,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXHeading","text":"API Call Usage","depth":12,"help_text":"","role_description":"heading","subrole":"AXUnknown"},{"role":"AXStaticText","text":"API Call Usage","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"The number of API calls made in the past 24 hours by privately distributed apps and service keys on this account.","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"0/250,000","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"calls","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"0%","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"API call counts reset at midnight","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Last updated","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"in a few seconds","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":".","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXHeading","text":"Apps & Service Keys Built Here","depth":12,"help_text":"","role_description":"heading","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Apps & Service Keys Built Here","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"0","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"0%","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXHeading","text":"Third Party Apps","depth":12,"help_text":"","role_description":"heading","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Third Party Apps","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"0","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"0%","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"}]...
|
3608882136366109917
|
4089772800348566276
|
visual_change
|
accessibility
|
NULL
|
Workers | Datadog
API Call Usage
API Call Usage
Cl Workers | Datadog
API Call Usage
API Call Usage
Close tab
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
New Tab
Customize sidebar
Open Google Gemini (⌃X)
Tabs from other devices
Open history (⇧⌘H)
Open bookmarks (⌘B)
HubSpot logo
Find or Ask
⌘
K
Create new
Scroll up
Scroll down
Development
Development
Overview
Projects
Legacy Apps
MCP Auth Apps BETA
MCP Auth Apps
BETA
Design Manager
Monitoring
Monitoring
Logs
API Call Usage
Keys
Testing
Domain
App Listings
Technology Partner
Documentation
Documentation
API Call Usage
API Call Usage
The number of API calls made in the past 24 hours by privately distributed apps and service keys on this account.
0/250,000
calls
0%
API call counts reset at midnight
Last updated
in a few seconds
.
Apps & Service Keys Built Here
Apps & Service Keys Built Here
0
0%
Third Party Apps
Third Party Apps
0
0%...
|
NULL
|
|
43868
|
932
|
0
|
2026-04-17T08:23:56.525703+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776414236525_m2.jpg...
|
Firefox
|
API Call Usage — Work
|
1
|
app.hubspot.com/api-call-usage/2752939
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Workers | Datadog
API Call Usage
API Call Usage
Cl Workers | Datadog
API Call Usage
API Call Usage
Close tab
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
New Tab
Customize sidebar
Open Google Gemini (⌃X)
Tabs from other devices
Open history (⇧⌘H)
Open bookmarks (⌘B)
HubSpot logo
Find or Ask
⌘
K
Create new
Scroll up
Scroll down
Development
Development
Overview
Projects
Legacy Apps
MCP Auth Apps BETA
MCP Auth Apps
BETA
Design Manager
Monitoring
Monitoring
Logs
API Call Usage
Keys
Testing
Domain
App Listings
Technology Partner
Documentation
Documentation
API Call Usage
API Call Usage
The number of API calls made in the past 24 hours by privately distributed apps and service keys on this account.
0/250,000
calls
0%
API call counts reset at midnight
Last updated
in a few seconds
.
Apps & Service Keys Built Here
Apps & Service Keys Built Here
0
0%
Third Party Apps
Third Party Apps
0
0%...
|
[{"role":"AXRadioButton","text [{"role":"AXRadioButton","text":"Workers | Datadog","depth":4,"bounds":{"left":0.00234375,"top":0.045138888,"width":0.0890625,"height":0.028472222},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXRadioButton","text":"API Call Usage","depth":4,"bounds":{"left":0.0,"top":0.08263889,"width":0.09375,"height":0.028472222},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":true},{"role":"AXStaticText","text":"API Call Usage","depth":5,"bounds":{"left":0.015625,"top":0.09236111,"width":0.030078124,"height":0.009722223},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Close tab","depth":5,"bounds":{"left":0.07890625,"top":0.08888889,"width":0.009375,"height":0.016666668},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXRadioButton","text":"Inbox (1,574) - lukas.kovalik@jiminny.com - Jiminny Mail","depth":4,"bounds":{"left":0.0,"top":0.11111111,"width":0.09375,"height":0.028472222},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Inbox (1,574) - lukas.kovalik@jiminny.com - Jiminny Mail","depth":5,"bounds":{"left":0.015625,"top":0.12083333,"width":0.11445312,"height":0.009722223},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXRadioButton","text":"Inbox (3,737) - integration-account@jiminny.com - Jiminny Mail","depth":4,"bounds":{"left":0.0,"top":0.13958333,"width":0.09375,"height":0.028472222},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Inbox (3,737) - integration-account@jiminny.com - Jiminny Mail","depth":5,"bounds":{"left":0.015625,"top":0.14930555,"width":0.1296875,"height":0.009722223},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"New Tab","depth":4,"bounds":{"left":0.003125,"top":0.16944444,"width":0.08710937,"height":0.022222223},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Customize sidebar","depth":6,"bounds":{"left":0.003125,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open Google Gemini (⌃X)","depth":6,"bounds":{"left":0.01640625,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Tabs from other devices","depth":6,"bounds":{"left":0.029296875,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open history (⇧⌘H)","depth":6,"bounds":{"left":0.0421875,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open bookmarks (⌘B)","depth":6,"bounds":{"left":0.05546875,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXLink","text":"HubSpot logo","depth":9,"bounds":{"left":0.0984375,"top":0.047916666,"width":0.016015625,"height":0.025694445},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXTextField","text":"Find or Ask","depth":11,"bounds":{"left":0.119140625,"top":0.05,"width":0.2140625,"height":0.020833334},"help_text":"","role_description":"search text field","subrole":"AXSearchField","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"⌘","depth":13,"bounds":{"left":0.3125,"top":0.054166667,"width":0.00546875,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"K","depth":13,"bounds":{"left":0.321875,"top":0.054166667,"width":0.00390625,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXMenuButton","text":"Create new","depth":9,"bounds":{"left":0.33828124,"top":0.049305554,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"menu button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXButton","text":"Scroll up","depth":9,"bounds":{"left":0.09375,"top":0.07569444,"width":0.025,"height":0.022222223},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXButton","text":"Scroll down","depth":9,"bounds":{"left":0.09375,"top":0.9777778,"width":0.025,"height":0.02222222},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXHeading","text":"Development","depth":11,"bounds":{"left":0.13125,"top":0.103472225,"width":0.075,"height":0.016666668},"help_text":"","role_description":"heading","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Development","depth":12,"bounds":{"left":0.13125,"top":0.103472225,"width":0.0515625,"height":0.017361112},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Overview","depth":15,"bounds":{"left":0.13125,"top":0.15416667,"width":0.075,"height":0.02638889},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Projects","depth":15,"bounds":{"left":0.13125,"top":0.18055555,"width":0.075,"height":0.02638889},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Legacy Apps","depth":15,"bounds":{"left":0.13125,"top":0.20694445,"width":0.075,"height":0.02638889},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"MCP Auth Apps BETA","depth":15,"bounds":{"left":0.13125,"top":0.23333333,"width":0.075,"height":0.02638889},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"MCP Auth Apps","depth":16,"bounds":{"left":0.1359375,"top":0.24027778,"width":0.03984375,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"BETA","depth":17,"bounds":{"left":0.18828125,"top":0.24236111,"width":0.01015625,"height":0.009027778},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Design Manager","depth":15,"bounds":{"left":0.13125,"top":0.25972223,"width":0.075,"height":0.02638889},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Monitoring","depth":15,"bounds":{"left":0.13125,"top":0.28611112,"width":0.075,"height":0.02638889},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":true},{"role":"AXStaticText","text":"Monitoring","depth":16,"bounds":{"left":0.1359375,"top":0.29305556,"width":0.027734375,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Logs","depth":18,"bounds":{"left":0.13125,"top":0.3125,"width":0.075,"height":0.02638889},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"API Call Usage","depth":18,"bounds":{"left":0.13125,"top":0.33888888,"width":0.075,"height":0.02638889},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":true},{"role":"AXButton","text":"Keys","depth":15,"bounds":{"left":0.13125,"top":0.36805555,"width":0.075,"height":0.02638889},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Testing","depth":15,"bounds":{"left":0.13125,"top":0.39444444,"width":0.075,"height":0.02638889},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Domain","depth":15,"bounds":{"left":0.13125,"top":0.42083332,"width":0.075,"height":0.02638889},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"App Listings","depth":15,"bounds":{"left":0.13125,"top":0.47013888,"width":0.075,"height":0.02638889},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Technology Partner","depth":15,"bounds":{"left":0.13125,"top":0.4965278,"width":0.075,"height":0.02638889},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Documentation","depth":15,"bounds":{"left":0.13125,"top":0.54583335,"width":0.075,"height":0.02638889},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Documentation","depth":16,"bounds":{"left":0.1359375,"top":0.55277777,"width":0.039453126,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXHeading","text":"API Call Usage","depth":12,"bounds":{"left":0.25507814,"top":0.10555556,"width":0.055078126,"height":0.016666668},"help_text":"","role_description":"heading","subrole":"AXUnknown"},{"role":"AXStaticText","text":"API Call Usage","depth":13,"bounds":{"left":0.25507814,"top":0.10555556,"width":0.055078126,"height":0.017361112},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"The number of API calls made in the past 24 hours by privately distributed apps and service keys on this account.","depth":13,"bounds":{"left":0.25507814,"top":0.15625,"width":0.2878906,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"0/250,000","depth":13,"bounds":{"left":0.25507814,"top":0.18611111,"width":0.03046875,"height":0.013888889},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"calls","depth":13,"bounds":{"left":0.28554687,"top":0.18611111,"width":0.0140625,"height":0.013888889},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"0%","depth":13,"bounds":{"left":0.74492186,"top":0.18472221,"width":0.01015625,"height":0.013888889},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"API call counts reset at midnight","depth":13,"bounds":{"left":0.25507814,"top":0.22222222,"width":0.0703125,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Last updated","depth":13,"bounds":{"left":0.6875,"top":0.22222222,"width":0.030078124,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"in a few seconds","depth":13,"bounds":{"left":0.7175781,"top":0.22222222,"width":0.036328126,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":".","depth":13,"bounds":{"left":0.75390625,"top":0.22222222,"width":0.001171875,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXHeading","text":"Apps & Service Keys Built Here","depth":12,"bounds":{"left":0.26328126,"top":0.2701389,"width":0.23203126,"height":0.013888889},"help_text":"","role_description":"heading","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Apps & Service Keys Built Here","depth":13,"bounds":{"left":0.26328126,"top":0.2701389,"width":0.096875,"height":0.013888889},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"0","depth":13,"bounds":{"left":0.26328126,"top":0.29652777,"width":0.003515625,"height":0.013888889},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"0%","depth":13,"bounds":{"left":0.48515624,"top":0.2951389,"width":0.01015625,"height":0.013888889},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXHeading","text":"Third Party Apps","depth":12,"bounds":{"left":0.51484376,"top":0.2701389,"width":0.23203126,"height":0.013888889},"help_text":"","role_description":"heading","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Third Party Apps","depth":13,"bounds":{"left":0.51484376,"top":0.2701389,"width":0.05234375,"height":0.013888889},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"0","depth":13,"bounds":{"left":0.51484376,"top":0.29652777,"width":0.003515625,"height":0.013888889},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"0%","depth":13,"bounds":{"left":0.7367188,"top":0.2951389,"width":0.01015625,"height":0.013888889},"help_text":"","role_description":"text","subrole":"AXUnknown"}]...
|
3608882136366109917
|
4089772800348566276
|
visual_change
|
accessibility
|
NULL
|
Workers | Datadog
API Call Usage
API Call Usage
Cl Workers | Datadog
API Call Usage
API Call Usage
Close tab
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
New Tab
Customize sidebar
Open Google Gemini (⌃X)
Tabs from other devices
Open history (⇧⌘H)
Open bookmarks (⌘B)
HubSpot logo
Find or Ask
⌘
K
Create new
Scroll up
Scroll down
Development
Development
Overview
Projects
Legacy Apps
MCP Auth Apps BETA
MCP Auth Apps
BETA
Design Manager
Monitoring
Monitoring
Logs
API Call Usage
Keys
Testing
Domain
App Listings
Technology Partner
Documentation
Documentation
API Call Usage
API Call Usage
The number of API calls made in the past 24 hours by privately distributed apps and service keys on this account.
0/250,000
calls
0%
API call counts reset at midnight
Last updated
in a few seconds
.
Apps & Service Keys Built Here
Apps & Service Keys Built Here
0
0%
Third Party Apps
Third Party Apps
0
0%...
|
NULL
|
|
44008
|
NULL
|
0
|
2026-04-17T08:29:32.451152+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776414572451_m1.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
FirefoxFileEditViewHistoryBookmarksProfilesToolsWi FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelpmeet.google.com/xpx-omah-rknallBackend Chapter • 1 m left100% C8 • Fri 17 Apr 11:29:326+llian Kyuchukov (Presenting, annotating)BraveProfilesHelp• Q 8• Frl17 Apr 11:29ureourine oraerouereeCloudWatch | us-east-2@ DEV Jiminmyhttps//us-east-2.console.aws.amazon.com/cloudwatch/home?regionsus-east-2#ogsV2:logs-insightsS3FqueryDetallS3D-(en…Q My PRsQ Assigned3 Pipelines - jiminery-JRA• OpenAl Platform |83 Confluence(7 Service-Desk - Qu.aws(Option+S) ©United States (Ohio) •[ All Bookmarkst ID: 4103-4619-5943View_Only ® lnLogs InsightsShowing 10,000 of 56,748 records matched ©1,338,861 records (451.4 MB) scanned in 5.4s ® 247,433 records/s (83,4 MB/$)04.15|04:1604.2804.2804.3004.3204.30Q, Filter toble results (cose insensitive).etinestomoPees5ooh:•9.• 10.• 12.• 14• 15.24252826-04-17T84:40:58.839+_"} ("correlation_(d*: "b836e487-e9bo-48c7-b387-ef3f340854eb*, "troce_(a": *8b033eb9-3623-4287-0048-70-023ec3837*)2826-84-17704:40:58.839+_*) ('correlation_(d": "0836e487-e9bo-48c7-b887-ef3f3408S4eb*, 'troce_(6°: "8b033e69-3623-4287-0048-78e023ec3837*)2026-04-17184:40:58.827+-(2826-04-17 01:40:58) production. INFO: [PrepareUpdateDtoAction) Torget object prepored ("run_id":1252785, "torget..Id": 19862190, "target_type": "opportunity", "update_torget_dto": ("locol_object_id* :19862190, *-2826-04-17T84:40:58.819-_(2826-04-17 01:40:58) production, INFO: [PrepareUpdateDtoAction) Terget dbject prepored ("run_id":1259600, "torget.(d":19862190, "target_type" : "opportunity", "update_target_dto": ("locol_object_id^ :19862190, *-2826-04-17704:40:58.818._*) ("correlation_id": "b3S8f2C7-doe-4e37-8fdS-eBeb862cBec9", "troce_id":^8ba33eb9-3623-4287-0048-78e823ec3837*}|2026-04-17704:40:58.818._*} (*cornelation_(d*: *b3S8f2C7-doße-4e37-8fdS-e0eb862c8ec9*, "troce_id": "8ba33e69-3623-4287-0048-78e023ec3837*)2826-04-17104:40:58.811+_*) ("correlation_id":"19174de3-3cf3-4727-0473-9f6ece967f15*, "troce_id" :"8bo33eb9-3623-4287-0048-78e023ec3837*)|2026-04-17104:40:58.811+_"} ("correlation_id": "19174de3-3cf3-4727-0473-9f6eee9b7f15*, "troce_id": "8bo33eb9-3623-4287-0048-78e023ec3837")2826-04-17704:40:58.772+_(2826-84-17 01:40:58] production. INFO: [OpportunityPendingAiAnalysisAfterStopeChonged) Opportunity is scheduled for analysis ("opportunity_id":19862190, 'teom,id":1018) ("correlation_id":"50867150-6146-4c_2826-84-17T84:40:58.651+_(2026-04-17 01:40:58] production.[Update(refieldAction) Could not update the renote object ('error": "You have reached your ten,secondly_rolling limit.", "cm.run_id" :1252580, "cm.object_type* : "oppo.2026-04-17704:40:58.651+_(2826-04-17 01:40:58] productic(ubSpot) Update record failed ("objectType": "opportunity", "objectld": "300815235798", "payload" : ("properties": ("totol_field_leods" : *12")), "resson": "You have reached.[2826-04-17 01:40:58] production.INFQ: RecolculateDealRisks.Job ("dato":{"oppld":19862190, "include": [4,8]}} ("correlation_id":"96bbbb71-c257-4coe-91fe-4805f74cdeбd*, "troce_(d": "8ba33eb9-3623-4287-0048-78e..2826-04-17104:40:58.573+_[2826-04-17 81:40:58] production. INFO: [OpportunityPendingAiAnalysisAfterStogeChonged) Opportunity is scheduled for anolysis ('"opportunity_id":19862190, 'teon_(d":1018) ("correletion_t6":"596516e7-6e1d-4c)2026-04-17T04:40:58.551+_(2026-04-17 01:40:58) production. INFO: [OpportunityPendingA(AnalysisAfterStogeChonged) Opportunity is schedbled for anolysis ("opportunity_td":19862190, "teon_(d*: 1018) ("correletion_(6": "90c45776-1ff8-42.2026-04-17704:40:58.410+(2826-04-17 01:40:58] production.INFO: [ProcessA(AutonationAnalysis] Analysis is to be written in CRM. ("torget_object_id*:19862190, "target_object_type":"opportunity","renote_object_provider_id":*3008152.2826-04-17T04:40:58.430-.(2026-04-17 01:40:58] production. INFO:(DetereineUpdateOperoticekction) Renote or local content exists. Log Method is Overarite. Updating ("locol_object_id": 19862198, "renote_object_type":"opportunity", **.-2026-04-17704:40:58.401+_(2826-84-17 01:40:58] production, INFO:(DetereineUpdateOperaticekction) Renote or local content exists. Log Method is Overarite. Updating ("locol_dbject_id": 19862198, "renote_coject_type*:"opportunity", **.-2026-84-17704:40:58.401+_[2826-04-17 01:40:58) production. INFO:attonAnalysis] Anelysis is to be written in CRM. ("torget_object_id":19862190, "target_dbject_type":"opportunity",*renote_object_provider_id*:*30081522826-04-17T84:40:58.395+_(2026-04-17 01:40:581 production.INF0: Recl2826-04-17104:40:58.38.4_jculateDealRisks/cb ("data": ("eppld": 19862190, "'include": [4, 83)) ("correlation.id*: *46b4808b-7385-42c8-b2b2-C6f874fcSe31*, 'troce_ld*: 86a33459-3623-4287-0048-70e.(2826-04-17 01:40:58] production. INFO:xForOpportunityJcb] Done reindexing ("opportunityIds":[19862199]} {"correlation_id":"a61b277d-65cd-4c60-0525-2f06bc81cfd6*, "troce_id*: "8ba33+b9-3623-4287-004E2 CoudShellFeedbackPtlvacyTerms$ICoolde preferencesNetmenthot2024-11_6.56.png..•Vasil Vasilevlian KyuchukovMihail MihayloNikolay NikolovLukas Kovalik11:29 AM | Daily - ProcessingLộ3...
|
NULL
|
-5291875512798394366
|
NULL
|
visual_change
|
ocr
|
NULL
|
FirefoxFileEditViewHistoryBookmarksProfilesToolsWi FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelpmeet.google.com/xpx-omah-rknallBackend Chapter • 1 m left100% C8 • Fri 17 Apr 11:29:326+llian Kyuchukov (Presenting, annotating)BraveProfilesHelp• Q 8• Frl17 Apr 11:29ureourine oraerouereeCloudWatch | us-east-2@ DEV Jiminmyhttps//us-east-2.console.aws.amazon.com/cloudwatch/home?regionsus-east-2#ogsV2:logs-insightsS3FqueryDetallS3D-(en…Q My PRsQ Assigned3 Pipelines - jiminery-JRA• OpenAl Platform |83 Confluence(7 Service-Desk - Qu.aws(Option+S) ©United States (Ohio) •[ All Bookmarkst ID: 4103-4619-5943View_Only ® lnLogs InsightsShowing 10,000 of 56,748 records matched ©1,338,861 records (451.4 MB) scanned in 5.4s ® 247,433 records/s (83,4 MB/$)04.15|04:1604.2804.2804.3004.3204.30Q, Filter toble results (cose insensitive).etinestomoPees5ooh:•9.• 10.• 12.• 14• 15.24252826-04-17T84:40:58.839+_"} ("correlation_(d*: "b836e487-e9bo-48c7-b387-ef3f340854eb*, "troce_(a": *8b033eb9-3623-4287-0048-70-023ec3837*)2826-84-17704:40:58.839+_*) ('correlation_(d": "0836e487-e9bo-48c7-b887-ef3f3408S4eb*, 'troce_(6°: "8b033e69-3623-4287-0048-78e023ec3837*)2026-04-17184:40:58.827+-(2826-04-17 01:40:58) production. INFO: [PrepareUpdateDtoAction) Torget object prepored ("run_id":1252785, "torget..Id": 19862190, "target_type": "opportunity", "update_torget_dto": ("locol_object_id* :19862190, *-2826-04-17T84:40:58.819-_(2826-04-17 01:40:58) production, INFO: [PrepareUpdateDtoAction) Terget dbject prepored ("run_id":1259600, "torget.(d":19862190, "target_type" : "opportunity", "update_target_dto": ("locol_object_id^ :19862190, *-2826-04-17704:40:58.818._*) ("correlation_id": "b3S8f2C7-doe-4e37-8fdS-eBeb862cBec9", "troce_id":^8ba33eb9-3623-4287-0048-78e823ec3837*}|2026-04-17704:40:58.818._*} (*cornelation_(d*: *b3S8f2C7-doße-4e37-8fdS-e0eb862c8ec9*, "troce_id": "8ba33e69-3623-4287-0048-78e023ec3837*)2826-04-17104:40:58.811+_*) ("correlation_id":"19174de3-3cf3-4727-0473-9f6ece967f15*, "troce_id" :"8bo33eb9-3623-4287-0048-78e023ec3837*)|2026-04-17104:40:58.811+_"} ("correlation_id": "19174de3-3cf3-4727-0473-9f6eee9b7f15*, "troce_id": "8bo33eb9-3623-4287-0048-78e023ec3837")2826-04-17704:40:58.772+_(2826-84-17 01:40:58] production. INFO: [OpportunityPendingAiAnalysisAfterStopeChonged) Opportunity is scheduled for analysis ("opportunity_id":19862190, 'teom,id":1018) ("correlation_id":"50867150-6146-4c_2826-84-17T84:40:58.651+_(2026-04-17 01:40:58] production.[Update(refieldAction) Could not update the renote object ('error": "You have reached your ten,secondly_rolling limit.", "cm.run_id" :1252580, "cm.object_type* : "oppo.2026-04-17704:40:58.651+_(2826-04-17 01:40:58] productic(ubSpot) Update record failed ("objectType": "opportunity", "objectld": "300815235798", "payload" : ("properties": ("totol_field_leods" : *12")), "resson": "You have reached.[2826-04-17 01:40:58] production.INFQ: RecolculateDealRisks.Job ("dato":{"oppld":19862190, "include": [4,8]}} ("correlation_id":"96bbbb71-c257-4coe-91fe-4805f74cdeбd*, "troce_(d": "8ba33eb9-3623-4287-0048-78e..2826-04-17104:40:58.573+_[2826-04-17 81:40:58] production. INFO: [OpportunityPendingAiAnalysisAfterStogeChonged) Opportunity is scheduled for anolysis ('"opportunity_id":19862190, 'teon_(d":1018) ("correletion_t6":"596516e7-6e1d-4c)2026-04-17T04:40:58.551+_(2026-04-17 01:40:58) production. INFO: [OpportunityPendingA(AnalysisAfterStogeChonged) Opportunity is schedbled for anolysis ("opportunity_td":19862190, "teon_(d*: 1018) ("correletion_(6": "90c45776-1ff8-42.2026-04-17704:40:58.410+(2826-04-17 01:40:58] production.INFO: [ProcessA(AutonationAnalysis] Analysis is to be written in CRM. ("torget_object_id*:19862190, "target_object_type":"opportunity","renote_object_provider_id":*3008152.2826-04-17T04:40:58.430-.(2026-04-17 01:40:58] production. INFO:(DetereineUpdateOperoticekction) Renote or local content exists. Log Method is Overarite. Updating ("locol_object_id": 19862198, "renote_object_type":"opportunity", **.-2026-04-17704:40:58.401+_(2826-84-17 01:40:58] production, INFO:(DetereineUpdateOperaticekction) Renote or local content exists. Log Method is Overarite. Updating ("locol_dbject_id": 19862198, "renote_coject_type*:"opportunity", **.-2026-84-17704:40:58.401+_[2826-04-17 01:40:58) production. INFO:attonAnalysis] Anelysis is to be written in CRM. ("torget_object_id":19862190, "target_dbject_type":"opportunity",*renote_object_provider_id*:*30081522826-04-17T84:40:58.395+_(2026-04-17 01:40:581 production.INF0: Recl2826-04-17104:40:58.38.4_jculateDealRisks/cb ("data": ("eppld": 19862190, "'include": [4, 83)) ("correlation.id*: *46b4808b-7385-42c8-b2b2-C6f874fcSe31*, 'troce_ld*: 86a33459-3623-4287-0048-70e.(2826-04-17 01:40:58] production. INFO:xForOpportunityJcb] Done reindexing ("opportunityIds":[19862199]} {"correlation_id":"a61b277d-65cd-4c60-0525-2f06bc81cfd6*, "troce_id*: "8ba33+b9-3623-4287-004E2 CoudShellFeedbackPtlvacyTerms$ICoolde preferencesNetmenthot2024-11_6.56.png..•Vasil Vasilevlian KyuchukovMihail MihayloNikolay NikolovLukas Kovalik11:29 AM | Daily - ProcessingLộ3...
|
44007
|
|
44009
|
NULL
|
0
|
2026-04-17T08:29:34.988953+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776414574988_m2.jpg...
|
Firefox
|
Developers | HubSpot — Work
|
1
|
app.hubspot.com/developer/2752939/application/3848 app.hubspot.com/developer/2752939/application/38484/monitoring/webhooks?objectTypeIds=0-3&subscriptionTypes=deal.creation&subscriptionTypes=deal.propertyChange&subscriptionTypes=deal.associationChange...
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Workers | Datadog
Developers | HubSpot
Developers Workers | Datadog
Developers | HubSpot
Developers | HubSpot
Close tab
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
New Tab
Customize sidebar
Open Google Gemini (⌃X)
Tabs from other devices
Open history (⇧⌘H)
Open bookmarks (⌘B)
HubSpot logo
Find or Ask
⌘
K
Create new
Scroll up
Scroll down
Back to all apps
Back to all apps
Jiminny
Jiminny
Created by
Jiminny #127
Jiminny
#
127
Basic info
Basic info
Contact & support
Contact & support
Monitoring
Monitoring
Features
Features
CRM cards
CRM cards
UI extensions BETA
UI extensions
BETA
Timeline events
Timeline events
Webhooks
Webhooks
App settings
App settings
More features
More features
API calls
API calls
Webhooks
Webhooks
App settings
App settings
UI extensions BETA
UI extensions
BETA
Log traces BETA
Log traces
BETA
OAuth
OAuth
Filter by:
Deal Close
Deal
Close
deal.creation Close deal.propertyChange Close deal.associationChange Close
deal.creation
Close
deal.propertyChange
Close
deal.associationChange
Close
Status
Status
Start date
End date
04/12/2026
to
04/17/2026
Log ID
Log ID
Search by log ID
Export logs (CSV)
Export logs (CSV)
STATUS
SUBSCRIPTION TYPE
BATCH ID
ATTEMPT START
204
deal.associationChange
49845354-415a-461a-bc92-c5b62bb46ce0
April 17, 2026 4:26 AM EDT
204
deal.associationChange
e456953e-4034-4375-bb5c-3d81bbae99d5...
|
[{"role":"AXRadioButton","text [{"role":"AXRadioButton","text":"Workers | Datadog","depth":4,"bounds":{"left":0.00234375,"top":0.045138888,"width":0.0890625,"height":0.028472222},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXRadioButton","text":"Developers | HubSpot","depth":4,"bounds":{"left":0.0,"top":0.08263889,"width":0.09375,"height":0.028472222},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":true},{"role":"AXStaticText","text":"Developers | HubSpot","depth":5,"bounds":{"left":0.015625,"top":0.09236111,"width":0.04453125,"height":0.009722223},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Close tab","depth":5,"bounds":{"left":0.07890625,"top":0.08888889,"width":0.009375,"height":0.016666668},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXRadioButton","text":"Inbox (1,574) - lukas.kovalik@jiminny.com - Jiminny Mail","depth":4,"bounds":{"left":0.0,"top":0.11111111,"width":0.09375,"height":0.028472222},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Inbox (1,574) - lukas.kovalik@jiminny.com - Jiminny Mail","depth":5,"bounds":{"left":0.015625,"top":0.12083333,"width":0.11445312,"height":0.009722223},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXRadioButton","text":"Inbox (3,737) - integration-account@jiminny.com - Jiminny Mail","depth":4,"bounds":{"left":0.0,"top":0.13958333,"width":0.09375,"height":0.028472222},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Inbox (3,737) - integration-account@jiminny.com - Jiminny Mail","depth":5,"bounds":{"left":0.015625,"top":0.14930555,"width":0.1296875,"height":0.009722223},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"New Tab","depth":4,"bounds":{"left":0.003125,"top":0.16944444,"width":0.08710937,"height":0.022222223},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Customize sidebar","depth":6,"bounds":{"left":0.003125,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open Google Gemini (⌃X)","depth":6,"bounds":{"left":0.01640625,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Tabs from other devices","depth":6,"bounds":{"left":0.029296875,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open history (⇧⌘H)","depth":6,"bounds":{"left":0.0421875,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open bookmarks (⌘B)","depth":6,"bounds":{"left":0.05546875,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXLink","text":"HubSpot logo","depth":9,"bounds":{"left":0.0984375,"top":0.047916666,"width":0.016015625,"height":0.025694445},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXTextField","text":"Find or Ask","depth":11,"bounds":{"left":0.119140625,"top":0.05,"width":0.2140625,"height":0.020833334},"help_text":"","role_description":"search text field","subrole":"AXSearchField","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"⌘","depth":13,"bounds":{"left":0.3125,"top":0.054166667,"width":0.00546875,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"K","depth":13,"bounds":{"left":0.321875,"top":0.054166667,"width":0.00390625,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXMenuButton","text":"Create new","depth":9,"bounds":{"left":0.33828124,"top":0.049305554,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"menu button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXButton","text":"Scroll up","depth":9,"bounds":{"left":0.09375,"top":0.07569444,"width":0.025,"height":0.022222223},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXButton","text":"Scroll down","depth":9,"bounds":{"left":0.09375,"top":0.9777778,"width":0.025,"height":0.02222222},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXLink","text":"Back to all apps","depth":10,"bounds":{"left":0.2046875,"top":0.09375,"width":0.042578124,"height":0.010416667},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Back to all apps","depth":12,"bounds":{"left":0.209375,"top":0.09375,"width":0.037890624,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXHeading","text":"Jiminny","depth":10,"bounds":{"left":0.2046875,"top":0.10972222,"width":0.5,"height":0.016666668},"help_text":"","role_description":"heading","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Jiminny","depth":13,"bounds":{"left":0.2046875,"top":0.10902778,"width":0.031640626,"height":0.017361112},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Created by","depth":10,"bounds":{"left":0.2046875,"top":0.13194445,"width":0.0296875,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"Jiminny #127","depth":10,"bounds":{"left":0.234375,"top":0.13194445,"width":0.03671875,"height":0.0125},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Jiminny","depth":11,"bounds":{"left":0.234375,"top":0.13194445,"width":0.022265624,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"#","depth":11,"bounds":{"left":0.2566406,"top":0.13194445,"width":0.00546875,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"127","depth":11,"bounds":{"left":0.26210937,"top":0.13194445,"width":0.008984375,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"Basic info","depth":12,"bounds":{"left":0.2,"top":0.175,"width":0.0796875,"height":0.02638889},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Basic info","depth":14,"bounds":{"left":0.2046875,"top":0.18194444,"width":0.025,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"Contact & support","depth":12,"bounds":{"left":0.2,"top":0.2013889,"width":0.0796875,"height":0.02638889},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Contact & support","depth":14,"bounds":{"left":0.2046875,"top":0.20833333,"width":0.047265626,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"Monitoring","depth":12,"bounds":{"left":0.2,"top":0.22777778,"width":0.0796875,"height":0.02638889},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":true},{"role":"AXStaticText","text":"Monitoring","depth":14,"bounds":{"left":0.2046875,"top":0.23472223,"width":0.027734375,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXHeading","text":"Features","depth":10,"bounds":{"left":0.2046875,"top":0.27708334,"width":0.075,"height":0.013888889},"help_text":"","role_description":"heading","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Features","depth":11,"bounds":{"left":0.2046875,"top":0.27708334,"width":0.026953125,"height":0.013888889},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"CRM cards","depth":12,"bounds":{"left":0.2,"top":0.29652777,"width":0.0796875,"height":0.02638889},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"CRM cards","depth":14,"bounds":{"left":0.2046875,"top":0.30347222,"width":0.027734375,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"UI extensions BETA","depth":12,"bounds":{"left":0.2,"top":0.32291666,"width":0.0796875,"height":0.02638889},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"UI extensions","depth":14,"bounds":{"left":0.2046875,"top":0.3298611,"width":0.03515625,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"BETA","depth":14,"bounds":{"left":0.24609375,"top":0.33125,"width":0.01015625,"height":0.009027778},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"Timeline events","depth":12,"bounds":{"left":0.2,"top":0.34930557,"width":0.0796875,"height":0.02638889},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Timeline events","depth":14,"bounds":{"left":0.2046875,"top":0.35625,"width":0.039453126,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"Webhooks","depth":12,"bounds":{"left":0.2,"top":0.37569445,"width":0.0796875,"height":0.02638889},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":true},{"role":"AXStaticText","text":"Webhooks","depth":14,"bounds":{"left":0.2046875,"top":0.3826389,"width":0.0265625,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"App settings","depth":12,"bounds":{"left":0.2,"top":0.40208334,"width":0.0796875,"height":0.02638889},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"App settings","depth":14,"bounds":{"left":0.2046875,"top":0.40902779,"width":0.03203125,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"More features","depth":12,"bounds":{"left":0.2,"top":0.42847222,"width":0.0796875,"height":0.02638889},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"More features","depth":14,"bounds":{"left":0.2046875,"top":0.43541667,"width":0.035546876,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"API calls","depth":12,"bounds":{"left":0.29257813,"top":0.17569445,"width":0.044140626,"height":0.033333335},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"API calls","depth":13,"bounds":{"left":0.3035156,"top":0.18611111,"width":0.022265624,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"Webhooks","depth":12,"bounds":{"left":0.33671874,"top":0.17569445,"width":0.050390624,"height":0.033333335},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Webhooks","depth":13,"bounds":{"left":0.34804687,"top":0.18611111,"width":0.028125,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"App settings","depth":12,"bounds":{"left":0.38710937,"top":0.17569445,"width":0.054296874,"height":0.033333335},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"App settings","depth":13,"bounds":{"left":0.3984375,"top":0.18611111,"width":0.03203125,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"UI extensions BETA","depth":12,"bounds":{"left":0.44140625,"top":0.17569445,"width":0.07734375,"height":0.033333335},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"UI extensions","depth":13,"bounds":{"left":0.45273438,"top":0.18611111,"width":0.035546876,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"BETA","depth":14,"bounds":{"left":0.49453124,"top":0.18888889,"width":0.01015625,"height":0.009027778},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"Log traces BETA","depth":12,"bounds":{"left":0.51875,"top":0.17569445,"width":0.06914063,"height":0.033333335},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Log traces","depth":13,"bounds":{"left":0.5300781,"top":0.18611111,"width":0.02734375,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"BETA","depth":14,"bounds":{"left":0.5636719,"top":0.18888889,"width":0.01015625,"height":0.009027778},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"OAuth","depth":12,"bounds":{"left":0.5878906,"top":0.17569445,"width":0.03828125,"height":0.033333335},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"OAuth","depth":13,"bounds":{"left":0.5992187,"top":0.18611111,"width":0.016015625,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Filter by:","depth":11,"bounds":{"left":0.2921875,"top":0.24305555,"width":0.021875,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXMenuButton","text":"Deal Close","depth":12,"bounds":{"left":0.31875,"top":0.22013889,"width":0.040234376,"height":0.030555556},"help_text":"","role_description":"menu button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Deal","depth":21,"bounds":{"left":0.32734376,"top":0.22916667,"width":0.010546875,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Close","depth":16,"bounds":{"left":0.340625,"top":0.23055555,"width":0.00390625,"height":0.007638889},"role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXMenuButton","text":"deal.creation Close deal.propertyChange Close deal.associationChange Close","depth":12,"bounds":{"left":0.35898438,"top":0.22013889,"width":0.20039062,"height":0.030555556},"help_text":"","role_description":"menu button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"deal.creation","depth":21,"bounds":{"left":0.36757812,"top":0.22916667,"width":0.030859375,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Close","depth":16,"bounds":{"left":0.40117186,"top":0.23055555,"width":0.00390625,"height":0.007638889},"role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"deal.propertyChange","depth":21,"bounds":{"left":0.4152344,"top":0.22916667,"width":0.05,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Close","depth":16,"bounds":{"left":0.46796876,"top":0.23055555,"width":0.00390625,"height":0.007638889},"role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"deal.associationChange","depth":21,"bounds":{"left":0.48203126,"top":0.22916667,"width":0.05625,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Close","depth":16,"bounds":{"left":0.5410156,"top":0.23055555,"width":0.00390625,"height":0.007638889},"role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXMenuButton","text":"Status","depth":12,"bounds":{"left":0.31875,"top":0.25069445,"width":0.032421876,"height":0.027777778},"help_text":"","role_description":"menu button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Status","depth":15,"bounds":{"left":0.32382813,"top":0.25833333,"width":0.017578125,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Start date","depth":12,"bounds":{"left":0.5839844,"top":0.24166666,"width":0.012890625,"height":0.029166667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"End date","depth":12,"bounds":{"left":0.5839844,"top":0.24166666,"width":0.01171875,"height":0.029166667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXTextField","text":"04/12/2026","depth":12,"bounds":{"left":0.584375,"top":0.24097222,"width":0.053515624,"height":0.017361112},"value":"04/12/2026","help_text":"","placeholder":"MM/DD/YYYY","role_description":"text field","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"to","depth":12,"bounds":{"left":0.6417969,"top":0.24305555,"width":0.00546875,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXTextField","text":"04/17/2026","depth":12,"bounds":{"left":0.65117186,"top":0.24097222,"width":0.053515624,"height":0.017361112},"value":"04/17/2026","help_text":"","placeholder":"MM/DD/YYYY","role_description":"text field","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXMenuButton","text":"Log ID","depth":12,"bounds":{"left":0.2921875,"top":0.28680557,"width":0.039453126,"height":0.027777778},"help_text":"","role_description":"menu button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Log ID","depth":18,"bounds":{"left":0.29882812,"top":0.29375,"width":0.019921875,"height":0.013888889},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXTextField","text":"Search by log ID","depth":12,"bounds":{"left":0.33125,"top":0.28680557,"width":0.3046875,"height":0.027777778},"help_text":"","role_description":"search text field","subrole":"AXSearchField","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXButton","text":"Export logs (CSV)","depth":11,"bounds":{"left":0.6359375,"top":0.28680557,"width":0.06875,"height":0.027777778},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Export logs (CSV)","depth":13,"bounds":{"left":0.65117186,"top":0.29444444,"width":0.0484375,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"STATUS","depth":13,"bounds":{"left":0.33125,"top":0.3375,"width":0.01796875,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"SUBSCRIPTION TYPE","depth":13,"bounds":{"left":0.3734375,"top":0.3375,"width":0.050390624,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"BATCH ID","depth":13,"bounds":{"left":0.46601564,"top":0.3375,"width":0.023046875,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"ATTEMPT START","depth":13,"bounds":{"left":0.61445314,"top":0.3375,"width":0.037890624,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"204","depth":13,"bounds":{"left":0.33125,"top":0.36944443,"width":0.009765625,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"deal.associationChange","depth":13,"bounds":{"left":0.3734375,"top":0.36944443,"width":0.06171875,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"49845354-415a-461a-bc92-c5b62bb46ce0","depth":13,"bounds":{"left":0.46601564,"top":0.36944443,"width":0.109375,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"April 17, 2026 4:26 AM EDT","depth":13,"bounds":{"left":0.61445314,"top":0.36944443,"width":0.0671875,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"204","depth":13,"bounds":{"left":0.33125,"top":0.40833333,"width":0.009765625,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"deal.associationChange","depth":13,"bounds":{"left":0.3734375,"top":0.40833333,"width":0.06171875,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"e456953e-4034-4375-bb5c-3d81bbae99d5","depth":13,"bounds":{"left":0.46601564,"top":0.40833333,"width":0.109375,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"}]...
|
-3667076530124337702
|
-4880353125262389107
|
idle
|
accessibility
|
NULL
|
Workers | Datadog
Developers | HubSpot
Developers Workers | Datadog
Developers | HubSpot
Developers | HubSpot
Close tab
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
New Tab
Customize sidebar
Open Google Gemini (⌃X)
Tabs from other devices
Open history (⇧⌘H)
Open bookmarks (⌘B)
HubSpot logo
Find or Ask
⌘
K
Create new
Scroll up
Scroll down
Back to all apps
Back to all apps
Jiminny
Jiminny
Created by
Jiminny #127
Jiminny
#
127
Basic info
Basic info
Contact & support
Contact & support
Monitoring
Monitoring
Features
Features
CRM cards
CRM cards
UI extensions BETA
UI extensions
BETA
Timeline events
Timeline events
Webhooks
Webhooks
App settings
App settings
More features
More features
API calls
API calls
Webhooks
Webhooks
App settings
App settings
UI extensions BETA
UI extensions
BETA
Log traces BETA
Log traces
BETA
OAuth
OAuth
Filter by:
Deal Close
Deal
Close
deal.creation Close deal.propertyChange Close deal.associationChange Close
deal.creation
Close
deal.propertyChange
Close
deal.associationChange
Close
Status
Status
Start date
End date
04/12/2026
to
04/17/2026
Log ID
Log ID
Search by log ID
Export logs (CSV)
Export logs (CSV)
STATUS
SUBSCRIPTION TYPE
BATCH ID
ATTEMPT START
204
deal.associationChange
49845354-415a-461a-bc92-c5b62bb46ce0
April 17, 2026 4:26 AM EDT
204
deal.associationChange
e456953e-4034-4375-bb5c-3d81bbae99d5...
|
NULL
|
|
44010
|
933
|
0
|
2026-04-17T08:29:38.463743+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776414578463_m1.jpg...
|
Firefox
|
Developers | HubSpot — Work
|
1
|
app.hubspot.com/developer/2752939/application/3848 app.hubspot.com/developer/2752939/application/38484/monitoring/webhooks?objectTypeIds=0-3&subscriptionTypes=deal.creation&subscriptionTypes=deal.propertyChange&subscriptionTypes=deal.associationChange...
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Workers | Datadog
Developers | HubSpot
Developers Workers | Datadog
Developers | HubSpot
Developers | HubSpot
Close tab
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
New Tab
Customize sidebar
Open Google Gemini (⌃X)
Tabs from other devices
Open history (⇧⌘H)
Open bookmarks (⌘B)
HubSpot logo
Find or Ask
⌘
K
Create new
Scroll up
Scroll down
Back to all apps
Back to all apps
Jiminny
Jiminny
Created by
Jiminny #127
Jiminny
#
127
Basic info
Basic info
Contact & support
Contact & support
Monitoring
Monitoring
Features
Features
CRM cards
CRM cards
UI extensions BETA
UI extensions
BETA
Timeline events
Timeline events
Webhooks
Webhooks
App settings
App settings
More features
More features
API calls
API calls
Webhooks
Webhooks
App settings
App settings
UI extensions BETA
UI extensions
BETA
Log traces BETA
Log traces
BETA
OAuth
OAuth
Filter by:
Deal Close
Deal
Close
deal.creation Close deal.propertyChange Close deal.associationChange Close
deal.creation
Close
deal.propertyChange
Close
deal.associationChange
Close
Status
Status
Start date
End date
04/12/2026
to
04/17/2026
Log ID
Log ID
Search by log ID
Export logs (CSV)
Export logs (CSV)
STATUS
SUBSCRIPTION TYPE
BATCH ID
ATTEMPT START
204
deal.associationChange
49845354-415a-461a-bc92-c5b62bb46ce0
April 17, 2026 4:26 AM EDT
204
deal.associationChange
e456953e-4034-4375-bb5c-3d81bbae99d5
April 17, 2026 4:26 AM EDT...
|
[{"role":"AXRadioButton","text [{"role":"AXRadioButton","text":"Workers | Datadog","depth":4,"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXRadioButton","text":"Developers | HubSpot","depth":4,"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":true},{"role":"AXStaticText","text":"Developers | HubSpot","depth":5,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Close tab","depth":5,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXRadioButton","text":"Inbox (1,574) - lukas.kovalik@jiminny.com - Jiminny Mail","depth":4,"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Inbox (1,574) - lukas.kovalik@jiminny.com - Jiminny Mail","depth":5,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXRadioButton","text":"Inbox (3,737) - integration-account@jiminny.com - Jiminny Mail","depth":4,"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Inbox (3,737) - integration-account@jiminny.com - Jiminny Mail","depth":5,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"New Tab","depth":4,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Customize sidebar","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open Google Gemini (⌃X)","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Tabs from other devices","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open history (⇧⌘H)","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open bookmarks (⌘B)","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXLink","text":"HubSpot logo","depth":9,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXTextField","text":"Find or Ask","depth":11,"help_text":"","role_description":"search text field","subrole":"AXSearchField","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"⌘","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"K","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXMenuButton","text":"Create new","depth":9,"help_text":"","role_description":"menu button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXButton","text":"Scroll up","depth":9,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXButton","text":"Scroll down","depth":9,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXLink","text":"Back to all apps","depth":10,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Back to all apps","depth":12,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXHeading","text":"Jiminny","depth":10,"help_text":"","role_description":"heading","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Jiminny","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Created by","depth":10,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"Jiminny #127","depth":10,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Jiminny","depth":11,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"#","depth":11,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"127","depth":11,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"Basic info","depth":12,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Basic info","depth":14,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"Contact & support","depth":12,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Contact & support","depth":14,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"Monitoring","depth":12,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":true},{"role":"AXStaticText","text":"Monitoring","depth":14,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXHeading","text":"Features","depth":10,"help_text":"","role_description":"heading","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Features","depth":11,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"CRM cards","depth":12,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"CRM cards","depth":14,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"UI extensions BETA","depth":12,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"UI extensions","depth":14,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"BETA","depth":14,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"Timeline events","depth":12,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Timeline events","depth":14,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"Webhooks","depth":12,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":true},{"role":"AXStaticText","text":"Webhooks","depth":14,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"App settings","depth":12,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"App settings","depth":14,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"More features","depth":12,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"More features","depth":14,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"API calls","depth":12,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"API calls","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"Webhooks","depth":12,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Webhooks","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"App settings","depth":12,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"App settings","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"UI extensions BETA","depth":12,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"UI extensions","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"BETA","depth":14,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"Log traces BETA","depth":12,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Log traces","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"BETA","depth":14,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"OAuth","depth":12,"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"OAuth","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Filter by:","depth":11,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXMenuButton","text":"Deal Close","depth":12,"help_text":"","role_description":"menu button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Deal","depth":21,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Close","depth":16,"role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXMenuButton","text":"deal.creation Close deal.propertyChange Close deal.associationChange Close","depth":12,"help_text":"","role_description":"menu button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"deal.creation","depth":21,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Close","depth":16,"role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"deal.propertyChange","depth":21,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Close","depth":16,"role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"deal.associationChange","depth":21,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Close","depth":16,"role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXMenuButton","text":"Status","depth":12,"help_text":"","role_description":"menu button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Status","depth":15,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Start date","depth":12,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"End date","depth":12,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXTextField","text":"04/12/2026","depth":12,"value":"04/12/2026","help_text":"","placeholder":"MM/DD/YYYY","role_description":"text field","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"to","depth":12,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXTextField","text":"04/17/2026","depth":12,"value":"04/17/2026","help_text":"","placeholder":"MM/DD/YYYY","role_description":"text field","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXMenuButton","text":"Log ID","depth":12,"help_text":"","role_description":"menu button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Log ID","depth":18,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXTextField","text":"Search by log ID","depth":12,"help_text":"","role_description":"search text field","subrole":"AXSearchField","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXButton","text":"Export logs (CSV)","depth":11,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Export logs (CSV)","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"STATUS","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"SUBSCRIPTION TYPE","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"BATCH ID","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"ATTEMPT START","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"204","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"deal.associationChange","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"49845354-415a-461a-bc92-c5b62bb46ce0","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"April 17, 2026 4:26 AM EDT","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"204","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"deal.associationChange","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"e456953e-4034-4375-bb5c-3d81bbae99d5","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"April 17, 2026 4:26 AM EDT","depth":13,"help_text":"","role_description":"text","subrole":"AXUnknown"}]...
|
7902201284774468120
|
-7186191736429571955
|
visual_change
|
accessibility
|
NULL
|
Workers | Datadog
Developers | HubSpot
Developers Workers | Datadog
Developers | HubSpot
Developers | HubSpot
Close tab
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
Inbox (3,737) - [EMAIL] - Jiminny Mail
New Tab
Customize sidebar
Open Google Gemini (⌃X)
Tabs from other devices
Open history (⇧⌘H)
Open bookmarks (⌘B)
HubSpot logo
Find or Ask
⌘
K
Create new
Scroll up
Scroll down
Back to all apps
Back to all apps
Jiminny
Jiminny
Created by
Jiminny #127
Jiminny
#
127
Basic info
Basic info
Contact & support
Contact & support
Monitoring
Monitoring
Features
Features
CRM cards
CRM cards
UI extensions BETA
UI extensions
BETA
Timeline events
Timeline events
Webhooks
Webhooks
App settings
App settings
More features
More features
API calls
API calls
Webhooks
Webhooks
App settings
App settings
UI extensions BETA
UI extensions
BETA
Log traces BETA
Log traces
BETA
OAuth
OAuth
Filter by:
Deal Close
Deal
Close
deal.creation Close deal.propertyChange Close deal.associationChange Close
deal.creation
Close
deal.propertyChange
Close
deal.associationChange
Close
Status
Status
Start date
End date
04/12/2026
to
04/17/2026
Log ID
Log ID
Search by log ID
Export logs (CSV)
Export logs (CSV)
STATUS
SUBSCRIPTION TYPE
BATCH ID
ATTEMPT START
204
deal.associationChange
49845354-415a-461a-bc92-c5b62bb46ce0
April 17, 2026 4:26 AM EDT
204
deal.associationChange
e456953e-4034-4375-bb5c-3d81bbae99d5
April 17, 2026 4:26 AM EDT...
|
NULL
|
|
44014
|
934
|
0
|
2026-04-17T08:29:49.300560+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776414589300_m2.jpg...
|
PhpStorm
|
faVsco.js – ProcessAiAutomationAnalysisResults.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Firefox FileEoit.•D<→View History Bookmarks P Firefox FileEoit.•D<→View History Bookmarks ProfilesTools Window HelpDevelopers | HubSpotM Inbox (1,574) - lukas.kovalik@jimin|M Inbox (3,737) - integration-accounT New Tab© app.hubspot.com/developer/2752939/application/38484/monitoring/webhooks?objectTypelds=0-3&subscriptionTypes=deal.creation&subscriptionTypes=deal.propertyChange&subscriptionTypes=deal.assoc tQ Find or AskUpgrade0• Assistant> 0lablsauruty‹ Back to all appsJiminnyCreated by Jiminny #127bosic IntoContact & supportMonitoringFeaturesCRM cardsUI extensionsTimeline eventsWebhooksApp settingsMore featuresoal+API callsWebhooksApp settingsUI extensionsLog tracesDeal x-deal.creation x deal.propertyChange x deal.associationChange x -Filter by:Status +Log ID+Search by log IDSTATUS204204204204204204204204204204204204204204204204SUBSCRIPTION TYPEdeal.associationChangedeal.associationChangedeal.associationChangedeal.associationChangedeal.creationdeal.associationChangedeal.creationdeal.associationChangedeal.associationChangedeal.associationChangedeal.associationChangedeal.creationdeal.associationChangedeal.associationChangedeal.associationChangedeal.associationChangeBATCH ID49845354-415a-461a-bc92-c5b62bb46ce0e456953e-4034-4375-bb5c-3d81bbae99d5c35a6fb1-1e86-4103-a3fc-12297137781fC35a6fb1-1e86-4103-a3fc-12297137781fbddb540c-8487-418e-912d-85ea6fa4583c37eeb7b4-2f22-4eb0-bbf9-bfea5295b418a16d1af6-4739-4a6c-b42e-9708c192792dal6d1af6-4739-4a6c-b42e-9708c192792dal6d1af6-4739-4a6c-b42e-9708c192792dde668243-8dd2-45cf-a69d-364c16046d8C0/1/0<40-Y0C/-4041-090/-48000500/000e7dabe89-774f-4c22-b34d-d7c04ab4f07858ba454b-1330-4091-9328-70aa348f89bd58ba454b-1330-4091-9328-70aa348f89bd58ba454b-1330-4091-9328-70aa348f89bd91fObbbe-7ab6-48a4-9bf5-f94399cef362aisobbbs Jabe hond Obee sorzoncaszenOAuth# 04/12/2026Backend Chapter • 1m leftAL AutomatedReportsCommandTest~100% CS•8 • Fri 17 Apr 11:29:48nvestigating HubSpot\Listeners|PendingAnalysis|OpportunityPendingAiAnalysisAfterStageChanged:ate the opportunityInityrendingAiAnalysisArlerstagecnanged listener class In 4.205¡elu valuesoel vice execule - uoes ll uoudle te opvortunly [EMAIL]'s the full chain:# 04/17/2026• Export logs (CSV)ATTEMPT STARTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTAad aa none dine nlaeatues trom dealob (queued)O to refresh local dataecureback to CRM (HubSpot)ed CRM field values (not→syncupporcunity —rroortunity from HubSpot,after writing - UpdateCrmthrough the normalS. oo tnis Al auromational trigger for the repeated importStages calls you're seeing, separate fromC1l -4.6Winasun leauir-dfa 4 spaces...
|
NULL
|
-75131274060343055
|
NULL
|
click
|
ocr
|
NULL
|
Firefox FileEoit.•D<→View History Bookmarks P Firefox FileEoit.•D<→View History Bookmarks ProfilesTools Window HelpDevelopers | HubSpotM Inbox (1,574) - lukas.kovalik@jimin|M Inbox (3,737) - integration-accounT New Tab© app.hubspot.com/developer/2752939/application/38484/monitoring/webhooks?objectTypelds=0-3&subscriptionTypes=deal.creation&subscriptionTypes=deal.propertyChange&subscriptionTypes=deal.assoc tQ Find or AskUpgrade0• Assistant> 0lablsauruty‹ Back to all appsJiminnyCreated by Jiminny #127bosic IntoContact & supportMonitoringFeaturesCRM cardsUI extensionsTimeline eventsWebhooksApp settingsMore featuresoal+API callsWebhooksApp settingsUI extensionsLog tracesDeal x-deal.creation x deal.propertyChange x deal.associationChange x -Filter by:Status +Log ID+Search by log IDSTATUS204204204204204204204204204204204204204204204204SUBSCRIPTION TYPEdeal.associationChangedeal.associationChangedeal.associationChangedeal.associationChangedeal.creationdeal.associationChangedeal.creationdeal.associationChangedeal.associationChangedeal.associationChangedeal.associationChangedeal.creationdeal.associationChangedeal.associationChangedeal.associationChangedeal.associationChangeBATCH ID49845354-415a-461a-bc92-c5b62bb46ce0e456953e-4034-4375-bb5c-3d81bbae99d5c35a6fb1-1e86-4103-a3fc-12297137781fC35a6fb1-1e86-4103-a3fc-12297137781fbddb540c-8487-418e-912d-85ea6fa4583c37eeb7b4-2f22-4eb0-bbf9-bfea5295b418a16d1af6-4739-4a6c-b42e-9708c192792dal6d1af6-4739-4a6c-b42e-9708c192792dal6d1af6-4739-4a6c-b42e-9708c192792dde668243-8dd2-45cf-a69d-364c16046d8C0/1/0<40-Y0C/-4041-090/-48000500/000e7dabe89-774f-4c22-b34d-d7c04ab4f07858ba454b-1330-4091-9328-70aa348f89bd58ba454b-1330-4091-9328-70aa348f89bd58ba454b-1330-4091-9328-70aa348f89bd91fObbbe-7ab6-48a4-9bf5-f94399cef362aisobbbs Jabe hond Obee sorzoncaszenOAuth# 04/12/2026Backend Chapter • 1m leftAL AutomatedReportsCommandTest~100% CS•8 • Fri 17 Apr 11:29:48nvestigating HubSpot\Listeners|PendingAnalysis|OpportunityPendingAiAnalysisAfterStageChanged:ate the opportunityInityrendingAiAnalysisArlerstagecnanged listener class In 4.205¡elu valuesoel vice execule - uoes ll uoudle te opvortunly [EMAIL]'s the full chain:# 04/17/2026• Export logs (CSV)ATTEMPT STARTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTApril 17, 2026 4:26 AM EDTAad aa none dine nlaeatues trom dealob (queued)O to refresh local dataecureback to CRM (HubSpot)ed CRM field values (not→syncupporcunity —rroortunity from HubSpot,after writing - UpdateCrmthrough the normalS. oo tnis Al auromational trigger for the repeated importStages calls you're seeing, separate fromC1l -4.6Winasun leauir-dfa 4 spaces...
|
44009
|
|
44173
|
NULL
|
0
|
2026-04-17T08:34:59.874944+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776414899874_m1.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
FirefoxFileEditViewHistoryBookmarksProfilesToolsWi FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelpmeet.google.com/xpx-omah-rkn‹ >0 llSupport Daily - in 3h 26 m100% C8 • Fri 17 Apr 11:34:596+llian Kyuchukov (Presenting, annotating)BraveViewProfiesHelpKuroe ounno oeaoroldocooCloudWanch | us-east-2CloudWatch | us-east-2@ DEV Simineyhttps://us-east-2.console.aws.amazon.com/cloudwatch/home?regionsus-east-2#logsV2:logs-insightsS3FqueryDetalS3.PROD EU JiminnyQ My PRS• Assigned• To ReviewAminny Prophet W..3 Pipeline7594349aws[Option+S) ©Logs InsightsOeneralLoos insichts oty½ Query generatorQ Fields• Saved and sample queries* Query commands|Run query• Completed. Query executed for 28 log groups.Update saved querySchedule queryLogs (932)Patterns (4)VisualizationLogs (932)(7 Service-Desk - Qu.Sentry4@ AWSUnited States (Ohio) •• Q 8• Frl17 Apr 11:34.All Bookmarkst ID: 4103-4619-5943n.Vien_Only 0 1mINNVasil Vasilevllian KyuchukovShare resultsAdd to dashboardShowing 932 of 932 records matched ©168,877 records (39.2 MB) scanned in 26s @ 65,153 records/s (15.1 MB/s)Q Filter toble results (cose insensitive)toeothres#logStreonidfmessope• 2.etinestomp2026-04-17704:25:01.75122026-84-17784:25:01.75122026-04-17T04:25:02.35022026-04-17704:25:02.4532|workes-delayed/worker-delayed/37ea68429te94207a6edße7213a3eefO L27030621-06ca-430d-bfca-2c65a436017:110671767366c4541l51e0654625e16628e9216211a16a3462589666063863e12::1776394248691(2826-04-17 84:25:00] production.INFO: [RunACtivityAlAnalysisListener) Opportunity triggered Al Analysis ("contextObjectid":19862190, "contextObjectType":"opportunity", "cratenplatefieldids":(142,202,143,144,203, 145, 146, 147,148, 149, 150, 151, 152, 153, 154, 155, 156,157,1S8], "triфрer1d":19862190, "tripperType": "opportunity") ("correlation_1d*:*574c2b18-9410-43fb-8c8b-|соPICт/2T2aS trace0100a3360)-3023-4281-3848-70602366553721776399900077"„"code": 500, "response":"Internal Server Error") ("correlation_id": "61325321-f23c-49c6-9e7a-96365c9806f7*, "troce_id": "0ba33eb9-3623-4287-0048-78e823ec3837*}1 сorreaлion10 • олома-тек-в-уeг0-90305896001 00088- [CREDIT_CARD]-[CREDIT_CARD] 21correlation1d: 01345321-125-4%cb-Уe70-У0365c960bt, troce,10: [CREDIT_CARD]-0048-700256C5637(2826-04-17 04:25:02] production.INFO: [RunActivityA(Analysististener) Opportunity trigsered Al Analysis ("contextObjectId":19862190, "contextObjectType": "opportunity", "crnTerpletefieldlds": [142,202,143, 144.@CoudShellSI2024-11_6.56.pngMihail MihaylovNikolay NikolovLukas Kovalik11:34 AM Daily - Processing...
|
NULL
|
-427576112433358305
|
NULL
|
click
|
ocr
|
NULL
|
FirefoxFileEditViewHistoryBookmarksProfilesToolsWi FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelpmeet.google.com/xpx-omah-rkn‹ >0 llSupport Daily - in 3h 26 m100% C8 • Fri 17 Apr 11:34:596+llian Kyuchukov (Presenting, annotating)BraveViewProfiesHelpKuroe ounno oeaoroldocooCloudWanch | us-east-2CloudWatch | us-east-2@ DEV Simineyhttps://us-east-2.console.aws.amazon.com/cloudwatch/home?regionsus-east-2#logsV2:logs-insightsS3FqueryDetalS3.PROD EU JiminnyQ My PRS• Assigned• To ReviewAminny Prophet W..3 Pipeline7594349aws[Option+S) ©Logs InsightsOeneralLoos insichts oty½ Query generatorQ Fields• Saved and sample queries* Query commands|Run query• Completed. Query executed for 28 log groups.Update saved querySchedule queryLogs (932)Patterns (4)VisualizationLogs (932)(7 Service-Desk - Qu.Sentry4@ AWSUnited States (Ohio) •• Q 8• Frl17 Apr 11:34.All Bookmarkst ID: 4103-4619-5943n.Vien_Only 0 1mINNVasil Vasilevllian KyuchukovShare resultsAdd to dashboardShowing 932 of 932 records matched ©168,877 records (39.2 MB) scanned in 26s @ 65,153 records/s (15.1 MB/s)Q Filter toble results (cose insensitive)toeothres#logStreonidfmessope• 2.etinestomp2026-04-17704:25:01.75122026-84-17784:25:01.75122026-04-17T04:25:02.35022026-04-17704:25:02.4532|workes-delayed/worker-delayed/37ea68429te94207a6edße7213a3eefO L27030621-06ca-430d-bfca-2c65a436017:110671767366c4541l51e0654625e16628e9216211a16a3462589666063863e12::1776394248691(2826-04-17 84:25:00] production.INFO: [RunACtivityAlAnalysisListener) Opportunity triggered Al Analysis ("contextObjectid":19862190, "contextObjectType":"opportunity", "cratenplatefieldids":(142,202,143,144,203, 145, 146, 147,148, 149, 150, 151, 152, 153, 154, 155, 156,157,1S8], "triфрer1d":19862190, "tripperType": "opportunity") ("correlation_1d*:*574c2b18-9410-43fb-8c8b-|соPICт/2T2aS trace0100a3360)-3023-4281-3848-70602366553721776399900077"„"code": 500, "response":"Internal Server Error") ("correlation_id": "61325321-f23c-49c6-9e7a-96365c9806f7*, "troce_id": "0ba33eb9-3623-4287-0048-78e823ec3837*}1 сorreaлion10 • олома-тек-в-уeг0-90305896001 00088- [CREDIT_CARD]-[CREDIT_CARD] 21correlation1d: 01345321-125-4%cb-Уe70-У0365c960bt, troce,10: [CREDIT_CARD]-0048-700256C5637(2826-04-17 04:25:02] production.INFO: [RunActivityA(Analysististener) Opportunity trigsered Al Analysis ("contextObjectId":19862190, "contextObjectType": "opportunity", "crnTerpletefieldlds": [142,202,143, 144.@CoudShellSI2024-11_6.56.pngMihail MihaylovNikolay NikolovLukas Kovalik11:34 AM Daily - Processing...
|
NULL
|
|
44174
|
NULL
|
0
|
2026-04-17T08:34:59.874927+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776414899874_m2.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
FirefoxFileEoitViewHistory BookmarksProfilesToolsW FirefoxFileEoitViewHistory BookmarksProfilesToolsWindow HelpDevelopers | HubSpotM Inbox (1,574) - lukas.kovalik@jimin|M° 120216 is your HubSpot Log in CocCa CloudWatch | eu-west-1New TabZ Configure SSH access to multiple+ New Tabeu-west-1.console.aws.amazon.com/cloudwatch/home?region=eu-west-1#logsV2:logs-insights$3FqueryDetail$3D~(end~0~start~-3600~timeType~'RELATIVE~tz~'UTC~unit~'seconds~editorString~'fields*2aws• search[Option+S]©@ ộ Europe (Ireland) •O EC2* CodeDeployElastiCache F0? Aurora and RDS liäl Amazon OpenSearch Ser...• CloudFrontEia MediaLive© Elastic Container ServiceCloudWatch > Logs InsightsG 53Ca CloudWatchQuery definition InfoLog Analytics a unified observability platform for a smoother experience, now in preview mode. Click here to try it out!30m12hCustomCompare (Off)UTC timezoneL Start tailingyuery scopeLou croupsProperty selectorLog group nameSelect up to 50 log groupsBrowse: Log Groups | Facets | Lookup tablesClear all )Monitorina accountl05/201SS/11E Show more chosen log groups (+25)fields @timestamp, @message, @logStream, @log•muter chessade uke: 1994349/ 41filter @message not like /Analytic/ | filter @message not like /Transcript/mtaller cnessdue not' lake wednook"Taller chessace not' uikemeecinabol?I limit 10000Account ID: 7657-2019-9711EUf Support Daily - in 3h 26mA100% C 8• Fri 17 Apr 11:34:59QueryQuery commands• fields• filter• filterindex• stats• sort• limit• parse• dedup• pattern• anomaly - new*diff• unnest• unmaskLearn more 2?CloudWatch Logs Insights query syntaxActionsread-onlyread-onlyread-onlyread-onlyread-onlyLogs Insights QL v)Run queryCancelLogs (-)Patterns (-)Logs (-)/ Query generatorg FieldsSaved and sample queries? Query commandsSaveSchedule queryHistoryVisualizationSQLDrop?# Summarize results# Investigate v ) ( Share resultsRun a query to res related eventsExport resultsAdd to dashboard0)CloudShellreedback© 2026, Amazon Web Services, Inc. or its affiliates.Privacy Terms Cookie preferences...
|
NULL
|
5045263215057048355
|
NULL
|
click
|
ocr
|
NULL
|
FirefoxFileEoitViewHistory BookmarksProfilesToolsW FirefoxFileEoitViewHistory BookmarksProfilesToolsWindow HelpDevelopers | HubSpotM Inbox (1,574) - lukas.kovalik@jimin|M° 120216 is your HubSpot Log in CocCa CloudWatch | eu-west-1New TabZ Configure SSH access to multiple+ New Tabeu-west-1.console.aws.amazon.com/cloudwatch/home?region=eu-west-1#logsV2:logs-insights$3FqueryDetail$3D~(end~0~start~-3600~timeType~'RELATIVE~tz~'UTC~unit~'seconds~editorString~'fields*2aws• search[Option+S]©@ ộ Europe (Ireland) •O EC2* CodeDeployElastiCache F0? Aurora and RDS liäl Amazon OpenSearch Ser...• CloudFrontEia MediaLive© Elastic Container ServiceCloudWatch > Logs InsightsG 53Ca CloudWatchQuery definition InfoLog Analytics a unified observability platform for a smoother experience, now in preview mode. Click here to try it out!30m12hCustomCompare (Off)UTC timezoneL Start tailingyuery scopeLou croupsProperty selectorLog group nameSelect up to 50 log groupsBrowse: Log Groups | Facets | Lookup tablesClear all )Monitorina accountl05/201SS/11E Show more chosen log groups (+25)fields @timestamp, @message, @logStream, @log•muter chessade uke: 1994349/ 41filter @message not like /Analytic/ | filter @message not like /Transcript/mtaller cnessdue not' lake wednook"Taller chessace not' uikemeecinabol?I limit 10000Account ID: 7657-2019-9711EUf Support Daily - in 3h 26mA100% C 8• Fri 17 Apr 11:34:59QueryQuery commands• fields• filter• filterindex• stats• sort• limit• parse• dedup• pattern• anomaly - new*diff• unnest• unmaskLearn more 2?CloudWatch Logs Insights query syntaxActionsread-onlyread-onlyread-onlyread-onlyread-onlyLogs Insights QL v)Run queryCancelLogs (-)Patterns (-)Logs (-)/ Query generatorg FieldsSaved and sample queries? Query commandsSaveSchedule queryHistoryVisualizationSQLDrop?# Summarize results# Investigate v ) ( Share resultsRun a query to res related eventsExport resultsAdd to dashboard0)CloudShellreedback© 2026, Amazon Web Services, Inc. or its affiliates.Privacy Terms Cookie preferences...
|
NULL
|
|
44175
|
935
|
0
|
2026-04-17T08:35:04.250121+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776414904250_m1.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
FirefoxFileEditViewHistoryBookmarksProfilesToolsWi FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelpmeet.google.com/xpx-omah-rkn‹$0(aolSupport Daily • in 3 h 25 m100% <8 • Fri 17 Apr 11:35:046+llian Kyuchukov (Presenting, annotating)BraveViewProfilesHelpurorouino oraicroleoceooCloudWatch | us-east-2@ DEV Siminmyhttps//us-east-2.console.aws.amazon.com/cloudwatch/home?regionsus-east-2#logsV2:logs-insightsS3FqueryDetailS3.PROD EU JiminnyQ My PRs• Assigned@ Jiminny Prophet W..3 Pipelineaws[Option+S) ©CloudWatchLogs InsightsGeneralLoos insichts oty½ Query generatorQ Fields• Saved and sample queriesQuery commands|Run queryUpdate saved query• Completed. Query executed for 28 log groups.Schedule queryLogs (932)Patterns (4)VisualizationLogs (932)40(7 Service-Desk - Qu.4 Sentry@ AWS|4United States (Ohio) •• Q 8• Frl17 Apr 11:35.[J All BookmarksVasil Vasilevlian KyuchukovShare resultsAdd to dashboardShowing 932 of 932 records matched ©168,877 records (39.2 MB) scanned in 2.6s @ 65,153 records/s (15.1 MB/s)Q Filter toble results (cose insensitive)tosothresPlogStreonidfnessopeetímestomp2026-04-17T04:25:01.75122026-84-17784:25:01.75122026-04-17704:25:02.4532|@CloudShellMihail MihaylovNikolay Nikolovworker-deluyed/morker-delryed/87eu6fe291e9420706edBe7211a3eefo 227080621-06ca-43bd-bfca-2c65aa436017:11d671767366c4541l51ea654625e16628e9216211816a3432589666063863e12: :1776394448691[2026-04-17 04:25:00] production.INFO: [RunActivityAlAnalysisListener) Opportunity triggered Al Analysis ("contextObjectid":19862190, "contextobjectType":"opportunity", "cratenplatefieldids":(142,202,143,144,203, 145, 146, 147,148, 149, 150, 151, 152, 153, 154, 155, 156,157,1S8], "trigper1d":19862190, "tripperType" :"opportunity") ("correlation_1d*:*574c2b18-9418-43fb-8c8b-|сорIст/eт2aS traсс000a3360)-3023-4267-[CREDIT_CARD] 21776399900877","code": 500, "response":"Internal Server Error") ("correlation_id": *61325321-f23c-49c6-9e7a-96365c9806f7*, "troce_id": "0ba33eb9-3623-4287-0048-78e823ec3837*}11 correiaсionsio • отом-тек-уо-уего-90305896001 Сroсe18: [CREDIT_CARD]-0096-10688580891 21 correlation_1d: 01345321-1<5-4%b-Уe70-У0365c960bt, troce,1d: [CREDIT_CARD]-0048-70e025eC5537 H(2826-04-17 04:25:02] production.INFO: [RunActivityA(Analysististener) Opportunity triggered Al Analysis ("contextObjectId":19862190, "contextObjectType*:"opportunity", "crnTerpleteFieldlds": [142,202,143, 144.zon Web Services, Inc. or its affillates.2024-11_6.56,pngLukas Kovalik11:35 AM | Daily - Processing...
|
NULL
|
-5079751359360735477
|
NULL
|
visual_change
|
ocr
|
NULL
|
FirefoxFileEditViewHistoryBookmarksProfilesToolsWi FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelpmeet.google.com/xpx-omah-rkn‹$0(aolSupport Daily • in 3 h 25 m100% <8 • Fri 17 Apr 11:35:046+llian Kyuchukov (Presenting, annotating)BraveViewProfilesHelpurorouino oraicroleoceooCloudWatch | us-east-2@ DEV Siminmyhttps//us-east-2.console.aws.amazon.com/cloudwatch/home?regionsus-east-2#logsV2:logs-insightsS3FqueryDetailS3.PROD EU JiminnyQ My PRs• Assigned@ Jiminny Prophet W..3 Pipelineaws[Option+S) ©CloudWatchLogs InsightsGeneralLoos insichts oty½ Query generatorQ Fields• Saved and sample queriesQuery commands|Run queryUpdate saved query• Completed. Query executed for 28 log groups.Schedule queryLogs (932)Patterns (4)VisualizationLogs (932)40(7 Service-Desk - Qu.4 Sentry@ AWS|4United States (Ohio) •• Q 8• Frl17 Apr 11:35.[J All BookmarksVasil Vasilevlian KyuchukovShare resultsAdd to dashboardShowing 932 of 932 records matched ©168,877 records (39.2 MB) scanned in 2.6s @ 65,153 records/s (15.1 MB/s)Q Filter toble results (cose insensitive)tosothresPlogStreonidfnessopeetímestomp2026-04-17T04:25:01.75122026-84-17784:25:01.75122026-04-17704:25:02.4532|@CloudShellMihail MihaylovNikolay Nikolovworker-deluyed/morker-delryed/87eu6fe291e9420706edBe7211a3eefo 227080621-06ca-43bd-bfca-2c65aa436017:11d671767366c4541l51ea654625e16628e9216211816a3432589666063863e12: :1776394448691[2026-04-17 04:25:00] production.INFO: [RunActivityAlAnalysisListener) Opportunity triggered Al Analysis ("contextObjectid":19862190, "contextobjectType":"opportunity", "cratenplatefieldids":(142,202,143,144,203, 145, 146, 147,148, 149, 150, 151, 152, 153, 154, 155, 156,157,1S8], "trigper1d":19862190, "tripperType" :"opportunity") ("correlation_1d*:*574c2b18-9418-43fb-8c8b-|сорIст/eт2aS traсс000a3360)-3023-4267-[CREDIT_CARD] 21776399900877","code": 500, "response":"Internal Server Error") ("correlation_id": *61325321-f23c-49c6-9e7a-96365c9806f7*, "troce_id": "0ba33eb9-3623-4287-0048-78e823ec3837*}11 correiaсionsio • отом-тек-уо-уего-90305896001 Сroсe18: [CREDIT_CARD]-0096-10688580891 21 correlation_1d: 01345321-1<5-4%b-Уe70-У0365c960bt, troce,1d: [CREDIT_CARD]-0048-70e025eC5537 H(2826-04-17 04:25:02] production.INFO: [RunActivityA(Analysististener) Opportunity triggered Al Analysis ("contextObjectId":19862190, "contextObjectType*:"opportunity", "crnTerpleteFieldlds": [142,202,143, 144.zon Web Services, Inc. or its affillates.2024-11_6.56,pngLukas Kovalik11:35 AM | Daily - Processing...
|
44173
|
|
44176
|
936
|
0
|
2026-04-17T08:35:08.919472+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776414908919_m2.jpg...
|
Firefox
|
CloudWatch | eu-west-1 — Work
|
1
|
eu-west-1.console.aws.amazon.com/cloudwatch/home?r eu-west-1.console.aws.amazon.com/cloudwatch/home?region=eu-west-1#logsV2:logs-insights$3FqueryDetail$3D~(end~0~start~-3600~timeType~'RELATIVE~tz~'UTC~unit~'seconds~editorString~'fields*20*40timestamp*2c*20*40message*2c*20*40logStream*2c*20*40log*0a*7c*20filter*20*40message*20like*20*2f7594349*2f*20*0a*7c*20filter*20*40message*20not*20like*20*2fAnalytic*2f*20*7c*20filter*20*40message*20not*20like*20*2fTranscript*2f*0a*7c*20filter*20*40message*20not*20like*20*2fWebhook*2f*20*7c*20filter*20*40message*20not*20like*20*2fMeetingBot*2f*20*0a*7c*20limit*2010000~queryId~'0551e814-f51a-4339-8372-80d7ba4cef27~source~(~'worker~'worker-analytics~'worker-app~'worker-audio~'worker-calendar~'worker-conferences~'worker-crm-sync~'worker-default~'worker-delayed~'worker-dialers~'worker-dialers-fifo~'worker-download~'worker-emails~'worker-meeting-bot~'worker-nudges~'worker-processing-1~'worker-processing-2~'worker-processing-3~'worker-processing-4~'worker-processing-5~'worker-processing-delayed~'worker-softphone~'worker-video~'worker-video-app~'php~'php-app)~lang~'CWLI~logClass~'STANDARD~queryBy~'logGroupName)...
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Workers | Datadog
Developers | HubSpot
Developers Workers | Datadog
Developers | HubSpot
Developers | HubSpot
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (1,574) - [EMAIL] - Jiminny Mail
120216 is your HubSpot Log In Code - [EMAIL] - Jiminny Mail
120216 is your HubSpot Log In Code - [EMAIL] - Jiminny Mail
CloudWatch | eu-west-1
CloudWatch | eu-west-1
Close tab
New Tab
New Tab
Configure SSH access to multiple environment - Engineering - Confluence
Configure SSH access to multiple environment - Engineering - Confluence
New Tab
Customize sidebar
Open Google Gemini (⌃X)
Tabs from other devices
Open history (⇧⌘H)
Open bookmarks (⌘B)
AWS Console Home
Skip to Main Content
Skip to Main Content
Amazon Q
Services
Search
Ask Amazon Q
[Option+S]
CloudShell
Notifications (none available)
Help & support
Settings
Europe (Ireland)
Europe (Ireland)
EU
Account ID: 7657-2019-9711
EU
EC2 EC2
EC2
Elastic Container Service Elastic Container Service
Elastic Container Service
S3 S3
S3
CodeDeploy CodeDeploy
CodeDeploy
CloudWatch CloudWatch
CloudWatch
ElastiCache ElastiCache
ElastiCache
Aurora and RDS Aurora and RDS
Aurora and RDS
Amazon OpenSearch Service Amazon OpenSearch Service
Amazon OpenSearch Service
CloudFront CloudFront
CloudFront...
|
[{"role":"AXRadioButton","text [{"role":"AXRadioButton","text":"Workers | Datadog","depth":4,"bounds":{"left":0.00234375,"top":0.045138888,"width":0.0890625,"height":0.028472222},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXRadioButton","text":"Developers | HubSpot","depth":4,"bounds":{"left":0.0,"top":0.08263889,"width":0.09375,"height":0.028472222},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Developers | HubSpot","depth":5,"bounds":{"left":0.015625,"top":0.09236111,"width":0.04453125,"height":0.009722223},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXRadioButton","text":"Inbox (1,574) - lukas.kovalik@jiminny.com - Jiminny Mail","depth":4,"bounds":{"left":0.0,"top":0.11111111,"width":0.09375,"height":0.028472222},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Inbox (1,574) - lukas.kovalik@jiminny.com - Jiminny Mail","depth":5,"bounds":{"left":0.015625,"top":0.12083333,"width":0.11445312,"height":0.009722223},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXRadioButton","text":"120216 is your HubSpot Log In Code - integration-account@jiminny.com - Jiminny Mail","depth":4,"bounds":{"left":0.0,"top":0.13958333,"width":0.09375,"height":0.028472222},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"120216 is your HubSpot Log In Code - integration-account@jiminny.com - Jiminny Mail","depth":5,"bounds":{"left":0.015625,"top":0.14930555,"width":0.17734376,"height":0.009722223},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXRadioButton","text":"CloudWatch | eu-west-1","depth":4,"bounds":{"left":0.0,"top":0.16805555,"width":0.09375,"height":0.028472222},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":true},{"role":"AXStaticText","text":"CloudWatch | eu-west-1","depth":5,"bounds":{"left":0.015625,"top":0.17777778,"width":0.048828125,"height":0.009722223},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Close tab","depth":5,"bounds":{"left":0.07890625,"top":0.17430556,"width":0.009375,"height":0.016666668},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXRadioButton","text":"New Tab","depth":4,"bounds":{"left":0.0,"top":0.19652778,"width":0.09375,"height":0.028472222},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"New Tab","depth":5,"bounds":{"left":0.015625,"top":0.20625,"width":0.017578125,"height":0.009722223},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXRadioButton","text":"Configure SSH access to multiple environment - Engineering - Confluence","depth":4,"bounds":{"left":0.0,"top":0.225,"width":0.09375,"height":0.028472222},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Configure SSH access to multiple environment - Engineering - Confluence","depth":5,"bounds":{"left":0.015625,"top":0.23472223,"width":0.1515625,"height":0.009722223},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"New Tab","depth":4,"bounds":{"left":0.003125,"top":0.25486112,"width":0.08710937,"height":0.022222223},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Customize sidebar","depth":6,"bounds":{"left":0.003125,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open Google Gemini (⌃X)","depth":6,"bounds":{"left":0.01640625,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Tabs from other devices","depth":6,"bounds":{"left":0.029296875,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open history (⇧⌘H)","depth":6,"bounds":{"left":0.0421875,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open bookmarks (⌘B)","depth":6,"bounds":{"left":0.05546875,"top":0.97430557,"width":0.0125,"height":0.022222223},"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXLink","text":"AWS Console Home","depth":13,"bounds":{"left":0.09375,"top":0.047916666,"width":0.025390625,"height":0.033333335},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXLink","text":"Skip to Main Content","depth":13,"bounds":{"left":0.09335937,"top":0.047222223,"width":0.0015625,"height":0.0013888889},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Skip to Main Content","depth":14,"bounds":{"left":0.09414063,"top":0.047916666,"width":0.01953125,"height":0.045138888},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Amazon Q","depth":14,"bounds":{"left":0.11953125,"top":0.047916666,"width":0.01953125,"height":0.033333335},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Services","depth":13,"bounds":{"left":0.1390625,"top":0.047916666,"width":0.01953125,"height":0.033333335},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXComboBox","text":"Search","depth":16,"bounds":{"left":0.15859374,"top":0.054166667,"width":0.2109375,"height":0.020833334},"role_description":"combo box","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Ask Amazon Q","depth":15,"bounds":{"left":0.35390624,"top":0.05625,"width":0.01171875,"height":0.016666668},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"[Option+S]","depth":16,"bounds":{"left":0.32851562,"top":0.058333334,"width":0.02734375,"height":0.0125},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXLink","text":"CloudShell","depth":14,"bounds":{"left":0.58554685,"top":0.047916666,"width":0.01875,"height":0.033333335},"help_text":"","role_description":"link","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXButton","text":"Notifications (none available)","depth":15,"bounds":{"left":0.60429686,"top":0.050694443,"width":0.01953125,"height":0.027777778},"help_text":"Notifications","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXButton","text":"Help & support","depth":15,"bounds":{"left":0.6238281,"top":0.047916666,"width":0.01953125,"height":0.033333335},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Settings","depth":15,"bounds":{"left":0.64335936,"top":0.047916666,"width":0.01953125,"height":0.033333335},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXComboBox","text":"Europe (Ireland)","depth":15,"bounds":{"left":0.6628906,"top":0.047916666,"width":0.05390625,"height":0.033333335},"value":"Europe (Ireland)","help_text":"Europe (Ireland)","role_description":"combo box","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Europe (Ireland)","depth":17,"bounds":{"left":0.6695312,"top":0.059722222,"width":0.034375,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"EU","depth":15,"bounds":{"left":0.7167969,"top":0.047916666,"width":0.07929687,"height":0.033333335},"help_text":"EU_View_Only @ jiminny-eu","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Account ID: 7657-2019-9711","depth":19,"bounds":{"left":0.7203125,"top":0.05,"width":0.06367187,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"EU","depth":18,"bounds":{"left":0.78164065,"top":0.065972224,"width":0.005859375,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"EC2 EC2","depth":16,"bounds":{"left":0.096875,"top":0.083333336,"width":0.023828125,"height":0.019444445},"role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"EC2","depth":18,"bounds":{"left":0.109375,"top":0.088194445,"width":0.008203125,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Elastic Container Service Elastic Container Service","depth":16,"bounds":{"left":0.12070312,"top":0.083333336,"width":0.06757812,"height":0.019444445},"role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Elastic Container Service","depth":18,"bounds":{"left":0.13320312,"top":0.088194445,"width":0.051953126,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"S3 S3","depth":16,"bounds":{"left":0.18828125,"top":0.083333336,"width":0.02109375,"height":0.019444445},"role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"S3","depth":18,"bounds":{"left":0.20078126,"top":0.088194445,"width":0.00546875,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"CodeDeploy CodeDeploy","depth":16,"bounds":{"left":0.209375,"top":0.083333336,"width":0.04140625,"height":0.019444445},"role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"CodeDeploy","depth":18,"bounds":{"left":0.221875,"top":0.088194445,"width":0.02578125,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"CloudWatch CloudWatch","depth":16,"bounds":{"left":0.25078124,"top":0.083333336,"width":0.04140625,"height":0.019444445},"role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"CloudWatch","depth":18,"bounds":{"left":0.26328126,"top":0.088194445,"width":0.02578125,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"ElastiCache ElastiCache","depth":16,"bounds":{"left":0.2921875,"top":0.083333336,"width":0.03984375,"height":0.019444445},"role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"ElastiCache","depth":18,"bounds":{"left":0.3046875,"top":0.088194445,"width":0.02421875,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Aurora and RDS Aurora and RDS","depth":16,"bounds":{"left":0.33203125,"top":0.083333336,"width":0.048828125,"height":0.019444445},"role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Aurora and RDS","depth":18,"bounds":{"left":0.34453124,"top":0.088194445,"width":0.033203125,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Amazon OpenSearch Service Amazon OpenSearch Service","depth":16,"bounds":{"left":0.38085938,"top":0.083333336,"width":0.07421875,"height":0.019444445},"role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Amazon OpenSearch Service","depth":18,"bounds":{"left":0.39335936,"top":0.088194445,"width":0.0609375,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"CloudFront CloudFront","depth":16,"bounds":{"left":0.45507812,"top":0.083333336,"width":0.039453126,"height":0.019444445},"role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"CloudFront","depth":18,"bounds":{"left":0.4675781,"top":0.088194445,"width":0.023828125,"height":0.010416667},"help_text":"","role_description":"text","subrole":"AXUnknown"}]...
|
8262157344193736152
|
-5171947511161373978
|
click
|
accessibility
|
NULL
|
Workers | Datadog
Developers | HubSpot
Developers Workers | Datadog
Developers | HubSpot
Developers | HubSpot
Inbox (1,574) - [EMAIL] - Jiminny Mail
Inbox (1,574) - [EMAIL] - Jiminny Mail
120216 is your HubSpot Log In Code - [EMAIL] - Jiminny Mail
120216 is your HubSpot Log In Code - [EMAIL] - Jiminny Mail
CloudWatch | eu-west-1
CloudWatch | eu-west-1
Close tab
New Tab
New Tab
Configure SSH access to multiple environment - Engineering - Confluence
Configure SSH access to multiple environment - Engineering - Confluence
New Tab
Customize sidebar
Open Google Gemini (⌃X)
Tabs from other devices
Open history (⇧⌘H)
Open bookmarks (⌘B)
AWS Console Home
Skip to Main Content
Skip to Main Content
Amazon Q
Services
Search
Ask Amazon Q
[Option+S]
CloudShell
Notifications (none available)
Help & support
Settings
Europe (Ireland)
Europe (Ireland)
EU
Account ID: 7657-2019-9711
EU
EC2 EC2
EC2
Elastic Container Service Elastic Container Service
Elastic Container Service
S3 S3
S3
CodeDeploy CodeDeploy
CodeDeploy
CloudWatch CloudWatch
CloudWatch
ElastiCache ElastiCache
ElastiCache
Aurora and RDS Aurora and RDS
Aurora and RDS
Amazon OpenSearch Service Amazon OpenSearch Service
Amazon OpenSearch Service
CloudFront CloudFront
CloudFront...
|
44174
|
|
44289
|
NULL
|
0
|
2026-04-17T08:40:17.415095+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776415217415_m2.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorToo PhpStormFileEditViewNavigateCodeLaravelRefactorToolsWindowHelpFV faVsco.s v#11894 on.ly-18009-automated-renorts-ask-liminnvProject v© AutomatedReportsService.php© SendReportJob.php© SendReportMailJob.php© ReportController.php= ids.txtTokenBuilder.php• TeamSetupController.phppnp apl.onoFilesystem.php• Team.php© CreateHeldActivityEvent.php=infection.son.dist© TrackProviderInstalledEvent.php© ActivityLogged.phpAutomatedReportsCallbackService.phpM+ INSTALL.mdM+ INTERNAL_WEBHOOK SETUP© RequestGenerateAskJiminnyReportJob.php© RequestGenerateReportJob.php© SyncOpportunity.php€ OpportunitySyncTrait.phpE jiminny_storageC Opportunity.phpOpoorunityupdated.onoOpoonunitystadeupaated.onoC EventServiceProvider.phpM+ licenses.md© OpportunityPendingAiAnalysisAfterStageChanged.php© RunOpportunityAiAnalysis.phpC Processa AutomationAnavsis?esults.onoM MakefileO package-lock.json© ImportOpportunityBatch.php€ ImportBatchJobTrait.phpx€ HasAttributes.php© Service.phpAutomaleakepontkesulc.ono= phpstan.neon.distC AutomatedReport.php= phpstan-baseline.neorTrart noortbarchsoo ratt< phpunit.xml48 X17 ATe raw_sql_query.sqlprotected function processImportBatch(requestea→ count schis->crmlasM+ KEADME.mO'processed' => count($filteredIds),ộ sonar-project.properties'duration_ms' => $durationMs,E test.py<> Untitled Diagram.xml1);Is vetur.config.js115if (! empty(SfailedIds)) {M+ WEBHOOK_FILTERING_IMPLELog: :error( message: $this->getLogPrefix() • ' Data-level failures require investigation', [› ih External Libraries'crnconfigurationid" → Sthis->crmConfigurationId,E° Scratches and Consolestarledlount"(count(sralleaias),v M Database Consoles'failedids = stalleaias,vA-U'errors' => $result['errors'] ?? [],c consoe -u4 DEAL RISKS [EU]1);1571A DI [EU]15721573A EU [EU]1574v A jiminny@localhostA console [jiminny@localt/**1575* Called by Laravel after all $tries are exhausted.1576DI [jiminny@localhost]1271577A HS_local [iminny@local128* System-level failure (HubSpot API down, timeout, OOM) - the entire handle() threwA SF [jiminny@localhost]1578129* an unhandled exception on every attempt. Requeue ALL IDs back to Redis so the next1579A zoho_dev ljiminny@locex suncuoecrs cucre ocks chell Uo.-100V & PROD131& consoe PRODI1154* This does NOT fire for data-level failures (those are caught in the per-object loop1084A console_1 [PROD]1100* and logged without retrying).1583A DI [PROD]1341584> LQA* Requeue Strategy:1585L QAi4 QAI PROD136* - Each ID is individually requeued to Redis using SADD (automatic deduplication)1586• A STAGING137* - If requeue fails for specific IDs, they are logged as permanently lost138* - Redis requeue failures are rare (Redis connection issues) but critical1588A console [STAGING]1589L console_1 [STAGING]3 usages« uranus [STAGING]140protected function requeueFailedBatch(\Throwable $exception): voidf...3-159011591› DJ Extensionsv D Scratches1861 usage1593E phpstorm_shortcuts.txt1181private function filterExisting0bjects(Configuration $crmConfig, CrmEntityRepository $crmEntityRepositor)1594=° scratch.txtC° scratch_1.json2011595lusaoe1596(° scratch_2.jsonprivate function filterExistingContacts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepositor 1597C* scratch_3.json= scratch_4.txt15981 usage1599ph, scratch_5.phpprivate function filterExistingAccounts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepositor 1600phỹ scratch_6.php2171601C° scratch_7.json11604C° stage2.jsonE test<° test.htmlph$ tmp.phpE custom.log= laravel.logA SF [jiminny@localhost]connect.vueV Onboard.vueA HS_local [jiminny@localhost]C° scratch_1.jsonÁ console [EU] xfi crm_configurations [EU]A console [PROD]d console [STAGINGX:Auto vPlayground~Ma liminnv v1553155415551556SELECT * FROM participants where activ026 A9 A22 X3 X103 ^SELECT * FROM activity_summary_logs where activity_id = 39216301;SELECT * FROM activities WHERE uuid_to_bin('c7d99fbe-1fb1-41f2-8f4d-52eSELECT * FROM activities WHERE uuid_to_bin('2e6ff4d3-9faa-447a-a8c1-9aeselect x T0Icirnoronues were cri conmouraron io = oly ano ciriliodeselect x ToIopportunities where crm_configuration_id = 319 and crm_pr1559156015611562156315641565156615671568seLect * Tromaccounts where crm_configuration_id = 319 and crm_provideselect * from contacts where crm_configuration_id = 319 and crm_provide# owner 13236 525785080# contact 116779180 665587441856 - activity - Alex Howes alex@support# contact 219247563 742723347700 - [EMAIL] 2026-03-24# company 4176133 47150650569# deal 7100953 410150124747CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE "'ENv.emall,sarx.t.owner id FROM social accounts saJOIN users u on u.id = sa.sociable_idJOIN teams t 1..n<->1: on t.id = u.team_idWHERE U. team_id = 400 and sa.provider = 'hubspot';select * from features;select * from team_features where feature_id = 40;select * from teams where id = 556; # owner: 18101, crm: 477select * from crm_configurations where id = 477;SELECT * FROM users WHERE id = 18101;SELECTCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' ELSE "' ENU. ellidat,sa.*,t.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable_idJOIN teams t1.n<->1: on t.id = u.team_idWHERE U.team_id = 556 and sa.provider = 'integration-app';select * from opportunities where id = 7594349;select * from stages where team id = 459:select * from teams where id = 459:SELECTCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' ELSE "'u.email,sa.*t.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable_idJOIN teams t1.n<->1: on t.id = u.team_idWHERE U.team_id = 459 and sa.provider = 'hubspat':> 0halCascadeAutomated Report RetiSailing...Support Daily - in 3h 20 mAAutomatedRenortsCommandTest100% C•8 • Fri 17 Apr 11:40:17Investigating HubSpot+D ...ok why is it triggered in the first place. There is no update in CRM.Ask anything (X4L)+ ‹> CodeClaude Sonnet 4.6nerate // Don't Show Anymore (today 8:59)Winasun leams1590:47 (7 chars)uir-o4 spaces...
|
NULL
|
7105931093513990397
|
NULL
|
visual_change
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorToo PhpStormFileEditViewNavigateCodeLaravelRefactorToolsWindowHelpFV faVsco.s v#11894 on.ly-18009-automated-renorts-ask-liminnvProject v© AutomatedReportsService.php© SendReportJob.php© SendReportMailJob.php© ReportController.php= ids.txtTokenBuilder.php• TeamSetupController.phppnp apl.onoFilesystem.php• Team.php© CreateHeldActivityEvent.php=infection.son.dist© TrackProviderInstalledEvent.php© ActivityLogged.phpAutomatedReportsCallbackService.phpM+ INSTALL.mdM+ INTERNAL_WEBHOOK SETUP© RequestGenerateAskJiminnyReportJob.php© RequestGenerateReportJob.php© SyncOpportunity.php€ OpportunitySyncTrait.phpE jiminny_storageC Opportunity.phpOpoorunityupdated.onoOpoonunitystadeupaated.onoC EventServiceProvider.phpM+ licenses.md© OpportunityPendingAiAnalysisAfterStageChanged.php© RunOpportunityAiAnalysis.phpC Processa AutomationAnavsis?esults.onoM MakefileO package-lock.json© ImportOpportunityBatch.php€ ImportBatchJobTrait.phpx€ HasAttributes.php© Service.phpAutomaleakepontkesulc.ono= phpstan.neon.distC AutomatedReport.php= phpstan-baseline.neorTrart noortbarchsoo ratt< phpunit.xml48 X17 ATe raw_sql_query.sqlprotected function processImportBatch(requestea→ count schis->crmlasM+ KEADME.mO'processed' => count($filteredIds),ộ sonar-project.properties'duration_ms' => $durationMs,E test.py<> Untitled Diagram.xml1);Is vetur.config.js115if (! empty(SfailedIds)) {M+ WEBHOOK_FILTERING_IMPLELog: :error( message: $this->getLogPrefix() • ' Data-level failures require investigation', [› ih External Libraries'crnconfigurationid" → Sthis->crmConfigurationId,E° Scratches and Consolestarledlount"(count(sralleaias),v M Database Consoles'failedids = stalleaias,vA-U'errors' => $result['errors'] ?? [],c consoe -u4 DEAL RISKS [EU]1);1571A DI [EU]15721573A EU [EU]1574v A jiminny@localhostA console [jiminny@localt/**1575* Called by Laravel after all $tries are exhausted.1576DI [jiminny@localhost]1271577A HS_local [iminny@local128* System-level failure (HubSpot API down, timeout, OOM) - the entire handle() threwA SF [jiminny@localhost]1578129* an unhandled exception on every attempt. Requeue ALL IDs back to Redis so the next1579A zoho_dev ljiminny@locex suncuoecrs cucre ocks chell Uo.-100V & PROD131& consoe PRODI1154* This does NOT fire for data-level failures (those are caught in the per-object loop1084A console_1 [PROD]1100* and logged without retrying).1583A DI [PROD]1341584> LQA* Requeue Strategy:1585L QAi4 QAI PROD136* - Each ID is individually requeued to Redis using SADD (automatic deduplication)1586• A STAGING137* - If requeue fails for specific IDs, they are logged as permanently lost138* - Redis requeue failures are rare (Redis connection issues) but critical1588A console [STAGING]1589L console_1 [STAGING]3 usages« uranus [STAGING]140protected function requeueFailedBatch(\Throwable $exception): voidf...3-159011591› DJ Extensionsv D Scratches1861 usage1593E phpstorm_shortcuts.txt1181private function filterExisting0bjects(Configuration $crmConfig, CrmEntityRepository $crmEntityRepositor)1594=° scratch.txtC° scratch_1.json2011595lusaoe1596(° scratch_2.jsonprivate function filterExistingContacts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepositor 1597C* scratch_3.json= scratch_4.txt15981 usage1599ph, scratch_5.phpprivate function filterExistingAccounts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepositor 1600phỹ scratch_6.php2171601C° scratch_7.json11604C° stage2.jsonE test<° test.htmlph$ tmp.phpE custom.log= laravel.logA SF [jiminny@localhost]connect.vueV Onboard.vueA HS_local [jiminny@localhost]C° scratch_1.jsonÁ console [EU] xfi crm_configurations [EU]A console [PROD]d console [STAGINGX:Auto vPlayground~Ma liminnv v1553155415551556SELECT * FROM participants where activ026 A9 A22 X3 X103 ^SELECT * FROM activity_summary_logs where activity_id = 39216301;SELECT * FROM activities WHERE uuid_to_bin('c7d99fbe-1fb1-41f2-8f4d-52eSELECT * FROM activities WHERE uuid_to_bin('2e6ff4d3-9faa-447a-a8c1-9aeselect x T0Icirnoronues were cri conmouraron io = oly ano ciriliodeselect x ToIopportunities where crm_configuration_id = 319 and crm_pr1559156015611562156315641565156615671568seLect * Tromaccounts where crm_configuration_id = 319 and crm_provideselect * from contacts where crm_configuration_id = 319 and crm_provide# owner 13236 525785080# contact 116779180 665587441856 - activity - Alex Howes alex@support# contact 219247563 742723347700 - [EMAIL] 2026-03-24# company 4176133 47150650569# deal 7100953 410150124747CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE "'ENv.emall,sarx.t.owner id FROM social accounts saJOIN users u on u.id = sa.sociable_idJOIN teams t 1..n<->1: on t.id = u.team_idWHERE U. team_id = 400 and sa.provider = 'hubspot';select * from features;select * from team_features where feature_id = 40;select * from teams where id = 556; # owner: 18101, crm: 477select * from crm_configurations where id = 477;SELECT * FROM users WHERE id = 18101;SELECTCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' ELSE "' ENU. ellidat,sa.*,t.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable_idJOIN teams t1.n<->1: on t.id = u.team_idWHERE U.team_id = 556 and sa.provider = 'integration-app';select * from opportunities where id = 7594349;select * from stages where team id = 459:select * from teams where id = 459:SELECTCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' ELSE "'u.email,sa.*t.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable_idJOIN teams t1.n<->1: on t.id = u.team_idWHERE U.team_id = 459 and sa.provider = 'hubspat':> 0halCascadeAutomated Report RetiSailing...Support Daily - in 3h 20 mAAutomatedRenortsCommandTest100% C•8 • Fri 17 Apr 11:40:17Investigating HubSpot+D ...ok why is it triggered in the first place. There is no update in CRM.Ask anything (X4L)+ ‹> CodeClaude Sonnet 4.6nerate // Don't Show Anymore (today 8:59)Winasun leams1590:47 (7 chars)uir-o4 spaces...
|
44287
|
|
44290
|
NULL
|
0
|
2026-04-17T08:40:26.291830+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776415226291_m1.jpg...
|
PhpStorm
|
faVsco.js – console [EU]
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
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,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#11894 on JY-18909-automated-reports-ask-jiminny, menu","depth":5,"help_text":"Pull request #11894 exists for current branch JY-18909-automated-reports-ask-jiminny, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AutomatedReportsCommandTest","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AutomatedReportsCommandTest'","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AutomatedReportsCommandTest'","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"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},"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},"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},"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},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
6550998122266906523
|
-8852862413624849598
|
idle
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
FirefoxFileBookmarksWindowEditViewHistoryProfiles→ToolsHelpmeet.google.com/xpx-omah-rknNikolay Nikolov (Presenting, annotating)(all= Support Daily • in 3 h 20 m100% <478 • Fri 17 Apr 11:40:257+NNPhpStorm -FleAT AccountTransformer.php-$ Debug-opportunityWindowDebug opportunity stagesUOpportunitySyncTest.testResolveAcoountidProject©CrmEntityRepository.php© Nudge.php 23.03.26, 10:59,781 k82.05.25© NudgeRun,php 23.03.26, 10.59, 3.861.10.24© Opportunnity php 17.04.26, 10.52, [IP_ADDRESS]© Participant,.php 15.04.26, 10.55, 18.451.10.24© Partner.php 3103.26, 1.02, 5.55 kB1.10.24175176© Permission,php 23.03.26, 10.59, 1.321.10.24© PhoneNumber.php 23.03.26, 10.59,4© PaybackTheme.php 23.03.26, 10.59.© Playbook,.php 23.03.26, 10.39, 5.38 kгPaytookCategory.php 23.03.26, [IP_ADDRESS].18Graham8.08.18178 €© Playlst.php 23.03.26, 10.59, 10.23 kв© RateLimit.php 23.03.26, 10-59,1.91 k8© Region,php 23.03.26, 10.50, 844 B14.10.25 Ivanoy© Role.php 304.26, 1355, 2.45 k814.10.25© RoleChangeÊvent.php 23.03.26, 10117.01.25 Ivano© ScopeGroup, php 23.03.26, 10.59,1.714.10.25© Session.php 23.03.26, 10.59, 6.75 k819.08.19 Grahan18118218318418S186187© SlackBot,php 23.03.26, 10:59, 2.79 kB8.08.18SocialAccount.php 23.03.20, [IP_ADDRESS].19 Graham© Stage.php 23.03.26, 10.59, 5.88 kB8.08.18 Graham189190© Task. php 23.03.26, 1059, 4.35 kB8.08.18Team,php 30.03.26, 10.30, 65.13 k95.06.19© TeamAlContext.php 23.03.26, 10.394.04.20© TeamOomain.php 2303.26, 10.58,1826.08.19 Graham© TeamFeature,php 1.04.26, 1100, 143195© TeamSettings.php 3.04.26, 11.00, 1.41© TextRelay.php 23.03.26, 10:30, 3.5 kB© Track.php 23.03.26, 1039, M.18 k8© TranscriptionModeL.php 23.03.26, K© TranscriptionModelLocale.php 23c8.08.18© TranscriçtionProvider.php 23.03.26© User.php 304.26, 11.00, 41.23 kа© UserSettings.php1 3.04.26, 11.00, 695© Vocabulary.php 23.03.26, 10:59,2.82© VocabularyPronunclation.php 23.0g203© VoiceAccess.php 23.03.26, 10.59, [IP_ADDRESS]©VolceConsentPrefic.php 23.03.26,[IP_ADDRESS].24Opportunity.phpx© Lead phpOpportunitySyneTrait.phpclass Opportunity extends Model implenentsprotected static function nesfactory(): Factoryreturn OpportunityFactory::new();& James Graham +4protected static function boot()parent..boorosstatie::created(statie function (Oppertunity Sopportunity): void (Sopportunity-»stages()-›attach(Sopportunity->stage_$d):F):statie::updating(static function (Opportunity Sopportunity): void (1f (Sopportunity->isDirty( attributes"stage_id")){Sopportunity->stage_updated_at • Carbon: :nowO):Sopportunity->stages()->attach(Sopportunity->stage_1d):static::updated(static function (Opportunity Sopportunity): void {event(new OpportunityUpdated(Sopportunity)):1f (Sopportunity->wasChanged( attributes:"stage,1d')) €event(nex OpportunityStageUpdated(Sopportunity)):Reprecated& Ceorge Tuevpublic function deleteExistingAjPronpt(): voidGenericAiPronpt::queryOGenericAlPrompt::PROMPT_TYPE_DEAL)GenericA1Prompt::SUBJECT_TYPE_OPPORTUNITY))hObsemeniOpportuniyOapp › app › Modeis › © Opportunity.php › © Opportunity › a - boot › ® LambdaboOtD NOmeet.poogie.com is sharing your screen.PHP: 8.3 W Windsurf Teams190.14Fri 17 Ape 11:40420 21 A M18Vasil VasilevTlian Kyuchukov2 othersNikolay NikolovSymfony LF UTF-8 C 4 spacesLukas Kovalik11:40 AM | Daily - Processing...
|
NULL
|
|
44291
|
938
|
0
|
2026-04-17T08:40:48.903588+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776415248903_m2.jpg...
|
PhpStorm
|
faVsco.js – console [EU]
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
17
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Jobs\Crm\Hubspot;
use Illuminate\Support\Facades\Log;
use Jiminny\Contracts\Services\Crm\Provider\HubspotInterface;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Repositories\Crm\CrmConfigurationRepository;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Services\Crm\Hubspot\BatchSyncRedisService;
use Jiminny\Services\ResolveTeamCrmConnection;
/**
* Shared logic for HubSpot batch import jobs.
*
* Provides common functionality for importing batches of HubSpot objects (deals, contacts, companies)
* with consistent error handling, logging, and failure recovery mechanisms.
*
* Failure Handling Strategy:
*
* 1. SYSTEM-LEVEL FAILURES (HubSpot API down, DB connection lost, timeout):
* - Exception propagates out of handle()
* - Laravel retries the job up to $tries times with $backoff delays
* - If all retries exhausted, failed() requeues ALL IDs back to Redis
* - Next SyncObjects cycle will pick them up and retry
*
* 2. DATA-LEVEL FAILURES (per-object exceptions during import):
* - Caught inside the per-object loop in import*BatchByIds() methods
* - Indicate permanent issues: DB constraints, corrupt data, unmappable values
* - Retrying won't fix them - logged with specific error per ID
* - NOT requeued to avoid infinite retry loops
* - Require manual investigation and data correction
*
* Note: Objects intentionally skipped (missing dependencies like account, unknown pipeline/stage)
* return null and are not considered failures - they simply cannot be imported until dependencies exist.
*/
trait ImportBatchJobTrait
{
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const string OBJECT_TYPE_DEAL = 'deal';
private int $crmConfigurationId;
private array $crmIds;
abstract protected function getObjectType(): string;
abstract protected function getLogPrefix(): string;
abstract protected function importBatch(HubspotInterface $crmService, array $crmIds): array;
protected function processImportBatch(
ResolveTeamCrmConnection $resolveTeamCrmConnection,
CrmConfigurationRepository $crmConfigurationRepository,
CrmEntityRepository $crmEntityRepository
): void {
$crmConfig = $crmConfigurationRepository->findById($this->crmConfigurationId);
if ($crmConfig === null) {
Log::error($this->getLogPrefix() . ' CRM configuration not found', [
'crmConfigurationId' => $this->crmConfigurationId,
]);
return;
}
$crmService = $resolveTeamCrmConnection->resolveForTeam($crmConfig->getTeam());
if (! $crmService instanceof HubspotInterface) {
Log::error($this->getLogPrefix() . ' CRM service is not HubSpot', [
'crmConfigurationId' => $this->crmConfigurationId,
'serviceClass' => $crmService::class,
]);
return;
}
Log::info($this->getLogPrefix() . ' Processing batch', [
'crmConfigurationId' => $this->crmConfigurationId,
'batchSize' => count($this->crmIds),
]);
$filteredIds = $this->filterExistingObjects($crmConfig, $crmEntityRepository);
if (empty($filteredIds)) {
Log::info($this->getLogPrefix() . ' No existing objects found in Jiminny, skipping batch', [
'crmConfigurationId' => $this->crmConfigurationId,
'requestedCount' => count($this->crmIds),
]);
return;
}
$startTime = microtime(true);
$result = $this->importBatch($crmService, $filteredIds);
$durationMs = round((microtime(true) - $startTime) * 1000, 2);
$successCount = $result['success_count'] ?? \count($result['success'] ?? []);
$failedIds = $result['failed_ids'] ?? [];
$skippedCount = count($this->crmIds) - count($filteredIds);
Log::info($this->getLogPrefix() . ' Batch completed', [
'crmConfigurationId' => $this->crmConfigurationId,
'success' => $successCount,
'failed' => count($failedIds),
'skipped' => $skippedCount,
'requested' => count($this->crmIds),
'processed' => count($filteredIds),
'duration_ms' => $durationMs,
]);
if (! empty($failedIds)) {
Log::error($this->getLogPrefix() . ' Data-level failures require investigation', [
'crmConfigurationId' => $this->crmConfigurationId,
'failedCount' => \count($failedIds),
'failedIds' => $failedIds,
'errors' => $result['errors'] ?? [],
]);
}
}
/**
* Called by Laravel after all $tries are exhausted.
*
* System-level failure (HubSpot API down, timeout, OOM) - the entire handle() threw
* an unhandled exception on every attempt. Requeue ALL IDs back to Redis so the next
* SyncObjects cycle picks them up.
*
* This does NOT fire for data-level failures (those are caught in the per-object loop
* and logged without retrying).
*
* Requeue Strategy:
* - Each ID is individually requeued to Redis using SADD (automatic deduplication)
* - If requeue fails for specific IDs, they are logged as permanently lost
* - Redis requeue failures are rare (Redis connection issues) but critical
*/
protected function requeueFailedBatch(\Throwable $exception): void
{
$redisService = app(BatchSyncRedisService::class);
Log::error($this->getLogPrefix() . ' Job failed after all retries, requeuing IDs', [
'crmConfigurationId' => $this->crmConfigurationId,
'idCount' => \count($this->crmIds),
'error' => $exception->getMessage(),
]);
$requeued = 0;
$failedToRequeue = [];
foreach ($this->crmIds as $crmId) {
try {
$redisService->collectObjectIdToBatch(
$this->getObjectType(),
(string) $crmId,
$this->crmConfigurationId,
'all'
);
$requeued++;
} catch (\Throwable $e) {
$failedToRequeue[] = $crmId;
Log::warning($this->getLogPrefix() . ' Failed to requeue ID', [
'crmConfigurationId' => $this->crmConfigurationId,
'crmId' => $crmId,
'error' => $e->getMessage(),
]);
}
}
Log::info($this->getLogPrefix() . ' Requeue completed after job failure', [
'crmConfigurationId' => $this->crmConfigurationId,
'requeued' => $requeued,
'failedToRequeue' => \count($failedToRequeue),
'total' => \count($this->crmIds),
]);
if (! empty($failedToRequeue)) {
Log::critical($this->getLogPrefix() . ' Permanently lost IDs after requeue failure', [
'crmConfigurationId' => $this->crmConfigurationId,
'failedIds' => $failedToRequeue,
]);
}
}
private function filterExistingObjects(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array
{
$objectType = $this->getObjectType();
if ($objectType === self::OBJECT_TYPE_CONTACT) {
return $this->filterExistingContacts($crmConfig, $crmEntityRepository);
}
if ($objectType === self::OBJECT_TYPE_COMPANY) {
return $this->filterExistingAccounts($crmConfig, $crmEntityRepository);
}
return $this->crmIds;
}
private function filterExistingContacts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array
{
$existingContacts = $crmEntityRepository->getExistingContactCrmIds($crmConfig, $this->crmIds);
$existingIds = array_intersect($this->crmIds, $existingContacts);
return array_values($existingIds);
}
private function filterExistingAccounts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array
{
$existingAccounts = $crmEntityRepository->getExistingAccountCrmIds($crmConfig, $this->crmIds);
$existingIds = array_intersect($this->crmIds, $existingAccounts);
return array_values($existingIds);
}
}
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...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.03046875,"top":0.017361112,"width":0.0453125,"height":0.022222223},"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#11894 on JY-18909-automated-reports-ask-jiminny, menu","depth":5,"bounds":{"left":0.07578125,"top":0.017361112,"width":0.14960937,"height":0.022222223},"help_text":"Pull request #11894 exists for current branch JY-18909-automated-reports-ask-jiminny, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.78515625,"top":0.017361112,"width":0.01328125,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AutomatedReportsCommandTest","depth":6,"bounds":{"left":0.803125,"top":0.017361112,"width":0.09765625,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AutomatedReportsCommandTest'","depth":6,"bounds":{"left":0.9007813,"top":0.017361112,"width":0.01328125,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AutomatedReportsCommandTest'","depth":6,"bounds":{"left":0.9140625,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9273437,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.96015626,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9734375,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9867188,"top":0.017361112,"width":0.013281226,"height":0.022222223},"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.23320313,"top":1.0,"width":0.01015625,"height":0.0},"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.23320313,"top":1.0,"width":0.01015625,"height":0.0},"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.23320313,"top":1.0,"width":0.049609374,"height":0.0},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.23320313,"top":1.0,"width":0.01015625,"height":0.0},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"bounds":{"left":0.43398437,"top":0.21666667,"width":0.009375,"height":0.013194445},"role_description":"text"},{"role":"AXStaticText","text":"17","depth":4,"bounds":{"left":0.44570312,"top":0.21666667,"width":0.0109375,"height":0.013194445},"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.45859376,"top":0.21527778,"width":0.00859375,"height":0.015972223},"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.4671875,"top":0.21527778,"width":0.008203125,"height":0.015972223},"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\\Jobs\\Crm\\Hubspot;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\HubspotInterface;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Repositories\\Crm\\CrmConfigurationRepository;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncRedisService;\nuse Jiminny\\Services\\ResolveTeamCrmConnection;\n\n/**\n * Shared logic for HubSpot batch import jobs.\n *\n * Provides common functionality for importing batches of HubSpot objects (deals, contacts, companies)\n * with consistent error handling, logging, and failure recovery mechanisms.\n *\n * Failure Handling Strategy:\n *\n * 1. SYSTEM-LEVEL FAILURES (HubSpot API down, DB connection lost, timeout):\n * - Exception propagates out of handle()\n * - Laravel retries the job up to $tries times with $backoff delays\n * - If all retries exhausted, failed() requeues ALL IDs back to Redis\n * - Next SyncObjects cycle will pick them up and retry\n *\n * 2. DATA-LEVEL FAILURES (per-object exceptions during import):\n * - Caught inside the per-object loop in import*BatchByIds() methods\n * - Indicate permanent issues: DB constraints, corrupt data, unmappable values\n * - Retrying won't fix them - logged with specific error per ID\n * - NOT requeued to avoid infinite retry loops\n * - Require manual investigation and data correction\n *\n * Note: Objects intentionally skipped (missing dependencies like account, unknown pipeline/stage)\n * return null and are not considered failures - they simply cannot be imported until dependencies exist.\n */\ntrait ImportBatchJobTrait\n{\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n private const string OBJECT_TYPE_DEAL = 'deal';\n\n private int $crmConfigurationId;\n private array $crmIds;\n\n abstract protected function getObjectType(): string;\n\n abstract protected function getLogPrefix(): string;\n\n abstract protected function importBatch(HubspotInterface $crmService, array $crmIds): array;\n\n protected function processImportBatch(\n ResolveTeamCrmConnection $resolveTeamCrmConnection,\n CrmConfigurationRepository $crmConfigurationRepository,\n CrmEntityRepository $crmEntityRepository\n ): void {\n $crmConfig = $crmConfigurationRepository->findById($this->crmConfigurationId);\n if ($crmConfig === null) {\n Log::error($this->getLogPrefix() . ' CRM configuration not found', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n ]);\n\n return;\n }\n\n $crmService = $resolveTeamCrmConnection->resolveForTeam($crmConfig->getTeam());\n\n if (! $crmService instanceof HubspotInterface) {\n Log::error($this->getLogPrefix() . ' CRM service is not HubSpot', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'serviceClass' => $crmService::class,\n ]);\n\n return;\n }\n\n Log::info($this->getLogPrefix() . ' Processing batch', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'batchSize' => count($this->crmIds),\n ]);\n\n $filteredIds = $this->filterExistingObjects($crmConfig, $crmEntityRepository);\n\n if (empty($filteredIds)) {\n Log::info($this->getLogPrefix() . ' No existing objects found in Jiminny, skipping batch', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'requestedCount' => count($this->crmIds),\n ]);\n\n return;\n }\n\n $startTime = microtime(true);\n\n $result = $this->importBatch($crmService, $filteredIds);\n $durationMs = round((microtime(true) - $startTime) * 1000, 2);\n\n $successCount = $result['success_count'] ?? \\count($result['success'] ?? []);\n $failedIds = $result['failed_ids'] ?? [];\n\n $skippedCount = count($this->crmIds) - count($filteredIds);\n\n Log::info($this->getLogPrefix() . ' Batch completed', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'success' => $successCount,\n 'failed' => count($failedIds),\n 'skipped' => $skippedCount,\n 'requested' => count($this->crmIds),\n 'processed' => count($filteredIds),\n 'duration_ms' => $durationMs,\n ]);\n\n if (! empty($failedIds)) {\n Log::error($this->getLogPrefix() . ' Data-level failures require investigation', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'failedCount' => \\count($failedIds),\n 'failedIds' => $failedIds,\n 'errors' => $result['errors'] ?? [],\n ]);\n }\n }\n\n /**\n * Called by Laravel after all $tries are exhausted.\n *\n * System-level failure (HubSpot API down, timeout, OOM) - the entire handle() threw\n * an unhandled exception on every attempt. Requeue ALL IDs back to Redis so the next\n * SyncObjects cycle picks them up.\n *\n * This does NOT fire for data-level failures (those are caught in the per-object loop\n * and logged without retrying).\n *\n * Requeue Strategy:\n * - Each ID is individually requeued to Redis using SADD (automatic deduplication)\n * - If requeue fails for specific IDs, they are logged as permanently lost\n * - Redis requeue failures are rare (Redis connection issues) but critical\n */\n protected function requeueFailedBatch(\\Throwable $exception): void\n {\n $redisService = app(BatchSyncRedisService::class);\n\n Log::error($this->getLogPrefix() . ' Job failed after all retries, requeuing IDs', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'idCount' => \\count($this->crmIds),\n 'error' => $exception->getMessage(),\n ]);\n\n $requeued = 0;\n $failedToRequeue = [];\n\n foreach ($this->crmIds as $crmId) {\n try {\n $redisService->collectObjectIdToBatch(\n $this->getObjectType(),\n (string) $crmId,\n $this->crmConfigurationId,\n 'all'\n );\n $requeued++;\n } catch (\\Throwable $e) {\n $failedToRequeue[] = $crmId;\n Log::warning($this->getLogPrefix() . ' Failed to requeue ID', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'crmId' => $crmId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n Log::info($this->getLogPrefix() . ' Requeue completed after job failure', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'requeued' => $requeued,\n 'failedToRequeue' => \\count($failedToRequeue),\n 'total' => \\count($this->crmIds),\n ]);\n\n if (! empty($failedToRequeue)) {\n Log::critical($this->getLogPrefix() . ' Permanently lost IDs after requeue failure', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'failedIds' => $failedToRequeue,\n ]);\n }\n }\n\n private function filterExistingObjects(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array\n {\n $objectType = $this->getObjectType();\n\n if ($objectType === self::OBJECT_TYPE_CONTACT) {\n return $this->filterExistingContacts($crmConfig, $crmEntityRepository);\n }\n\n if ($objectType === self::OBJECT_TYPE_COMPANY) {\n return $this->filterExistingAccounts($crmConfig, $crmEntityRepository);\n }\n\n return $this->crmIds;\n }\n\n private function filterExistingContacts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array\n {\n $existingContacts = $crmEntityRepository->getExistingContactCrmIds($crmConfig, $this->crmIds);\n $existingIds = array_intersect($this->crmIds, $existingContacts);\n\n return array_values($existingIds);\n }\n\n private function filterExistingAccounts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array\n {\n $existingAccounts = $crmEntityRepository->getExistingAccountCrmIds($crmConfig, $this->crmIds);\n $existingIds = array_intersect($this->crmIds, $existingAccounts);\n\n return array_values($existingIds);\n }\n}","depth":4,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Jobs\\Crm\\Hubspot;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\HubspotInterface;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Repositories\\Crm\\CrmConfigurationRepository;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncRedisService;\nuse Jiminny\\Services\\ResolveTeamCrmConnection;\n\n/**\n * Shared logic for HubSpot batch import jobs.\n *\n * Provides common functionality for importing batches of HubSpot objects (deals, contacts, companies)\n * with consistent error handling, logging, and failure recovery mechanisms.\n *\n * Failure Handling Strategy:\n *\n * 1. SYSTEM-LEVEL FAILURES (HubSpot API down, DB connection lost, timeout):\n * - Exception propagates out of handle()\n * - Laravel retries the job up to $tries times with $backoff delays\n * - If all retries exhausted, failed() requeues ALL IDs back to Redis\n * - Next SyncObjects cycle will pick them up and retry\n *\n * 2. DATA-LEVEL FAILURES (per-object exceptions during import):\n * - Caught inside the per-object loop in import*BatchByIds() methods\n * - Indicate permanent issues: DB constraints, corrupt data, unmappable values\n * - Retrying won't fix them - logged with specific error per ID\n * - NOT requeued to avoid infinite retry loops\n * - Require manual investigation and data correction\n *\n * Note: Objects intentionally skipped (missing dependencies like account, unknown pipeline/stage)\n * return null and are not considered failures - they simply cannot be imported until dependencies exist.\n */\ntrait ImportBatchJobTrait\n{\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n private const string OBJECT_TYPE_DEAL = 'deal';\n\n private int $crmConfigurationId;\n private array $crmIds;\n\n abstract protected function getObjectType(): string;\n\n abstract protected function getLogPrefix(): string;\n\n abstract protected function importBatch(HubspotInterface $crmService, array $crmIds): array;\n\n protected function processImportBatch(\n ResolveTeamCrmConnection $resolveTeamCrmConnection,\n CrmConfigurationRepository $crmConfigurationRepository,\n CrmEntityRepository $crmEntityRepository\n ): void {\n $crmConfig = $crmConfigurationRepository->findById($this->crmConfigurationId);\n if ($crmConfig === null) {\n Log::error($this->getLogPrefix() . ' CRM configuration not found', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n ]);\n\n return;\n }\n\n $crmService = $resolveTeamCrmConnection->resolveForTeam($crmConfig->getTeam());\n\n if (! $crmService instanceof HubspotInterface) {\n Log::error($this->getLogPrefix() . ' CRM service is not HubSpot', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'serviceClass' => $crmService::class,\n ]);\n\n return;\n }\n\n Log::info($this->getLogPrefix() . ' Processing batch', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'batchSize' => count($this->crmIds),\n ]);\n\n $filteredIds = $this->filterExistingObjects($crmConfig, $crmEntityRepository);\n\n if (empty($filteredIds)) {\n Log::info($this->getLogPrefix() . ' No existing objects found in Jiminny, skipping batch', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'requestedCount' => count($this->crmIds),\n ]);\n\n return;\n }\n\n $startTime = microtime(true);\n\n $result = $this->importBatch($crmService, $filteredIds);\n $durationMs = round((microtime(true) - $startTime) * 1000, 2);\n\n $successCount = $result['success_count'] ?? \\count($result['success'] ?? []);\n $failedIds = $result['failed_ids'] ?? [];\n\n $skippedCount = count($this->crmIds) - count($filteredIds);\n\n Log::info($this->getLogPrefix() . ' Batch completed', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'success' => $successCount,\n 'failed' => count($failedIds),\n 'skipped' => $skippedCount,\n 'requested' => count($this->crmIds),\n 'processed' => count($filteredIds),\n 'duration_ms' => $durationMs,\n ]);\n\n if (! empty($failedIds)) {\n Log::error($this->getLogPrefix() . ' Data-level failures require investigation', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'failedCount' => \\count($failedIds),\n 'failedIds' => $failedIds,\n 'errors' => $result['errors'] ?? [],\n ]);\n }\n }\n\n /**\n * Called by Laravel after all $tries are exhausted.\n *\n * System-level failure (HubSpot API down, timeout, OOM) - the entire handle() threw\n * an unhandled exception on every attempt. Requeue ALL IDs back to Redis so the next\n * SyncObjects cycle picks them up.\n *\n * This does NOT fire for data-level failures (those are caught in the per-object loop\n * and logged without retrying).\n *\n * Requeue Strategy:\n * - Each ID is individually requeued to Redis using SADD (automatic deduplication)\n * - If requeue fails for specific IDs, they are logged as permanently lost\n * - Redis requeue failures are rare (Redis connection issues) but critical\n */\n protected function requeueFailedBatch(\\Throwable $exception): void\n {\n $redisService = app(BatchSyncRedisService::class);\n\n Log::error($this->getLogPrefix() . ' Job failed after all retries, requeuing IDs', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'idCount' => \\count($this->crmIds),\n 'error' => $exception->getMessage(),\n ]);\n\n $requeued = 0;\n $failedToRequeue = [];\n\n foreach ($this->crmIds as $crmId) {\n try {\n $redisService->collectObjectIdToBatch(\n $this->getObjectType(),\n (string) $crmId,\n $this->crmConfigurationId,\n 'all'\n );\n $requeued++;\n } catch (\\Throwable $e) {\n $failedToRequeue[] = $crmId;\n Log::warning($this->getLogPrefix() . ' Failed to requeue ID', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'crmId' => $crmId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n Log::info($this->getLogPrefix() . ' Requeue completed after job failure', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'requeued' => $requeued,\n 'failedToRequeue' => \\count($failedToRequeue),\n 'total' => \\count($this->crmIds),\n ]);\n\n if (! empty($failedToRequeue)) {\n Log::critical($this->getLogPrefix() . ' Permanently lost IDs after requeue failure', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'failedIds' => $failedToRequeue,\n ]);\n }\n }\n\n private function filterExistingObjects(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array\n {\n $objectType = $this->getObjectType();\n\n if ($objectType === self::OBJECT_TYPE_CONTACT) {\n return $this->filterExistingContacts($crmConfig, $crmEntityRepository);\n }\n\n if ($objectType === self::OBJECT_TYPE_COMPANY) {\n return $this->filterExistingAccounts($crmConfig, $crmEntityRepository);\n }\n\n return $this->crmIds;\n }\n\n private function filterExistingContacts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array\n {\n $existingContacts = $crmEntityRepository->getExistingContactCrmIds($crmConfig, $this->crmIds);\n $existingIds = array_intersect($this->crmIds, $existingContacts);\n\n return array_values($existingIds);\n }\n\n private function filterExistingAccounts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array\n {\n $existingAccounts = $crmEntityRepository->getExistingAccountCrmIds($crmConfig, $this->crmIds);\n $existingIds = array_intersect($this->crmIds, $existingAccounts);\n\n return array_values($existingIds);\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.47734374,"top":0.10763889,"width":0.01015625,"height":0.016666668},"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.4875,"top":0.10763889,"width":0.01015625,"height":0.016666668},"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.50039065,"top":0.10763889,"width":0.01015625,"height":0.016666668},"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.51054686,"top":0.10763889,"width":0.01015625,"height":0.016666668},"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.52070314,"top":0.10763889,"width":0.01015625,"height":0.016666668},"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.5335938,"top":0.10763889,"width":0.01015625,"height":0.016666668},"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.54648435,"top":0.10763889,"width":0.028515626,"height":0.016666668},"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.57773435,"top":0.10763889,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"bounds":{"left":0.590625,"top":0.10763889,"width":0.034765624,"height":0.016666668},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.6917969,"top":0.10763889,"width":0.033203125,"height":0.016666668},"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.23320313,"top":1.0,"width":0.049609374,"height":0.0},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.23320313,"top":1.0,"width":0.01015625,"height":0.0},"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.23320313,"top":1.0,"width":0.01015625,"height":0.0},"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.23320313,"top":1.0,"width":0.01015625,"height":0.0},"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-8602736163367039487
|
2224264300252072548
|
idle
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
17
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Jobs\Crm\Hubspot;
use Illuminate\Support\Facades\Log;
use Jiminny\Contracts\Services\Crm\Provider\HubspotInterface;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Repositories\Crm\CrmConfigurationRepository;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Services\Crm\Hubspot\BatchSyncRedisService;
use Jiminny\Services\ResolveTeamCrmConnection;
/**
* Shared logic for HubSpot batch import jobs.
*
* Provides common functionality for importing batches of HubSpot objects (deals, contacts, companies)
* with consistent error handling, logging, and failure recovery mechanisms.
*
* Failure Handling Strategy:
*
* 1. SYSTEM-LEVEL FAILURES (HubSpot API down, DB connection lost, timeout):
* - Exception propagates out of handle()
* - Laravel retries the job up to $tries times with $backoff delays
* - If all retries exhausted, failed() requeues ALL IDs back to Redis
* - Next SyncObjects cycle will pick them up and retry
*
* 2. DATA-LEVEL FAILURES (per-object exceptions during import):
* - Caught inside the per-object loop in import*BatchByIds() methods
* - Indicate permanent issues: DB constraints, corrupt data, unmappable values
* - Retrying won't fix them - logged with specific error per ID
* - NOT requeued to avoid infinite retry loops
* - Require manual investigation and data correction
*
* Note: Objects intentionally skipped (missing dependencies like account, unknown pipeline/stage)
* return null and are not considered failures - they simply cannot be imported until dependencies exist.
*/
trait ImportBatchJobTrait
{
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const string OBJECT_TYPE_DEAL = 'deal';
private int $crmConfigurationId;
private array $crmIds;
abstract protected function getObjectType(): string;
abstract protected function getLogPrefix(): string;
abstract protected function importBatch(HubspotInterface $crmService, array $crmIds): array;
protected function processImportBatch(
ResolveTeamCrmConnection $resolveTeamCrmConnection,
CrmConfigurationRepository $crmConfigurationRepository,
CrmEntityRepository $crmEntityRepository
): void {
$crmConfig = $crmConfigurationRepository->findById($this->crmConfigurationId);
if ($crmConfig === null) {
Log::error($this->getLogPrefix() . ' CRM configuration not found', [
'crmConfigurationId' => $this->crmConfigurationId,
]);
return;
}
$crmService = $resolveTeamCrmConnection->resolveForTeam($crmConfig->getTeam());
if (! $crmService instanceof HubspotInterface) {
Log::error($this->getLogPrefix() . ' CRM service is not HubSpot', [
'crmConfigurationId' => $this->crmConfigurationId,
'serviceClass' => $crmService::class,
]);
return;
}
Log::info($this->getLogPrefix() . ' Processing batch', [
'crmConfigurationId' => $this->crmConfigurationId,
'batchSize' => count($this->crmIds),
]);
$filteredIds = $this->filterExistingObjects($crmConfig, $crmEntityRepository);
if (empty($filteredIds)) {
Log::info($this->getLogPrefix() . ' No existing objects found in Jiminny, skipping batch', [
'crmConfigurationId' => $this->crmConfigurationId,
'requestedCount' => count($this->crmIds),
]);
return;
}
$startTime = microtime(true);
$result = $this->importBatch($crmService, $filteredIds);
$durationMs = round((microtime(true) - $startTime) * 1000, 2);
$successCount = $result['success_count'] ?? \count($result['success'] ?? []);
$failedIds = $result['failed_ids'] ?? [];
$skippedCount = count($this->crmIds) - count($filteredIds);
Log::info($this->getLogPrefix() . ' Batch completed', [
'crmConfigurationId' => $this->crmConfigurationId,
'success' => $successCount,
'failed' => count($failedIds),
'skipped' => $skippedCount,
'requested' => count($this->crmIds),
'processed' => count($filteredIds),
'duration_ms' => $durationMs,
]);
if (! empty($failedIds)) {
Log::error($this->getLogPrefix() . ' Data-level failures require investigation', [
'crmConfigurationId' => $this->crmConfigurationId,
'failedCount' => \count($failedIds),
'failedIds' => $failedIds,
'errors' => $result['errors'] ?? [],
]);
}
}
/**
* Called by Laravel after all $tries are exhausted.
*
* System-level failure (HubSpot API down, timeout, OOM) - the entire handle() threw
* an unhandled exception on every attempt. Requeue ALL IDs back to Redis so the next
* SyncObjects cycle picks them up.
*
* This does NOT fire for data-level failures (those are caught in the per-object loop
* and logged without retrying).
*
* Requeue Strategy:
* - Each ID is individually requeued to Redis using SADD (automatic deduplication)
* - If requeue fails for specific IDs, they are logged as permanently lost
* - Redis requeue failures are rare (Redis connection issues) but critical
*/
protected function requeueFailedBatch(\Throwable $exception): void
{
$redisService = app(BatchSyncRedisService::class);
Log::error($this->getLogPrefix() . ' Job failed after all retries, requeuing IDs', [
'crmConfigurationId' => $this->crmConfigurationId,
'idCount' => \count($this->crmIds),
'error' => $exception->getMessage(),
]);
$requeued = 0;
$failedToRequeue = [];
foreach ($this->crmIds as $crmId) {
try {
$redisService->collectObjectIdToBatch(
$this->getObjectType(),
(string) $crmId,
$this->crmConfigurationId,
'all'
);
$requeued++;
} catch (\Throwable $e) {
$failedToRequeue[] = $crmId;
Log::warning($this->getLogPrefix() . ' Failed to requeue ID', [
'crmConfigurationId' => $this->crmConfigurationId,
'crmId' => $crmId,
'error' => $e->getMessage(),
]);
}
}
Log::info($this->getLogPrefix() . ' Requeue completed after job failure', [
'crmConfigurationId' => $this->crmConfigurationId,
'requeued' => $requeued,
'failedToRequeue' => \count($failedToRequeue),
'total' => \count($this->crmIds),
]);
if (! empty($failedToRequeue)) {
Log::critical($this->getLogPrefix() . ' Permanently lost IDs after requeue failure', [
'crmConfigurationId' => $this->crmConfigurationId,
'failedIds' => $failedToRequeue,
]);
}
}
private function filterExistingObjects(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array
{
$objectType = $this->getObjectType();
if ($objectType === self::OBJECT_TYPE_CONTACT) {
return $this->filterExistingContacts($crmConfig, $crmEntityRepository);
}
if ($objectType === self::OBJECT_TYPE_COMPANY) {
return $this->filterExistingAccounts($crmConfig, $crmEntityRepository);
}
return $this->crmIds;
}
private function filterExistingContacts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array
{
$existingContacts = $crmEntityRepository->getExistingContactCrmIds($crmConfig, $this->crmIds);
$existingIds = array_intersect($this->crmIds, $existingContacts);
return array_values($existingIds);
}
private function filterExistingAccounts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array
{
$existingAccounts = $crmEntityRepository->getExistingAccountCrmIds($crmConfig, $this->crmIds);
$existingIds = array_intersect($this->crmIds, $existingAccounts);
return array_values($existingIds);
}
}
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...
|
NULL
|
|
44292
|
937
|
0
|
2026-04-17T08:40:57.122641+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776415257122_m1.jpg...
|
PhpStorm
|
faVsco.js – console [EU]
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
17
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Jobs\Crm\Hubspot;
use Illuminate\Support\Facades\Log;
use Jiminny\Contracts\Services\Crm\Provider\HubspotInterface;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Repositories\Crm\CrmConfigurationRepository;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Services\Crm\Hubspot\BatchSyncRedisService;
use Jiminny\Services\ResolveTeamCrmConnection;
/**
* Shared logic for HubSpot batch import jobs.
*
* Provides common functionality for importing batches of HubSpot objects (deals, contacts, companies)
* with consistent error handling, logging, and failure recovery mechanisms.
*
* Failure Handling Strategy:
*
* 1. SYSTEM-LEVEL FAILURES (HubSpot API down, DB connection lost, timeout):
* - Exception propagates out of handle()
* - Laravel retries the job up to $tries times with $backoff delays
* - If all retries exhausted, failed() requeues ALL IDs back to Redis
* - Next SyncObjects cycle will pick them up and retry
*
* 2. DATA-LEVEL FAILURES (per-object exceptions during import):
* - Caught inside the per-object loop in import*BatchByIds() methods
* - Indicate permanent issues: DB constraints, corrupt data, unmappable values
* - Retrying won't fix them - logged with specific error per ID
* - NOT requeued to avoid infinite retry loops
* - Require manual investigation and data correction
*
* Note: Objects intentionally skipped (missing dependencies like account, unknown pipeline/stage)
* return null and are not considered failures - they simply cannot be imported until dependencies exist.
*/
trait ImportBatchJobTrait
{
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const string OBJECT_TYPE_DEAL = 'deal';
private int $crmConfigurationId;
private array $crmIds;
abstract protected function getObjectType(): string;
abstract protected function getLogPrefix(): string;
abstract protected function importBatch(HubspotInterface $crmService, array $crmIds): array;
protected function processImportBatch(
ResolveTeamCrmConnection $resolveTeamCrmConnection,
CrmConfigurationRepository $crmConfigurationRepository,
CrmEntityRepository $crmEntityRepository
): void {
$crmConfig = $crmConfigurationRepository->findById($this->crmConfigurationId);
if ($crmConfig === null) {
Log::error($this->getLogPrefix() . ' CRM configuration not found', [
'crmConfigurationId' => $this->crmConfigurationId,
]);
return;
}
$crmService = $resolveTeamCrmConnection->resolveForTeam($crmConfig->getTeam());
if (! $crmService instanceof HubspotInterface) {
Log::error($this->getLogPrefix() . ' CRM service is not HubSpot', [
'crmConfigurationId' => $this->crmConfigurationId,
'serviceClass' => $crmService::class,
]);
return;
}
Log::info($this->getLogPrefix() . ' Processing batch', [
'crmConfigurationId' => $this->crmConfigurationId,
'batchSize' => count($this->crmIds),
]);
$filteredIds = $this->filterExistingObjects($crmConfig, $crmEntityRepository);
if (empty($filteredIds)) {
Log::info($this->getLogPrefix() . ' No existing objects found in Jiminny, skipping batch', [
'crmConfigurationId' => $this->crmConfigurationId,
'requestedCount' => count($this->crmIds),
]);
return;
}
$startTime = microtime(true);
$result = $this->importBatch($crmService, $filteredIds);
$durationMs = round((microtime(true) - $startTime) * 1000, 2);
$successCount = $result['success_count'] ?? \count($result['success'] ?? []);
$failedIds = $result['failed_ids'] ?? [];
$skippedCount = count($this->crmIds) - count($filteredIds);
Log::info($this->getLogPrefix() . ' Batch completed', [
'crmConfigurationId' => $this->crmConfigurationId,
'success' => $successCount,
'failed' => count($failedIds),
'skipped' => $skippedCount,
'requested' => count($this->crmIds),
'processed' => count($filteredIds),
'duration_ms' => $durationMs,
]);
if (! empty($failedIds)) {
Log::error($this->getLogPrefix() . ' Data-level failures require investigation', [
'crmConfigurationId' => $this->crmConfigurationId,
'failedCount' => \count($failedIds),
'failedIds' => $failedIds,
'errors' => $result['errors'] ?? [],
]);
}
}
/**
* Called by Laravel after all $tries are exhausted.
*
* System-level failure (HubSpot API down, timeout, OOM) - the entire handle() threw
* an unhandled exception on every attempt. Requeue ALL IDs back to Redis so the next
* SyncObjects cycle picks them up.
*
* This does NOT fire for data-level failures (those are caught in the per-object loop
* and logged without retrying).
*
* Requeue Strategy:
* - Each ID is individually requeued to Redis using SADD (automatic deduplication)
* - If requeue fails for specific IDs, they are logged as permanently lost
* - Redis requeue failures are rare (Redis connection issues) but critical
*/
protected function requeueFailedBatch(\Throwable $exception): void
{
$redisService = app(BatchSyncRedisService::class);
Log::error($this->getLogPrefix() . ' Job failed after all retries, requeuing IDs', [
'crmConfigurationId' => $this->crmConfigurationId,
'idCount' => \count($this->crmIds),
'error' => $exception->getMessage(),
]);
$requeued = 0;
$failedToRequeue = [];
foreach ($this->crmIds as $crmId) {
try {
$redisService->collectObjectIdToBatch(
$this->getObjectType(),
(string) $crmId,
$this->crmConfigurationId,
'all'
);
$requeued++;
} catch (\Throwable $e) {
$failedToRequeue[] = $crmId;
Log::warning($this->getLogPrefix() . ' Failed to requeue ID', [
'crmConfigurationId' => $this->crmConfigurationId,
'crmId' => $crmId,
'error' => $e->getMessage(),
]);
}
}
Log::info($this->getLogPrefix() . ' Requeue completed after job failure', [
'crmConfigurationId' => $this->crmConfigurationId,
'requeued' => $requeued,
'failedToRequeue' => \count($failedToRequeue),
'total' => \count($this->crmIds),
]);
if (! empty($failedToRequeue)) {
Log::critical($this->getLogPrefix() . ' Permanently lost IDs after requeue failure', [
'crmConfigurationId' => $this->crmConfigurationId,
'failedIds' => $failedToRequeue,
]);
}
}
private function filterExistingObjects(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array
{
$objectType = $this->getObjectType();
if ($objectType === self::OBJECT_TYPE_CONTACT) {
return $this->filterExistingContacts($crmConfig, $crmEntityRepository);
}
if ($objectType === self::OBJECT_TYPE_COMPANY) {
return $this->filterExistingAccounts($crmConfig, $crmEntityRepository);
}
return $this->crmIds;
}
private function filterExistingContacts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array
{
$existingContacts = $crmEntityRepository->getExistingContactCrmIds($crmConfig, $this->crmIds);
$existingIds = array_intersect($this->crmIds, $existingContacts);
return array_values($existingIds);
}
private function filterExistingAccounts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array
{
$existingAccounts = $crmEntityRepository->getExistingAccountCrmIds($crmConfig, $this->crmIds);
$existingIds = array_intersect($this->crmIds, $existingAccounts);
return array_values($existingIds);
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#11894 on JY-18909-automated-reports-ask-jiminny, menu","depth":5,"help_text":"Pull request #11894 exists for current branch JY-18909-automated-reports-ask-jiminny, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AutomatedReportsCommandTest","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AutomatedReportsCommandTest'","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AutomatedReportsCommandTest'","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"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},"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},"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},"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},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"role_description":"text"},{"role":"AXStaticText","text":"17","depth":4,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"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\\Jobs\\Crm\\Hubspot;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\HubspotInterface;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Repositories\\Crm\\CrmConfigurationRepository;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncRedisService;\nuse Jiminny\\Services\\ResolveTeamCrmConnection;\n\n/**\n * Shared logic for HubSpot batch import jobs.\n *\n * Provides common functionality for importing batches of HubSpot objects (deals, contacts, companies)\n * with consistent error handling, logging, and failure recovery mechanisms.\n *\n * Failure Handling Strategy:\n *\n * 1. SYSTEM-LEVEL FAILURES (HubSpot API down, DB connection lost, timeout):\n * - Exception propagates out of handle()\n * - Laravel retries the job up to $tries times with $backoff delays\n * - If all retries exhausted, failed() requeues ALL IDs back to Redis\n * - Next SyncObjects cycle will pick them up and retry\n *\n * 2. DATA-LEVEL FAILURES (per-object exceptions during import):\n * - Caught inside the per-object loop in import*BatchByIds() methods\n * - Indicate permanent issues: DB constraints, corrupt data, unmappable values\n * - Retrying won't fix them - logged with specific error per ID\n * - NOT requeued to avoid infinite retry loops\n * - Require manual investigation and data correction\n *\n * Note: Objects intentionally skipped (missing dependencies like account, unknown pipeline/stage)\n * return null and are not considered failures - they simply cannot be imported until dependencies exist.\n */\ntrait ImportBatchJobTrait\n{\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n private const string OBJECT_TYPE_DEAL = 'deal';\n\n private int $crmConfigurationId;\n private array $crmIds;\n\n abstract protected function getObjectType(): string;\n\n abstract protected function getLogPrefix(): string;\n\n abstract protected function importBatch(HubspotInterface $crmService, array $crmIds): array;\n\n protected function processImportBatch(\n ResolveTeamCrmConnection $resolveTeamCrmConnection,\n CrmConfigurationRepository $crmConfigurationRepository,\n CrmEntityRepository $crmEntityRepository\n ): void {\n $crmConfig = $crmConfigurationRepository->findById($this->crmConfigurationId);\n if ($crmConfig === null) {\n Log::error($this->getLogPrefix() . ' CRM configuration not found', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n ]);\n\n return;\n }\n\n $crmService = $resolveTeamCrmConnection->resolveForTeam($crmConfig->getTeam());\n\n if (! $crmService instanceof HubspotInterface) {\n Log::error($this->getLogPrefix() . ' CRM service is not HubSpot', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'serviceClass' => $crmService::class,\n ]);\n\n return;\n }\n\n Log::info($this->getLogPrefix() . ' Processing batch', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'batchSize' => count($this->crmIds),\n ]);\n\n $filteredIds = $this->filterExistingObjects($crmConfig, $crmEntityRepository);\n\n if (empty($filteredIds)) {\n Log::info($this->getLogPrefix() . ' No existing objects found in Jiminny, skipping batch', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'requestedCount' => count($this->crmIds),\n ]);\n\n return;\n }\n\n $startTime = microtime(true);\n\n $result = $this->importBatch($crmService, $filteredIds);\n $durationMs = round((microtime(true) - $startTime) * 1000, 2);\n\n $successCount = $result['success_count'] ?? \\count($result['success'] ?? []);\n $failedIds = $result['failed_ids'] ?? [];\n\n $skippedCount = count($this->crmIds) - count($filteredIds);\n\n Log::info($this->getLogPrefix() . ' Batch completed', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'success' => $successCount,\n 'failed' => count($failedIds),\n 'skipped' => $skippedCount,\n 'requested' => count($this->crmIds),\n 'processed' => count($filteredIds),\n 'duration_ms' => $durationMs,\n ]);\n\n if (! empty($failedIds)) {\n Log::error($this->getLogPrefix() . ' Data-level failures require investigation', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'failedCount' => \\count($failedIds),\n 'failedIds' => $failedIds,\n 'errors' => $result['errors'] ?? [],\n ]);\n }\n }\n\n /**\n * Called by Laravel after all $tries are exhausted.\n *\n * System-level failure (HubSpot API down, timeout, OOM) - the entire handle() threw\n * an unhandled exception on every attempt. Requeue ALL IDs back to Redis so the next\n * SyncObjects cycle picks them up.\n *\n * This does NOT fire for data-level failures (those are caught in the per-object loop\n * and logged without retrying).\n *\n * Requeue Strategy:\n * - Each ID is individually requeued to Redis using SADD (automatic deduplication)\n * - If requeue fails for specific IDs, they are logged as permanently lost\n * - Redis requeue failures are rare (Redis connection issues) but critical\n */\n protected function requeueFailedBatch(\\Throwable $exception): void\n {\n $redisService = app(BatchSyncRedisService::class);\n\n Log::error($this->getLogPrefix() . ' Job failed after all retries, requeuing IDs', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'idCount' => \\count($this->crmIds),\n 'error' => $exception->getMessage(),\n ]);\n\n $requeued = 0;\n $failedToRequeue = [];\n\n foreach ($this->crmIds as $crmId) {\n try {\n $redisService->collectObjectIdToBatch(\n $this->getObjectType(),\n (string) $crmId,\n $this->crmConfigurationId,\n 'all'\n );\n $requeued++;\n } catch (\\Throwable $e) {\n $failedToRequeue[] = $crmId;\n Log::warning($this->getLogPrefix() . ' Failed to requeue ID', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'crmId' => $crmId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n Log::info($this->getLogPrefix() . ' Requeue completed after job failure', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'requeued' => $requeued,\n 'failedToRequeue' => \\count($failedToRequeue),\n 'total' => \\count($this->crmIds),\n ]);\n\n if (! empty($failedToRequeue)) {\n Log::critical($this->getLogPrefix() . ' Permanently lost IDs after requeue failure', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'failedIds' => $failedToRequeue,\n ]);\n }\n }\n\n private function filterExistingObjects(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array\n {\n $objectType = $this->getObjectType();\n\n if ($objectType === self::OBJECT_TYPE_CONTACT) {\n return $this->filterExistingContacts($crmConfig, $crmEntityRepository);\n }\n\n if ($objectType === self::OBJECT_TYPE_COMPANY) {\n return $this->filterExistingAccounts($crmConfig, $crmEntityRepository);\n }\n\n return $this->crmIds;\n }\n\n private function filterExistingContacts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array\n {\n $existingContacts = $crmEntityRepository->getExistingContactCrmIds($crmConfig, $this->crmIds);\n $existingIds = array_intersect($this->crmIds, $existingContacts);\n\n return array_values($existingIds);\n }\n\n private function filterExistingAccounts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array\n {\n $existingAccounts = $crmEntityRepository->getExistingAccountCrmIds($crmConfig, $this->crmIds);\n $existingIds = array_intersect($this->crmIds, $existingAccounts);\n\n return array_values($existingIds);\n }\n}","depth":4,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Jobs\\Crm\\Hubspot;\n\nuse Illuminate\\Support\\Facades\\Log;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\HubspotInterface;\nuse Jiminny\\Models\\Crm\\Configuration;\nuse Jiminny\\Repositories\\Crm\\CrmConfigurationRepository;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Services\\Crm\\Hubspot\\BatchSyncRedisService;\nuse Jiminny\\Services\\ResolveTeamCrmConnection;\n\n/**\n * Shared logic for HubSpot batch import jobs.\n *\n * Provides common functionality for importing batches of HubSpot objects (deals, contacts, companies)\n * with consistent error handling, logging, and failure recovery mechanisms.\n *\n * Failure Handling Strategy:\n *\n * 1. SYSTEM-LEVEL FAILURES (HubSpot API down, DB connection lost, timeout):\n * - Exception propagates out of handle()\n * - Laravel retries the job up to $tries times with $backoff delays\n * - If all retries exhausted, failed() requeues ALL IDs back to Redis\n * - Next SyncObjects cycle will pick them up and retry\n *\n * 2. DATA-LEVEL FAILURES (per-object exceptions during import):\n * - Caught inside the per-object loop in import*BatchByIds() methods\n * - Indicate permanent issues: DB constraints, corrupt data, unmappable values\n * - Retrying won't fix them - logged with specific error per ID\n * - NOT requeued to avoid infinite retry loops\n * - Require manual investigation and data correction\n *\n * Note: Objects intentionally skipped (missing dependencies like account, unknown pipeline/stage)\n * return null and are not considered failures - they simply cannot be imported until dependencies exist.\n */\ntrait ImportBatchJobTrait\n{\n private const string OBJECT_TYPE_CONTACT = 'contact';\n private const string OBJECT_TYPE_COMPANY = 'company';\n private const string OBJECT_TYPE_DEAL = 'deal';\n\n private int $crmConfigurationId;\n private array $crmIds;\n\n abstract protected function getObjectType(): string;\n\n abstract protected function getLogPrefix(): string;\n\n abstract protected function importBatch(HubspotInterface $crmService, array $crmIds): array;\n\n protected function processImportBatch(\n ResolveTeamCrmConnection $resolveTeamCrmConnection,\n CrmConfigurationRepository $crmConfigurationRepository,\n CrmEntityRepository $crmEntityRepository\n ): void {\n $crmConfig = $crmConfigurationRepository->findById($this->crmConfigurationId);\n if ($crmConfig === null) {\n Log::error($this->getLogPrefix() . ' CRM configuration not found', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n ]);\n\n return;\n }\n\n $crmService = $resolveTeamCrmConnection->resolveForTeam($crmConfig->getTeam());\n\n if (! $crmService instanceof HubspotInterface) {\n Log::error($this->getLogPrefix() . ' CRM service is not HubSpot', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'serviceClass' => $crmService::class,\n ]);\n\n return;\n }\n\n Log::info($this->getLogPrefix() . ' Processing batch', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'batchSize' => count($this->crmIds),\n ]);\n\n $filteredIds = $this->filterExistingObjects($crmConfig, $crmEntityRepository);\n\n if (empty($filteredIds)) {\n Log::info($this->getLogPrefix() . ' No existing objects found in Jiminny, skipping batch', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'requestedCount' => count($this->crmIds),\n ]);\n\n return;\n }\n\n $startTime = microtime(true);\n\n $result = $this->importBatch($crmService, $filteredIds);\n $durationMs = round((microtime(true) - $startTime) * 1000, 2);\n\n $successCount = $result['success_count'] ?? \\count($result['success'] ?? []);\n $failedIds = $result['failed_ids'] ?? [];\n\n $skippedCount = count($this->crmIds) - count($filteredIds);\n\n Log::info($this->getLogPrefix() . ' Batch completed', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'success' => $successCount,\n 'failed' => count($failedIds),\n 'skipped' => $skippedCount,\n 'requested' => count($this->crmIds),\n 'processed' => count($filteredIds),\n 'duration_ms' => $durationMs,\n ]);\n\n if (! empty($failedIds)) {\n Log::error($this->getLogPrefix() . ' Data-level failures require investigation', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'failedCount' => \\count($failedIds),\n 'failedIds' => $failedIds,\n 'errors' => $result['errors'] ?? [],\n ]);\n }\n }\n\n /**\n * Called by Laravel after all $tries are exhausted.\n *\n * System-level failure (HubSpot API down, timeout, OOM) - the entire handle() threw\n * an unhandled exception on every attempt. Requeue ALL IDs back to Redis so the next\n * SyncObjects cycle picks them up.\n *\n * This does NOT fire for data-level failures (those are caught in the per-object loop\n * and logged without retrying).\n *\n * Requeue Strategy:\n * - Each ID is individually requeued to Redis using SADD (automatic deduplication)\n * - If requeue fails for specific IDs, they are logged as permanently lost\n * - Redis requeue failures are rare (Redis connection issues) but critical\n */\n protected function requeueFailedBatch(\\Throwable $exception): void\n {\n $redisService = app(BatchSyncRedisService::class);\n\n Log::error($this->getLogPrefix() . ' Job failed after all retries, requeuing IDs', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'idCount' => \\count($this->crmIds),\n 'error' => $exception->getMessage(),\n ]);\n\n $requeued = 0;\n $failedToRequeue = [];\n\n foreach ($this->crmIds as $crmId) {\n try {\n $redisService->collectObjectIdToBatch(\n $this->getObjectType(),\n (string) $crmId,\n $this->crmConfigurationId,\n 'all'\n );\n $requeued++;\n } catch (\\Throwable $e) {\n $failedToRequeue[] = $crmId;\n Log::warning($this->getLogPrefix() . ' Failed to requeue ID', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'crmId' => $crmId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n Log::info($this->getLogPrefix() . ' Requeue completed after job failure', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'requeued' => $requeued,\n 'failedToRequeue' => \\count($failedToRequeue),\n 'total' => \\count($this->crmIds),\n ]);\n\n if (! empty($failedToRequeue)) {\n Log::critical($this->getLogPrefix() . ' Permanently lost IDs after requeue failure', [\n 'crmConfigurationId' => $this->crmConfigurationId,\n 'failedIds' => $failedToRequeue,\n ]);\n }\n }\n\n private function filterExistingObjects(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array\n {\n $objectType = $this->getObjectType();\n\n if ($objectType === self::OBJECT_TYPE_CONTACT) {\n return $this->filterExistingContacts($crmConfig, $crmEntityRepository);\n }\n\n if ($objectType === self::OBJECT_TYPE_COMPANY) {\n return $this->filterExistingAccounts($crmConfig, $crmEntityRepository);\n }\n\n return $this->crmIds;\n }\n\n private function filterExistingContacts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array\n {\n $existingContacts = $crmEntityRepository->getExistingContactCrmIds($crmConfig, $this->crmIds);\n $existingIds = array_intersect($this->crmIds, $existingContacts);\n\n return array_values($existingIds);\n }\n\n private function filterExistingAccounts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array\n {\n $existingAccounts = $crmEntityRepository->getExistingAccountCrmIds($crmConfig, $this->crmIds);\n $existingIds = array_intersect($this->crmIds, $existingAccounts);\n\n return array_values($existingIds);\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,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Tx: Auto","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Cancel Running Statements","depth":4,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-6633995899592120377
|
2223140599368505956
|
idle
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
17
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Jobs\Crm\Hubspot;
use Illuminate\Support\Facades\Log;
use Jiminny\Contracts\Services\Crm\Provider\HubspotInterface;
use Jiminny\Models\Crm\Configuration;
use Jiminny\Repositories\Crm\CrmConfigurationRepository;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Services\Crm\Hubspot\BatchSyncRedisService;
use Jiminny\Services\ResolveTeamCrmConnection;
/**
* Shared logic for HubSpot batch import jobs.
*
* Provides common functionality for importing batches of HubSpot objects (deals, contacts, companies)
* with consistent error handling, logging, and failure recovery mechanisms.
*
* Failure Handling Strategy:
*
* 1. SYSTEM-LEVEL FAILURES (HubSpot API down, DB connection lost, timeout):
* - Exception propagates out of handle()
* - Laravel retries the job up to $tries times with $backoff delays
* - If all retries exhausted, failed() requeues ALL IDs back to Redis
* - Next SyncObjects cycle will pick them up and retry
*
* 2. DATA-LEVEL FAILURES (per-object exceptions during import):
* - Caught inside the per-object loop in import*BatchByIds() methods
* - Indicate permanent issues: DB constraints, corrupt data, unmappable values
* - Retrying won't fix them - logged with specific error per ID
* - NOT requeued to avoid infinite retry loops
* - Require manual investigation and data correction
*
* Note: Objects intentionally skipped (missing dependencies like account, unknown pipeline/stage)
* return null and are not considered failures - they simply cannot be imported until dependencies exist.
*/
trait ImportBatchJobTrait
{
private const string OBJECT_TYPE_CONTACT = 'contact';
private const string OBJECT_TYPE_COMPANY = 'company';
private const string OBJECT_TYPE_DEAL = 'deal';
private int $crmConfigurationId;
private array $crmIds;
abstract protected function getObjectType(): string;
abstract protected function getLogPrefix(): string;
abstract protected function importBatch(HubspotInterface $crmService, array $crmIds): array;
protected function processImportBatch(
ResolveTeamCrmConnection $resolveTeamCrmConnection,
CrmConfigurationRepository $crmConfigurationRepository,
CrmEntityRepository $crmEntityRepository
): void {
$crmConfig = $crmConfigurationRepository->findById($this->crmConfigurationId);
if ($crmConfig === null) {
Log::error($this->getLogPrefix() . ' CRM configuration not found', [
'crmConfigurationId' => $this->crmConfigurationId,
]);
return;
}
$crmService = $resolveTeamCrmConnection->resolveForTeam($crmConfig->getTeam());
if (! $crmService instanceof HubspotInterface) {
Log::error($this->getLogPrefix() . ' CRM service is not HubSpot', [
'crmConfigurationId' => $this->crmConfigurationId,
'serviceClass' => $crmService::class,
]);
return;
}
Log::info($this->getLogPrefix() . ' Processing batch', [
'crmConfigurationId' => $this->crmConfigurationId,
'batchSize' => count($this->crmIds),
]);
$filteredIds = $this->filterExistingObjects($crmConfig, $crmEntityRepository);
if (empty($filteredIds)) {
Log::info($this->getLogPrefix() . ' No existing objects found in Jiminny, skipping batch', [
'crmConfigurationId' => $this->crmConfigurationId,
'requestedCount' => count($this->crmIds),
]);
return;
}
$startTime = microtime(true);
$result = $this->importBatch($crmService, $filteredIds);
$durationMs = round((microtime(true) - $startTime) * 1000, 2);
$successCount = $result['success_count'] ?? \count($result['success'] ?? []);
$failedIds = $result['failed_ids'] ?? [];
$skippedCount = count($this->crmIds) - count($filteredIds);
Log::info($this->getLogPrefix() . ' Batch completed', [
'crmConfigurationId' => $this->crmConfigurationId,
'success' => $successCount,
'failed' => count($failedIds),
'skipped' => $skippedCount,
'requested' => count($this->crmIds),
'processed' => count($filteredIds),
'duration_ms' => $durationMs,
]);
if (! empty($failedIds)) {
Log::error($this->getLogPrefix() . ' Data-level failures require investigation', [
'crmConfigurationId' => $this->crmConfigurationId,
'failedCount' => \count($failedIds),
'failedIds' => $failedIds,
'errors' => $result['errors'] ?? [],
]);
}
}
/**
* Called by Laravel after all $tries are exhausted.
*
* System-level failure (HubSpot API down, timeout, OOM) - the entire handle() threw
* an unhandled exception on every attempt. Requeue ALL IDs back to Redis so the next
* SyncObjects cycle picks them up.
*
* This does NOT fire for data-level failures (those are caught in the per-object loop
* and logged without retrying).
*
* Requeue Strategy:
* - Each ID is individually requeued to Redis using SADD (automatic deduplication)
* - If requeue fails for specific IDs, they are logged as permanently lost
* - Redis requeue failures are rare (Redis connection issues) but critical
*/
protected function requeueFailedBatch(\Throwable $exception): void
{
$redisService = app(BatchSyncRedisService::class);
Log::error($this->getLogPrefix() . ' Job failed after all retries, requeuing IDs', [
'crmConfigurationId' => $this->crmConfigurationId,
'idCount' => \count($this->crmIds),
'error' => $exception->getMessage(),
]);
$requeued = 0;
$failedToRequeue = [];
foreach ($this->crmIds as $crmId) {
try {
$redisService->collectObjectIdToBatch(
$this->getObjectType(),
(string) $crmId,
$this->crmConfigurationId,
'all'
);
$requeued++;
} catch (\Throwable $e) {
$failedToRequeue[] = $crmId;
Log::warning($this->getLogPrefix() . ' Failed to requeue ID', [
'crmConfigurationId' => $this->crmConfigurationId,
'crmId' => $crmId,
'error' => $e->getMessage(),
]);
}
}
Log::info($this->getLogPrefix() . ' Requeue completed after job failure', [
'crmConfigurationId' => $this->crmConfigurationId,
'requeued' => $requeued,
'failedToRequeue' => \count($failedToRequeue),
'total' => \count($this->crmIds),
]);
if (! empty($failedToRequeue)) {
Log::critical($this->getLogPrefix() . ' Permanently lost IDs after requeue failure', [
'crmConfigurationId' => $this->crmConfigurationId,
'failedIds' => $failedToRequeue,
]);
}
}
private function filterExistingObjects(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array
{
$objectType = $this->getObjectType();
if ($objectType === self::OBJECT_TYPE_CONTACT) {
return $this->filterExistingContacts($crmConfig, $crmEntityRepository);
}
if ($objectType === self::OBJECT_TYPE_COMPANY) {
return $this->filterExistingAccounts($crmConfig, $crmEntityRepository);
}
return $this->crmIds;
}
private function filterExistingContacts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array
{
$existingContacts = $crmEntityRepository->getExistingContactCrmIds($crmConfig, $this->crmIds);
$existingIds = array_intersect($this->crmIds, $existingContacts);
return array_values($existingIds);
}
private function filterExistingAccounts(Configuration $crmConfig, CrmEntityRepository $crmEntityRepository): array
{
$existingAccounts = $crmEntityRepository->getExistingAccountCrmIds($crmConfig, $this->crmIds);
$existingIds = array_intersect($this->crmIds, $existingAccounts);
return array_values($existingIds);
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results
Tx: Auto
Cancel Running Statements
Playground...
|
44290
|
|
44391
|
NULL
|
0
|
2026-04-17T08:45:46.630356+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776415546630_m1.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
FirefoxFileEditViewHistoryBookmarksProfilesToolsWi FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelpmeet.google.com/xpx-omah-rkn= Support Daily • in 3 h 15 m100% C8 • Fri 17 Apr 11:45:46=Ilian Kyuchukov (Presenting, annotating)6ProfiesawsCloudwatch | eu-west-1CloudWatch [ eu-west-1eu-west-1.console.aws.amazon.com/cloudwatch/home?region=eu-west-1#logsV2:logs-insightsS3FqueryDetailS3D-(end-0-start--86400-timeType-'RELATIVE-1z-'UTC-unit-'seconds-editor Strin.(Option+S)© Ask Amazon QCurope Oreland)• 16• 1%.• 19|• 20.• 21• 22.• 23• 24.• 26• 27• 28.•29.• 34• 31.• 32.• 34.• 35.• 36.• 37•38.• 40.• 41• 43E CoudShellCloudWatchLogs Insights generalPtimestamp2026-04-16T19:14:08.64922026-04-16T19:14:03.65822026-04-16T19:14:08.65822826-04- 16T19:14:88.65622026-84-16719:14:98.66622226-04-16T19:14:08.67522826-04-16T19:14:88.67822026-04-16T19: 14:08.68422026-04-16T19:14:08.68422826-04-16T19:14:03.68522826-04-16T19:14:08.68522026-04-16T19:14:08.685226-M-1519:4r0X.em2026-04-16719:14:03.68922826-04-16T19:14:08.68922826-04-16T19:14:08.68922826-04-16T19:14:09.69222026-04-16T19:14:03.69220-04-101:4.0.6%h2026-04-16T19:14:08.22522026-04-16T19:14:08.71122826-04-16T19:14:08.72322026-04-16T19:14:88.72422826-04-16T19:14:08.72522826-64-16T19:14:08.7252FeedbackInessogé[2826-04-16 19:14:03] production.INFD: [SocialAccountService] Token retrieved ("sociolAccountId":7880, "provider":"solesforce"} ["correlation_(d":*3192boef-ec60-4904-ca16-ef51de7bb4de", "troce_td": *c9910669).(2826-04-16 19:14:84) productioo. INFO: [SyncObjects] After mtnory usoge: ('"tearr: "2335b051-9414-401d-b822-9bf8738(3062", "asose" :144679256, "real_enooe* :253755392, "pid": 65697) ['correletton.ld*: *ceßet6ce-16.(2826-04-16 19:14:0S] production. INFO:[SyncObjects] Dispatching Selesforce fetch jobs [Tteant: 7914288ce-505e-4007-908c-6009efe4f*/"crm._configurot1o0_.td":54, "entity_types*: ["leod" ,"eccouet", 'opportuni t.1226-04-16 19:14:04) proфuctioe.1N0:(SyncObjects] Dispatched fetch job {"crm.configurotion_id":54, "entity_type":"lead", "since": *2026-04-16T18:44:09-00:80") ("correletion_(d": "3192boef-ec6o-4904-a016-ef.(2826-04-16 19:14:05) production. INFO:(Sync0ojectsJ Dispatched fetch job ["crm_configurotion_id":54, 'entity,type": "occcunt", 'since*: *2026-av-16T18:45:28-00:00*) ("correlation_1d": *3192b0ef-ec6o-4904- oa16.[SyncObjects) Before nenory usoge: (['"tean":*ed4SS3f7-da1b-4dc2-99co-9685fB181oRb*, "usoge" :144680688, "reol_usoge" : 253755392, "pid":65687) ["cornelotion_id":*011c0992-6_(2826-04-16 19:14:05) productton.INFO: [SyncObjects) Dispotched fetch job ("crn.conftguration_id":54, "'entity_type": "opportunity"„"'since": *2826-04-16T18:45:19+00:00') ("cornelation_id": *3192boef-ec6o-4904-..(2826-04-16 19:14:08) production. INFO: [SasVisibilityControl) job vistbtlity chanped ("QueueUrl":"crn-sync", 'ReceiptHandle*: "AQEB7VOSP4fILel +SereOTceJBA95HKTÜIVCK+h)P+Fh296ETNACDCACRMeNCyV29VojXloP+7oL9.[2826-04-16 19:14:08) production.INFO: [SociolAccountService) Fetching token ("socialAccount.Id":12390, "provider": "hubspot") ("correlation_id":*a1lc0992-6223-457c-91db-9eScoß28f219", "troce_id*:*099106f9-e7-[2826-04-16 19:14:08] production. INFO: [SyncObjects] Dispatched fetch job {"cre_configurotton.id":S4, "entity-type":"contoct", "since":*2026-84-16T18:45:01400:00*) ["correlation.id*: *3192boef-ec6а-4904-0016..(2826-04-16 19:14:08) productiion. INFO: [EncryptedTokenManoger) Generating eccess token. ("sode": "legocy") ["correlation,id":*011ca992-6223-457c-91db-9eScoß28f219", "troce_(d" :*09918619-e768-403c-958c-39dff..(2226-04-16 19:14:08) production.INF0: ((rnOwnerkesolver) Integration owner natched os (RM Owrier ("crn,provider": "hubspot", "crk.onner":7339, "teon,id":80) ("correlation_id": *01lc0992-6223-457c-910b-9eScoß2(2026-04-16 19:14:08] production. INFO: [SociolAccountService) Token retritved ("sociolAccountld" :12390, "provider": Thubspot*) ('correlation,id": "a11ca992-6223-457c-91db-9eSc00281219", "troce_Id°: *09918619-e.(2826-04-16 19:14:08] production, INFO:etchsynchedisservice neset nete setch contiaid:9, ohiectetwoecontoctcutttyoeo,"neto,key": "botch.sync_contect:neto:59:0ll*,*reset_at*:1726366848(2826-04-16 19:14:08) production. INFO:[SyncObjects) All Salesforce fetch jobs dispotched ("teon": *914298ot-SbSe-4b07-9o0c-6000889efe4f", "cr. conf(guration_id":S4) ("correlation_id": *3192boef-ecба-4904-о..[2026-04-16 19:14:08] production. INFO:[SyncObjects) Oispatched fetch, job {"cre_configurotion_1d":54, "entity_type":"contoct_role", "since":*2026-04-36718:45:07÷00:00*) {"corretetion.1d":*3192boef-ecбa-4984.(2026-04-16 19:14:08] production. INFO:(SyncOojects) After nesory usage: ["tean*: *9142080e-S05e-4007-9o0c-6000189efe4f", "utoye":1495S9SS2, "reol_asoge":182452224, *p16" : 59361) ['correletion_id*:*3192boef-ec-(2826-04-16 19:14:08] production.INFO:(HubspotkebhookBatchSyncStrotegy] Geol batches processed ("config_id':59, "total_dispatchedt:0} ("correlation,ild": "o11c6992-6223-457c-91do-9eScoB2Sf219%, "troce_id":"a(2026-04-16 19:14:083[HubSpot) Synced opportunittes ("teor":80, "synk_count*:0, "totol":0, "last_syncod,sa":null) ("coerelation, (6*:"a11ca992-6223-457c-91do-9e5coß28f219", "troce_id" :*099106..(2026-04-16 19:14:89) production.(MebbookSyricBatchProcessor) Ratch processing coepleted ("object,type":"contoct", "config_id":59, "totol_dispetched": 10, "batches_dispatched" : 1) ["correletton_td*: *allco.(2026-04-16 19:14:08] production.tuntties using Strattgy: nebhookbatch ("correlotion_(a":"a1lc0992-6223-457c-91db-%e5col28f219", "troce_id":*009106f9-e768-483c-958c-390tf69e368.Dyrcuonects after merosy usoge: (tran: cols53t/-do10-4осв-У0с0-300918261000 43000 0344/4/512. 0001-11090 803/35392. 010 80 68731 60r601102.168 08.60992-06(2826-04-16 19:14:08] production. INF0:(SyncObjects] Before monory usoge: ("'tean": *98571420-c3e5-4693-0009-cb687612f7a7" ,"usoge":140559264, "real._usoge": 182452224, "pld*: 59361) ("correlation_id":*e2189552-b..(2826-04-16 19:14:85) production. INFO:[SasVisibilityControl] job visibility chonged ("Queueur)":"crn-sync", "ReceiptHondle": *ADEBtFY1kfzoeGAo2h5 1.pu/cXaS6MZ12032ry48Hd1+OATa0w6YGpFTyNBRJPEYYtRSw/2DXfGAx10z.[2826-04-16 19:14:03)production.INFO: [SociolAccountServtce]- Fetching token ("soctolAccountId": 11645, "provider": "hubspot") ("cornelotlon.ld":"eZ188552-bb96-4189-boB2-f21460r06599", "troce_fd" :*099106f9-e7-(2826-04-16 19:14:88) production.INFO:|(SociolAccountService) Token retrieved ("sociolAccountld":11648, 'provider*: "hubspot*) ("correlation_id":"+2180552-6696-4189-bo82-+24462+0e599", "troce_ld^: *09910619-e_("node": "legocy"} ("correlotion,(a*:*+2182552-6096-4129-Bo82-121460e26509*. "troce_td*:*09910619-+768-463c-958c-39d1.2826-84-16 19:14:051 0600 4910.Lernunerkesolver) Inteo detoo oPivacyCoolde preferencesllian KyuchukovNikolay NikolovVasil VasilevMihail MihaylovLukas Kovalik11:45 AM | Daily - ProcessingLộ3...
|
NULL
|
3284064384053596964
|
NULL
|
visual_change
|
ocr
|
NULL
|
FirefoxFileEditViewHistoryBookmarksProfilesToolsWi FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelpmeet.google.com/xpx-omah-rkn= Support Daily • in 3 h 15 m100% C8 • Fri 17 Apr 11:45:46=Ilian Kyuchukov (Presenting, annotating)6ProfiesawsCloudwatch | eu-west-1CloudWatch [ eu-west-1eu-west-1.console.aws.amazon.com/cloudwatch/home?region=eu-west-1#logsV2:logs-insightsS3FqueryDetailS3D-(end-0-start--86400-timeType-'RELATIVE-1z-'UTC-unit-'seconds-editor Strin.(Option+S)© Ask Amazon QCurope Oreland)• 16• 1%.• 19|• 20.• 21• 22.• 23• 24.• 26• 27• 28.•29.• 34• 31.• 32.• 34.• 35.• 36.• 37•38.• 40.• 41• 43E CoudShellCloudWatchLogs Insights generalPtimestamp2026-04-16T19:14:08.64922026-04-16T19:14:03.65822026-04-16T19:14:08.65822826-04- 16T19:14:88.65622026-84-16719:14:98.66622226-04-16T19:14:08.67522826-04-16T19:14:88.67822026-04-16T19: 14:08.68422026-04-16T19:14:08.68422826-04-16T19:14:03.68522826-04-16T19:14:08.68522026-04-16T19:14:08.685226-M-1519:4r0X.em2026-04-16719:14:03.68922826-04-16T19:14:08.68922826-04-16T19:14:08.68922826-04-16T19:14:09.69222026-04-16T19:14:03.69220-04-101:4.0.6%h2026-04-16T19:14:08.22522026-04-16T19:14:08.71122826-04-16T19:14:08.72322026-04-16T19:14:88.72422826-04-16T19:14:08.72522826-64-16T19:14:08.7252FeedbackInessogé[2826-04-16 19:14:03] production.INFD: [SocialAccountService] Token retrieved ("sociolAccountId":7880, "provider":"solesforce"} ["correlation_(d":*3192boef-ec60-4904-ca16-ef51de7bb4de", "troce_td": *c9910669).(2826-04-16 19:14:84) productioo. INFO: [SyncObjects] After mtnory usoge: ('"tearr: "2335b051-9414-401d-b822-9bf8738(3062", "asose" :144679256, "real_enooe* :253755392, "pid": 65697) ['correletton.ld*: *ceßet6ce-16.(2826-04-16 19:14:0S] production. INFO:[SyncObjects] Dispatching Selesforce fetch jobs [Tteant: 7914288ce-505e-4007-908c-6009efe4f*/"crm._configurot1o0_.td":54, "entity_types*: ["leod" ,"eccouet", 'opportuni t.1226-04-16 19:14:04) proфuctioe.1N0:(SyncObjects] Dispatched fetch job {"crm.configurotion_id":54, "entity_type":"lead", "since": *2026-04-16T18:44:09-00:80") ("correletion_(d": "3192boef-ec6o-4904-a016-ef.(2826-04-16 19:14:05) production. INFO:(Sync0ojectsJ Dispatched fetch job ["crm_configurotion_id":54, 'entity,type": "occcunt", 'since*: *2026-av-16T18:45:28-00:00*) ("correlation_1d": *3192b0ef-ec6o-4904- oa16.[SyncObjects) Before nenory usoge: (['"tean":*ed4SS3f7-da1b-4dc2-99co-9685fB181oRb*, "usoge" :144680688, "reol_usoge" : 253755392, "pid":65687) ["cornelotion_id":*011c0992-6_(2826-04-16 19:14:05) productton.INFO: [SyncObjects) Dispotched fetch job ("crn.conftguration_id":54, "'entity_type": "opportunity"„"'since": *2826-04-16T18:45:19+00:00') ("cornelation_id": *3192boef-ec6o-4904-..(2826-04-16 19:14:08) production. INFO: [SasVisibilityControl) job vistbtlity chanped ("QueueUrl":"crn-sync", 'ReceiptHandle*: "AQEB7VOSP4fILel +SereOTceJBA95HKTÜIVCK+h)P+Fh296ETNACDCACRMeNCyV29VojXloP+7oL9.[2826-04-16 19:14:08) production.INFO: [SociolAccountService) Fetching token ("socialAccount.Id":12390, "provider": "hubspot") ("correlation_id":*a1lc0992-6223-457c-91db-9eScoß28f219", "troce_id*:*099106f9-e7-[2826-04-16 19:14:08] production. INFO: [SyncObjects] Dispatched fetch job {"cre_configurotton.id":S4, "entity-type":"contoct", "since":*2026-84-16T18:45:01400:00*) ["correlation.id*: *3192boef-ec6а-4904-0016..(2826-04-16 19:14:08) productiion. INFO: [EncryptedTokenManoger) Generating eccess token. ("sode": "legocy") ["correlation,id":*011ca992-6223-457c-91db-9eScoß28f219", "troce_(d" :*09918619-e768-403c-958c-39dff..(2226-04-16 19:14:08) production.INF0: ((rnOwnerkesolver) Integration owner natched os (RM Owrier ("crn,provider": "hubspot", "crk.onner":7339, "teon,id":80) ("correlation_id": *01lc0992-6223-457c-910b-9eScoß2(2026-04-16 19:14:08] production. INFO: [SociolAccountService) Token retritved ("sociolAccountld" :12390, "provider": Thubspot*) ('correlation,id": "a11ca992-6223-457c-91db-9eSc00281219", "troce_Id°: *09918619-e.(2826-04-16 19:14:08] production, INFO:etchsynchedisservice neset nete setch contiaid:9, ohiectetwoecontoctcutttyoeo,"neto,key": "botch.sync_contect:neto:59:0ll*,*reset_at*:1726366848(2826-04-16 19:14:08) production. INFO:[SyncObjects) All Salesforce fetch jobs dispotched ("teon": *914298ot-SbSe-4b07-9o0c-6000889efe4f", "cr. conf(guration_id":S4) ("correlation_id": *3192boef-ecба-4904-о..[2026-04-16 19:14:08] production. INFO:[SyncObjects) Oispatched fetch, job {"cre_configurotion_1d":54, "entity_type":"contoct_role", "since":*2026-04-36718:45:07÷00:00*) {"corretetion.1d":*3192boef-ecбa-4984.(2026-04-16 19:14:08] production. INFO:(SyncOojects) After nesory usage: ["tean*: *9142080e-S05e-4007-9o0c-6000189efe4f", "utoye":1495S9SS2, "reol_asoge":182452224, *p16" : 59361) ['correletion_id*:*3192boef-ec-(2826-04-16 19:14:08] production.INFO:(HubspotkebhookBatchSyncStrotegy] Geol batches processed ("config_id':59, "total_dispatchedt:0} ("correlation,ild": "o11c6992-6223-457c-91do-9eScoB2Sf219%, "troce_id":"a(2026-04-16 19:14:083[HubSpot) Synced opportunittes ("teor":80, "synk_count*:0, "totol":0, "last_syncod,sa":null) ("coerelation, (6*:"a11ca992-6223-457c-91do-9e5coß28f219", "troce_id" :*099106..(2026-04-16 19:14:89) production.(MebbookSyricBatchProcessor) Ratch processing coepleted ("object,type":"contoct", "config_id":59, "totol_dispetched": 10, "batches_dispatched" : 1) ["correletton_td*: *allco.(2026-04-16 19:14:08] production.tuntties using Strattgy: nebhookbatch ("correlotion_(a":"a1lc0992-6223-457c-91db-%e5col28f219", "troce_id":*009106f9-e768-483c-958c-390tf69e368.Dyrcuonects after merosy usoge: (tran: cols53t/-do10-4осв-У0с0-300918261000 43000 0344/4/512. 0001-11090 803/35392. 010 80 68731 60r601102.168 08.60992-06(2826-04-16 19:14:08] production. INF0:(SyncObjects] Before monory usoge: ("'tean": *98571420-c3e5-4693-0009-cb687612f7a7" ,"usoge":140559264, "real._usoge": 182452224, "pld*: 59361) ("correlation_id":*e2189552-b..(2826-04-16 19:14:85) production. INFO:[SasVisibilityControl] job visibility chonged ("Queueur)":"crn-sync", "ReceiptHondle": *ADEBtFY1kfzoeGAo2h5 1.pu/cXaS6MZ12032ry48Hd1+OATa0w6YGpFTyNBRJPEYYtRSw/2DXfGAx10z.[2826-04-16 19:14:03)production.INFO: [SociolAccountServtce]- Fetching token ("soctolAccountId": 11645, "provider": "hubspot") ("cornelotlon.ld":"eZ188552-bb96-4189-boB2-f21460r06599", "troce_fd" :*099106f9-e7-(2826-04-16 19:14:88) production.INFO:|(SociolAccountService) Token retrieved ("sociolAccountld":11648, 'provider*: "hubspot*) ("correlation_id":"+2180552-6696-4189-bo82-+24462+0e599", "troce_ld^: *09910619-e_("node": "legocy"} ("correlotion,(a*:*+2182552-6096-4129-Bo82-121460e26509*. "troce_td*:*09910619-+768-463c-958c-39d1.2826-84-16 19:14:051 0600 4910.Lernunerkesolver) Inteo detoo oPivacyCoolde preferencesllian KyuchukovNikolay NikolovVasil VasilevMihail MihaylovLukas Kovalik11:45 AM | Daily - ProcessingLộ3...
|
NULL
|
|
44392
|
NULL
|
0
|
2026-04-17T08:45:53.919349+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776415553919_m2.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorToo PhpStormFileEditViewNavigateCodeLaravelRefactorToolsWindowFV faVsco.s v#11894 on JY-18909-automated-reports-ask-iminny kHelpProjectv© PlaybookCategoryRepo© PlaybookRepository.php© PlaylistActivity Repositor©PlaylistRepository.php® PlaylistShareRepositoryQuestionRepository.php© RoleChangeEventRepos© RoleRepository.php© SearchRepository.php© SnapshotRepository.ph|© SocialAccountRepositor© StageRepository.php© SubscriptionSetRepositTaskRepository.php• TeamAiContextRepositc© TeamDomainsRepositor© TeamInsightsRepository© TeamRepository.php© ThemeRepository.php©) TimezoneRepository.ph© TopicRepository.php© TopicTriggerRepository© TrackRepository.php© TranscriptionModelLoce© TranscriptionRepository© TranscriptionSummaryF© UserRepository.php© VocabularyRepository.p> M7 Rulesv M ServicesD ActivityD AjReportsD AvatarCalendar[ ConferenceD CrmBullhorn_ closeD CopperCrmooiectsM DecorateActivitv• Dummy→ HelpersD Hubspot[J AccountSyncStra› D ActionsC ContactSyncStrat> UDTOWFieldsD JournalM MetadataOpportunitySync!> M7Pagination> D ProspectSearchs> D Redisv D ServiceTraits€ OpportunitySy& SyncCrmEntiti© SyncFieldsTra© AutomatedReportsService.php© SendReportJob.php© SendReportMailJob.php© ReportController.phpTokenBuilder.php• TeamSetupController.phppnp apl.onoFilesystem.php• Team.php© TrackProviderInstalledEvent.php© ActivityLogged.phpAutomatedReportsCallbackService.php© RequestGenerateAskJiminnyReportJob.php© RequestGenerateReportJob.php© SyncOpportunity.phpC Opportunity.phpC OpportunityUpdated.phpOpoonunitystadeupaaled.onoC EventServiceProvider.phpC CreateHeldActivityEvent.php€ OpportunitySyncTrait.php x© OpportunityPendingAiAnalysisAfterStageChanged.php© ImportOpportunityBatch.php© ImportBatchJobTrait.phpC AutomatedReport.php© RunOpportunityAiAnalysis.php€ HasAttributes.php© ProcessAiAutomationAnalysisResults.php© Service.phpAutomatedReportResult.php"podcast_audio_url"Cc W.*trait OpportunitySyncTraitprivate function buildOpportunityData(0 results83890590670/937941942943944945740947948949950951952953954955956958959700962964965966967968969970971972973974988984432 X2 X19 ^2 usagesprivate function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess{...}Lusaeesprivate function getBusinessProcess(string $pipelineId): ?BusinessProcessf...}2 usagesprivate function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stageif (empty($stageId)) {return nulli$cacheKey = $businessProcess->getId() . ':'if (isset($this->cachedStages[$cacheKey])) {return $this->cachedStages[$cacheKey]:. $stageId;$stage = $this->crmEntityRepository->getPipelineStageByConditions($businessProcess,'crm_provider_id' => $stageId,iwoe"o swaderere UeruruNreif ($stage === null) {$this->importStages(null, $stageId);if ($stage === null) {фs->loggerntoospot meae does notexist→.tagel$this->cachedStages[$cacheKey] = $stage;recurn ostade.lusageprivate function resolveAmount(array $properties): ?stringf...}lusayeprivate function parseCleanDatetime(string $datetime): ?Carbonf...}E custom.log= laravel.logA SF [jiminny@localhost]C scratch_1jsonV Onboard.vue< Hs local liminnyalocalnostconsole EUl© CrmEntityRepository.php XA console [STAGING]class CrmEntityRepository281): Opportunity {...+fi crm_configurations [EU]A console [PROD]7467132 л5501332333334335336337339340341—544=343356357370F371377378-379=380382383384385396397403404405406407408-40941041142242274234227450=4362 usagespublic function upsertOpportunity(array $attributes, array $data): Opp/** @var ?Opportunity $opportunity */$opportunity = Opportunity: :withTrashed()->where($attributes)->firif ($opportunity === null) {$opportunity = Opportunity::create($data);felse {$opportunity->update($data);return Sopportunity;public function importstage(Configuration $configuration, string $objeLusagespublic function importBusinessProcess(Configuration $configuration,public function findAccountByExternalId(Configuration $configuration,/*** Find multiple accounts by their external CRM IDs* oocran contourcson ocontrourdcion* oocral arrausstrinos oeciirrovderros* Oreturn Collection<Account>s usagespublic function findAccountsByExternalIds(Configuration $configurationpublic function findContactByExternalId(Configuration $configuration,/*** Find multiple contacts by their external CRM IDS* @param Configuration Sconfiguration* Oparam array<string> $ermProviderIds* @return Collection<Contact>Tusdyepublic function findContactsByExternalIds(Configuration $configurationpubLic tunccion tindleadbyexcernalld conriguracion sconfiguracion, sch14 usagespublic function find0pportunityByExternalId(Configuration $configurati> 0Support Daily • in 3h 15 mAL AutomatedReportsCommandTestv100% C•8 • Fri 17 Apr 11:45:53CascadeAutomated Report Reti© Investigating HubSp+D ...buildOpportunityData( only sets stage id if $stage is non-null (line 893-895). But upsertOpportunity() always calls $opportunity→>update($data) with whatever is in $data.In update0pportunity() - Sstage can be null when $businessProcess is null (line 802):0 phpw$stage = $businessProcess ? $this→>resolveStage(...) : null;When $stage is null, stage_id is absent from $data entirely. But update($data) doesn't mean "keepexisting value" for absent keys — it just doesn't touch that column. So stage_id is preserved.but nere's the acrual osclllation source — resolvestage caches nuule• OpportunitySyncTrait.php:969$this->cachedStages [$cacheKey] = $stage; // caches null after importStages() is calledThis means:• Sync run 1 (new Service instance, empty cache): stage not in DB → importStages() called $stage= null → stage_id notsetin Sdata → updatel) doesh'ttouch stage_id → opportunity keepswhatever stage_id was set previously (or null )Sync run 2 (fresh instance, empty cache again): stage IS in DB now (imported in run 1) → resolves tostage 456 → stage_id = 456 written → OpportunityStageUpdated firesSync run 3: same as run 2... unless importStages() somehow re-runs and overwrites the stagestable witn alterentibsThe real oscillation: importStages() recreates stages with new DB IDsService.php:459-469— importStages() uses update0rCreate on stages:D php$stage = $this->config->stages ()→>update0rCreate(l'crm_provider_id' => $sl'id'],dalaaalnThis is fine — it reuses the same DB id . BUT resolveBusinessProcess() also calls importStages() whena plpeline is missing uine g20. ll a olpeline gets recrealed with a new BusinessProcess Db recora, the business_process_id → stage relationship could point to a different stage DB ID.Most likely actual cause: Two different sync paths are running concurrently or in rapid succession:1. SyncObjects scheduled job → processes the deal → writes stage_id = 4562. SvncOpportunity iob (triaaered by somethina else) → resolves via a different businessProcessinstance → writes stage id = 123lnese wo loos run noevencenty wiun no coorelnation. ooun calllino uoser Uoportuniv on the sameopportunity, alternating between two valid stage IDs that belong to different BusinessProcess recordspolntine lo tne same muospot olpellne - le. cupllcare businessprocess rows in the Db for the same chiprovider_id.Command docke• dockercontia =dinken1andeto r aronsaguratkon eecute( tean', fn(15a) =→ 1sa-deletebp-»erPHP LEOL;Run 2i+Ask anything (24L)+ <>Code Claude Sonnet 4.6Unhandled (Severwinasun lea( 4 spaces...
|
NULL
|
-4203566092012763467
|
NULL
|
visual_change
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorToo PhpStormFileEditViewNavigateCodeLaravelRefactorToolsWindowFV faVsco.s v#11894 on JY-18909-automated-reports-ask-iminny kHelpProjectv© PlaybookCategoryRepo© PlaybookRepository.php© PlaylistActivity Repositor©PlaylistRepository.php® PlaylistShareRepositoryQuestionRepository.php© RoleChangeEventRepos© RoleRepository.php© SearchRepository.php© SnapshotRepository.ph|© SocialAccountRepositor© StageRepository.php© SubscriptionSetRepositTaskRepository.php• TeamAiContextRepositc© TeamDomainsRepositor© TeamInsightsRepository© TeamRepository.php© ThemeRepository.php©) TimezoneRepository.ph© TopicRepository.php© TopicTriggerRepository© TrackRepository.php© TranscriptionModelLoce© TranscriptionRepository© TranscriptionSummaryF© UserRepository.php© VocabularyRepository.p> M7 Rulesv M ServicesD ActivityD AjReportsD AvatarCalendar[ ConferenceD CrmBullhorn_ closeD CopperCrmooiectsM DecorateActivitv• Dummy→ HelpersD Hubspot[J AccountSyncStra› D ActionsC ContactSyncStrat> UDTOWFieldsD JournalM MetadataOpportunitySync!> M7Pagination> D ProspectSearchs> D Redisv D ServiceTraits€ OpportunitySy& SyncCrmEntiti© SyncFieldsTra© AutomatedReportsService.php© SendReportJob.php© SendReportMailJob.php© ReportController.phpTokenBuilder.php• TeamSetupController.phppnp apl.onoFilesystem.php• Team.php© TrackProviderInstalledEvent.php© ActivityLogged.phpAutomatedReportsCallbackService.php© RequestGenerateAskJiminnyReportJob.php© RequestGenerateReportJob.php© SyncOpportunity.phpC Opportunity.phpC OpportunityUpdated.phpOpoonunitystadeupaaled.onoC EventServiceProvider.phpC CreateHeldActivityEvent.php€ OpportunitySyncTrait.php x© OpportunityPendingAiAnalysisAfterStageChanged.php© ImportOpportunityBatch.php© ImportBatchJobTrait.phpC AutomatedReport.php© RunOpportunityAiAnalysis.php€ HasAttributes.php© ProcessAiAutomationAnalysisResults.php© Service.phpAutomatedReportResult.php"podcast_audio_url"Cc W.*trait OpportunitySyncTraitprivate function buildOpportunityData(0 results83890590670/937941942943944945740947948949950951952953954955956958959700962964965966967968969970971972973974988984432 X2 X19 ^2 usagesprivate function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess{...}Lusaeesprivate function getBusinessProcess(string $pipelineId): ?BusinessProcessf...}2 usagesprivate function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stageif (empty($stageId)) {return nulli$cacheKey = $businessProcess->getId() . ':'if (isset($this->cachedStages[$cacheKey])) {return $this->cachedStages[$cacheKey]:. $stageId;$stage = $this->crmEntityRepository->getPipelineStageByConditions($businessProcess,'crm_provider_id' => $stageId,iwoe"o swaderere UeruruNreif ($stage === null) {$this->importStages(null, $stageId);if ($stage === null) {фs->loggerntoospot meae does notexist→.tagel$this->cachedStages[$cacheKey] = $stage;recurn ostade.lusageprivate function resolveAmount(array $properties): ?stringf...}lusayeprivate function parseCleanDatetime(string $datetime): ?Carbonf...}E custom.log= laravel.logA SF [jiminny@localhost]C scratch_1jsonV Onboard.vue< Hs local liminnyalocalnostconsole EUl© CrmEntityRepository.php XA console [STAGING]class CrmEntityRepository281): Opportunity {...+fi crm_configurations [EU]A console [PROD]7467132 л5501332333334335336337339340341—544=343356357370F371377378-379=380382383384385396397403404405406407408-40941041142242274234227450=4362 usagespublic function upsertOpportunity(array $attributes, array $data): Opp/** @var ?Opportunity $opportunity */$opportunity = Opportunity: :withTrashed()->where($attributes)->firif ($opportunity === null) {$opportunity = Opportunity::create($data);felse {$opportunity->update($data);return Sopportunity;public function importstage(Configuration $configuration, string $objeLusagespublic function importBusinessProcess(Configuration $configuration,public function findAccountByExternalId(Configuration $configuration,/*** Find multiple accounts by their external CRM IDs* oocran contourcson ocontrourdcion* oocral arrausstrinos oeciirrovderros* Oreturn Collection<Account>s usagespublic function findAccountsByExternalIds(Configuration $configurationpublic function findContactByExternalId(Configuration $configuration,/*** Find multiple contacts by their external CRM IDS* @param Configuration Sconfiguration* Oparam array<string> $ermProviderIds* @return Collection<Contact>Tusdyepublic function findContactsByExternalIds(Configuration $configurationpubLic tunccion tindleadbyexcernalld conriguracion sconfiguracion, sch14 usagespublic function find0pportunityByExternalId(Configuration $configurati> 0Support Daily • in 3h 15 mAL AutomatedReportsCommandTestv100% C•8 • Fri 17 Apr 11:45:53CascadeAutomated Report Reti© Investigating HubSp+D ...buildOpportunityData( only sets stage id if $stage is non-null (line 893-895). But upsertOpportunity() always calls $opportunity→>update($data) with whatever is in $data.In update0pportunity() - Sstage can be null when $businessProcess is null (line 802):0 phpw$stage = $businessProcess ? $this→>resolveStage(...) : null;When $stage is null, stage_id is absent from $data entirely. But update($data) doesn't mean "keepexisting value" for absent keys — it just doesn't touch that column. So stage_id is preserved.but nere's the acrual osclllation source — resolvestage caches nuule• OpportunitySyncTrait.php:969$this->cachedStages [$cacheKey] = $stage; // caches null after importStages() is calledThis means:• Sync run 1 (new Service instance, empty cache): stage not in DB → importStages() called $stage= null → stage_id notsetin Sdata → updatel) doesh'ttouch stage_id → opportunity keepswhatever stage_id was set previously (or null )Sync run 2 (fresh instance, empty cache again): stage IS in DB now (imported in run 1) → resolves tostage 456 → stage_id = 456 written → OpportunityStageUpdated firesSync run 3: same as run 2... unless importStages() somehow re-runs and overwrites the stagestable witn alterentibsThe real oscillation: importStages() recreates stages with new DB IDsService.php:459-469— importStages() uses update0rCreate on stages:D php$stage = $this->config->stages ()→>update0rCreate(l'crm_provider_id' => $sl'id'],dalaaalnThis is fine — it reuses the same DB id . BUT resolveBusinessProcess() also calls importStages() whena plpeline is missing uine g20. ll a olpeline gets recrealed with a new BusinessProcess Db recora, the business_process_id → stage relationship could point to a different stage DB ID.Most likely actual cause: Two different sync paths are running concurrently or in rapid succession:1. SyncObjects scheduled job → processes the deal → writes stage_id = 4562. SvncOpportunity iob (triaaered by somethina else) → resolves via a different businessProcessinstance → writes stage id = 123lnese wo loos run noevencenty wiun no coorelnation. ooun calllino uoser Uoportuniv on the sameopportunity, alternating between two valid stage IDs that belong to different BusinessProcess recordspolntine lo tne same muospot olpellne - le. cupllcare businessprocess rows in the Db for the same chiprovider_id.Command docke• dockercontia =dinken1andeto r aronsaguratkon eecute( tean', fn(15a) =→ 1sa-deletebp-»erPHP LEOL;Run 2i+Ask anything (24L)+ <>Code Claude Sonnet 4.6Unhandled (Severwinasun lea( 4 spaces...
|
44387
|
|
44393
|
939
|
0
|
2026-04-17T08:46:13.449992+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776415573449_m1.jpg...
|
PhpStorm
|
faVsco.js – OpportunitySyncTrait.php
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
"podcast_audio_url"
New Line
Match Case
Words
Regex
Replace History
Replace...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#11894 on JY-18909-automated-reports-ask-jiminny, menu","depth":5,"help_text":"Pull request #11894 exists for current branch JY-18909-automated-reports-ask-jiminny, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AutomatedReportsCommandTest","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AutomatedReportsCommandTest'","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AutomatedReportsCommandTest'","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Show Replace Field","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Search History","depth":3,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"\"podcast_audio_url\"","depth":4,"value":"\"podcast_audio_url\"","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"New Line","depth":3,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Match Case","depth":3,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Words","depth":3,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Regex","depth":3,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Replace History","depth":3,"bounds":{"left":0.0,"top":0.0,"width":0.015277778,"height":0.024444444},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextField","text":"Replace","depth":4,"role_description":"text field","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-7638872701774903089
|
-8281753825854144188
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
"podcast_audio_url"
New Line
Match Case
Words
Regex
Replace History
Replace
FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelpmeet.google.com/xpx-omah-rkn• Support Daily • in 3 h 14 mIlian Kyuchukov (Presenting, annotating)100% C8 • Fri 17 Apr 11:46:126aws• 10.• 11• 12• 14• 16• 17.• 18• 191• 20.• 23.• 24• 25• 26• 2h• 29• з0• 31.• 32.• 33.• 34.• 35E CoudShellHistoryCloudWatch | eu-west-1CloudWatch | eu-west-1eu-west-1.console.aws.amazon.com/cloudwatch/nome/region=eu-west-10109sV2:logs-ins.ghtss%queryDetails3b-(end-0-start--86400-timelype-KELATIVE-1z-"UTc-unit- seconds-edntorstriniFinish update :[Option+5)© Ask Amazon Q©Curope Greland)CU.View_Only@765720199711CloudWatchLogs Insights _generalftimestamp2826-64-16T19:14:08.641220-4-760994%04.04h2026-04-16T19:14:03.64222026-04-16T19:14:08.64822026-04-16T19:14:08.64922026-04-16T19:14:08.64922826-04-16T19:14:08.64922026-04-16T19:14:03.65822026-04-16T19:14:08.65822026-04-16T19:14:08.65622026-04-16T19:14:08.66622026-04-16T19:14:08.67322026-04-16T19:14:08.67522026-04-16T19:14:08.67822826-04-16T19:14:08.63422026-04-16T19:14:03.68522026-04-16T19:14:08.68522026-04-16T19:14:08.63622026-04-16T19:14:08.68922026-04-16T19:14:08.69222026-04-16T19:14:08.69222026-04-16T19:14:08.69222026-04-16T19:14:08.7802Feedbackenessoge(2826-04-16 19:14:08] production.INFO: [HUbSpot] Syncing opportunities using strotegy: nebhookßatch ["correlation_id":*oe8616сс-1628-4054-0971-7284f1338Sfd*, "troce_(d":*099186f9-e768-443c-958c-39dff69e368_(2826-04-16 19:14:08] production. INFO: [HubspotWebhookBatchSyncStrategy) Deal botches processed ("config.(6":360, "totol_dispotched":0} ("correlation.id": "ое8e46сс-1628-4054-0971-7204f1338Sfd*, "troce_id":*-(2826-04-16 19:14:08] production.INF0:[ubSpot) Synced opportunities ("teon":3, "sync_count*:0, "total*:0, "lest_synced_(d":null) ("correlation,(d":*oeße46cc-1628-4054-0971-7204f1338Sfd*,"troce_(d" :*099106f-(2826-04-16 19:14:08] production.INF0:[SocialAccountService) Fetching token ("sociolAccountId":7880, "provider": "solesforce") ("correlation_id":"3192boef-ecбo-4904-0016-efS1de7bb4de", "troce_id":*c99106f9--(2826-04-16 19:14:03] production.INF0: [CrnOwnerResolver) Integration owner notched as CRM Onner ("crnuprovider": "solesforce", "cr_onner":3888, "teon,id" :73) ("correlation_id":*3192boef-ecбo-4904-0016-ef51_(2826-04-16 19:14:08] production. INFO:(EncryptedTokerMonoger) Genereting occess token. ("node": "legocy"} ("correlotion_id":*3192boef-ec6a-4904-0a16-ef51de7bb4de*, "troce_id":*699106f9-e768-463c-958c-39dff_(2826-04-16 19:14:08] production. INFO:[SociolAccountService) Token retrieved ("socialAccountld" :7830, "provider": "solesforce") ("correlation_(d": *3192boef-ec6o-4984-0016-ef51de7bb4de*, 'troce_(d*: *699106f9.(2826-04-16 19:14:08) production.INF0: [SyncObjects) After nenory usoge: ("'tean":"23350d51-9014-4e1d-b822-96f8738f3062", "usoge" :244679256, *reol_usoge":253755392, "pid":65687)(*correletion_\&":"œe$e46cc-16_(2826-04-16 19:14:08] production. INFO:[SyncObjects) Dispatching Salesforce fetch jobs ("teon": *914208oe-S05e-4b07-900c-600889efe4f", "cr.configuration_id": 54, "entity_types": ["leod", "occount", *opportuni t..(2826-04-16 19:14:08) production.INFO:(SyncObjects) Dispatched fetch job ("crn.configuration_id":54, "entity_type": "leod", "since":*2026-84-16T18:44:89-00:00*) ("correlation_(d':*3192boef-ec60-4904-0016-ef_(2826-04-16 19:14:08] production. INFO:(SyncObjects) Dispotched fetch job {"cr_configuration_id":54, "entity_type":"occount", "since": *2826-04-16T18:45:28+00:00*) ("correlation_ia":*3192boef-ec6о-4904-0016.[2826-04-16 19:14:08] production.INFO:[SyncObjects) Before nenory usoge: ("teon":"e04553f7-da1b-4dc2-99co-9685f818100b*, "usoge":144680333, "real_usoge":253755392, "pid":65637) ["correlotion_id":*011ca992-6.[2826-04-16 19:14:08) production. INF0: [SyncObjects) Dispotched fetch job ["crm_configuration_id":54, "entity_type": "opportunity", "since": "2026-04-16T18:45:19+00:00*) ("correlation_1d*: *3192boef-ec6a-4984--[2826-04-16 19:14:08) production. INFO:[SqsVisibilityControl] job visibility chong+d {"QueueÜe}*:™сгm-synс*,"ReсeÏptНondÌe*:"AQЄB7V05P4f1ÌeL+SenQ7сe)BA98HXT¡IVс™+hJP»Fh296€TNыGDCAсRнMeÑЖQVZ9VojKLoP+7oL9…[SociolAccountService) Fetching token ("sociolAccountld" :12390, "provider": "hubspot") ("correlation_id":"011c0992-6223-457c-91đb-9eScoß28f219", "troce_id" :*099106f9-e7-(SyncObjects) Dispatched fetch job ("crn.configuration_id":S4, "entity_type":"contoct", "since": *2026-84-16T18:45:01+80:00"} ("correlation_id": "3192boef-ec6o-4984-0016.[2026-04-16 19:14:83) production.INF0)Tmrmtectokentonooerwmencttnd otthtttoren.("node": "legocy") ("correlation_id":*011c0992-6223-457c-91db-9eScoß28f219", "troce_id*:*099186f9-€768-463c-958c-39dff_(2026-04-16 19:14:08] production.INF0:[CrOwnerResolver) Integration owner notched as CRM Onner ["crn,provider": "hubspot", "cr,ouner":7339, "teon_id":80) ("correlation_id":*a11ca992-6223-457c-91do-9eScoß2(2826-04-16 19:14:08] production. INF0:[SociolAccountService] Token retrieved ("sociolAccountId" :12390, "provider": "hubspot") ("correlation_id":*a11c0992-6223-457c-91db-9eScoß28f219", "troce_id" :*099106f9-e_(2026-04-16 19:14:08)(BatchSyncRedisService) Reset neto botch ("config_id":59, "object_type": "contoct", "event_type": "oll", "neta,key": "botch_sync_contoct:meto:59:ol1*, "reset_ot* :17763668487275-04-16 19:14:0%1 production[SyncObjects) All Salesforce fetch jobs dispatched ("teon": *914288oe-S0Se-4b07-9o0c-6000889efe4f*, "cr.configuration_id":54) ("cornelation,id": *3192boef-ecба-4904-oa.[SyncObjects) Dispatched fetch job ("cr_configuration_íd":54, "entity_type": "contoct_role", "since": *2826-84-16T18:45:07+00:00"} ("correlation_(d": *3192boef-ecбa-4904.[SyncObjects) After nenory usoge: ("teon": *9142030e-5b5e-4b07-9o8c-6000889efe4f*, "usoge" :140559552, "real_usoge" :182452224, "Pid": 59361) ("correletion_id':*3192boef-ec_xb-14-16 19:14:85) production.2004060-04-10 19:14:65 production.20012026-04-16 19:14:03) production.LN0(2026-04-16 19:14:08] production(2826-04-16 19:14:08) productionookbatchyynkstrategy) Deal batches processedcontig.id :5%, total_dispatched: correlationio: allcassz+0123-45/c-11c0-Heoollately, troce.1d: a(ubSpot) Synced opportunities ("teon": 80, "synk_count*:0, "total":8, "lest_synced_id":rull) ('correlation.te*: *611c0992-622};457c-9100-9e5coB28f219", "'troce_(d":*099106.[MebhookSyncBatchProcessor) Botch processing completed ("object_type":"contoct", "config_id":59, "total_dispetched" :10, "batches_dispatched" :1) ("correletion_id":*allca.[HubSpot) Syncing opportunities using strotegy: webhookBatch ("cornelation_id":*011c0992-6223-457c-91do-9eScoß28f219", "troce_id": *699106f9-e768-443c-958c-39dff69e368..("teon":*ed4S53f7-do1b-4dc2-99ca-9685f8181o8b*,"usoge":144747512, "'real_usoge":253755392, "pid":65687) ("correlotion_ia":*o11co992-62.0 2026, Amazon Web Services, Inc, or its affillatesCookde preferencesCtMsadhonllian KyuchukovNikolay NikolovVasil VasilevMihail MihaylLukas Kovalik11:46 AM | Daily - ProcessingLộ3...
|
44391
|
|
44394
|
940
|
0
|
2026-04-17T08:46:13.445178+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776415573445_m2.jpg...
|
PhpStorm
|
faVsco.js – OpportunitySyncTrait.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
"podcast_audio_url"...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.03046875,"top":0.017361112,"width":0.0453125,"height":0.022222223},"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#11894 on JY-18909-automated-reports-ask-jiminny, menu","depth":5,"bounds":{"left":0.07578125,"top":0.017361112,"width":0.14960937,"height":0.022222223},"help_text":"Pull request #11894 exists for current branch JY-18909-automated-reports-ask-jiminny, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.78515625,"top":0.017361112,"width":0.01328125,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AutomatedReportsCommandTest","depth":6,"bounds":{"left":0.803125,"top":0.017361112,"width":0.09765625,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AutomatedReportsCommandTest'","depth":6,"bounds":{"left":0.9007813,"top":0.017361112,"width":0.01328125,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AutomatedReportsCommandTest'","depth":6,"bounds":{"left":0.9140625,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9273437,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.96015626,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9734375,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9867188,"top":0.017361112,"width":0.013281226,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Show Replace Field","depth":4,"bounds":{"left":0.12382813,"top":0.22083333,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Search History","depth":3,"bounds":{"left":0.13867188,"top":0.22013889,"width":0.00859375,"height":0.015277778},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"\"podcast_audio_url\"","depth":4,"bounds":{"left":0.1515625,"top":0.22013889,"width":0.06367187,"height":0.013888889},"value":"\"podcast_audio_url\"","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-3833449677623645987
|
-8637832831181272252
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
"podcast_audio_url"
PhpStormFileEditViewNavigateCodeLaravelRefactorToolsWindowFV faVsco.s v#11894 on JY-18909-automated-reports-ask-iminny kHelpProjectv© PlaybookCategoryRepo© PlaybookRepository.php© PlaylistActivity Repositor©PlaylistRepository.php® PlaylistShareRepositoryQuestionRepository.php© RoleChangeEventRepos© RoleRepository.php© SearchRepository.php© SnapshotRepository.ph|© SocialAccountRepositor© StageRepository.php© SubscriptionSetRepositTaskRepository.php• TeamAiContextRepositc© TeamDomainsRepositor© TeamInsightsRepository© TeamRepository.php© ThemeRepository.php©) TimezoneRepository.ph© TopicRepository.php© TopicTriggerRepository© TrackRepository.php© TranscriptionModelLoce© TranscriptionRepository© TranscriptionSummaryF© UserRepository.php© VocabularyRepository.p> M7 Rulesv M ServicesD ActivityD AjReportsD AvatarCalendar[ ConferenceD CrmBullhorn_ closeD CopperCrmooiectsM DecorateActivitv• Dummy→ HelpersD Hubspot[J AccountSyncStra› D ActionsC ContactSyncStrat> UDTOWFieldsD JournalM MetadataOpportunitySync!> M7Pagination> D ProspectSearchs> D Redisv D ServiceTraits€ OpportunitySy& SyncCrmEntiti© SyncFieldsTra© AutomatedReportsService.php© SendReportJob.php© SendReportMailJob.php© ReportController.phpTokenBuilder.php• TeamSetupController.phppnp apl.onoFilesystem.php• Team.php© TrackProviderInstalledEvent.php© ActivityLogged.phpAutomatedReportsCallbackService.php© RequestGenerateAskJiminnyReportJob.php© RequestGenerateReportJob.php© SyncOpportunity.phpC Opportunity.phpC OpportunityUpdated.phpOpoonunitystadeupaaled.onoC EventServiceProvider.phpC CreateHeldActivityEvent.php€ OpportunitySyncTrait.php x© OpportunityPendingAiAnalysisAfterStageChanged.php© ImportOpportunityBatch.php© ImportBatchJobTrait.phpC AutomatedReport.php© RunOpportunityAiAnalysis.php€ HasAttributes.php© ProcessAiAutomationAnalysisResults.php© Service.phpAutomatedReportResult.php"podcast_audio_ur!"Cc W.*trait OpportunitySyncTraitprivate function buildOpportunityData(0 results83890590670/937941942943944945740947948949950951952953954955956958959700962964965966967968969970971972973974988984432 X2 X19 ^2 usagesprivate function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess{...}Lusaeesprivate function getBusinessProcess(string $pipelineId): ?BusinessProcessf...}2 usagesprivate function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stageif (empty($stageId)) {return nulli$cacheKey = $businessProcess->getId() . ':'if (isset($this->cachedStages[$cacheKey])) {return $this->cachedStages[$cacheKey]:. $stageId;$stage = $this->crmEntityRepository->getPipelineStageByConditions($businessProcess,'crm_provider_id' => $stageId,iwoe" o staderere UeruruNreif ($stage === null) {$this->importStages(null, $stageId);if ($stage === null) {фs->loggerntoospot meae does notexist→.tagel$this->cachedStages[$cacheKey] = $stage;recurn ostade.lusageprivate function resolveAmount(array $properties): ?stringf...}lusayeprivate function parseCleanDatetime(string $datetime): ?Carbonf...}E custom.log= laravel.logA SF [jiminny@localhost]C scratch_1jsonV Onboard.vue< Hs local liminnyalocalnostconsole EUl© CrmEntityRepository.php XA console [STAGING]class CrmEntityRepository281): Opportunity {...+fi crm_configurations [EU]A console [PROD]7467132 л5501332333334335336337339340341-44=343356357370F371377378-379=380382383384385396397403404405406407408-40941041142242274234227450=4362 usagespublic function upsertOpportunity(array $attributes, array $data): Opp/** @var ?Opportunity $opportunity */$opportunity = Opportunity: :withTrashed()->where($attributes)->firif ($opportunity === null) {$opportunity = Opportunity::create($data);felse {$opportunity->update($data);return Sopportunity;public function importstage(Configuration $configuration, string $objeLusagespublic function importBusinessProcess(Configuration $configuration,public function findAccountByExternalId(Configuration $configuration,/*** Find multiple accounts by their external CRM IDs* oocran contqurason ocontlourccion* oocral arrausstrnos oecirrovcerios* Oreturn Collection<Account>s usagespublic function findAccountsByExternalIds(Configuration $configurationpublic function findContactByExternalId(Configuration $configuration,/*** Find multiple contacts by their external CRM IDS* @param Configuration Sconfiguration* Oparam array<string> $ermProviderIds* @return Collection<Contact>Tusdyepublic function findContactsByExternalIds(Configuration $configurationpubLic tunccion tindleadbyexcernalld conriguracion sconfiguracion, sch14 usagespublic function find0pportunityByExternalId(Configuration $configurati> 0Support Daily • in 3h 14 mAL AutomatedReportsCommandTestv100% C•8 • Fri 17 Apr 11:46:13CascadeAutomated Report Retr© Investigating HubSp+D ...buildOpportunityData( only sets stage id if $stage is non-null (line 893-895). But upsertOpportunity() always calls $opportunity→>update($data) with whatever is in $data.In updateOpportunity()- Sstage can be null when $businessProcess is null (line 802):w0 php$stage = $businessProcess ? $this→>resolveStage(...) : null;When $stage is null, stage_id is absent from $data entirely. But update($data) doesn't mean "keepexisting value" for absent keys — it just doesn't touch that column. So stage_id is preserved.but nere's the acrual osclllation source — resolvestage caches nuula• OpportunitySyncTrait.php:969$this->cachedStages [$cacheKey] = $stage; // caches null after importStages() is calledThis means:Sync run 1 (new Service instance, empty cache): stage not in DB → importStages() called $stage= nul → stage 1d nor seuin scata → vocatel coeshrouch stace 1. → 0•o0nunilv keeoswhatever stage_id was set previously (or null )Sync run 2 (fresh instance, empty cache again): stage IS in DB now (imported in run 1) → resolves tostage 456 → stage_id = 456 written → OpportunityStageUpdated firesSync run 3: same as run 2... unless importStages() somehow re-runs and overwrites the stagestable witn alterentibsThe real oscillation: importStages() recreates stages with new DB IDsService.php:459-469— importStages() uses update0rCreate on stages:D php$stage = $this->config->stages ()→>update0rCreate(l'crm_provider_id' => $sl'id'],1, [...1);This is fine — it reuses the same DB id . BUT resolveBusinessProcess() also calls importStages() whena plpeline is missing uine g20. ll a olpeline gets recrealed with a new BusinessProcess Db recora, the business_process_id → stage relationship could point to a different stage DB ID.Most likely actual cause: Two different sync paths are running concurrently or in rapid succession:1. SyncObjects scheduled job → processes the deal → writes stage_id = 4562. SvncOpportunity iob (triagered by somethina else) → resolves via a different businessProcessinstance → writes stage id = 123lnese wo loos run noevencenty wiun no coorelnation. ooun calllino uoser Uoportuniv on the sameopportunity, alternating between two valid stage IDs that belong to different BusinessProcess recordspolntine lo tne same muospot olpellne - le. cupllcare businessprocess rows in the Db for the same chiprovider_id.Command docke• dockercontia =danken laodetolCm contaguratkon ereuts(" team', Fn(lsa) => 159-deletebp-»erPHP _EOL;Run 2i+Ask anything (24L)+ <>Code Claude Sonnet 4.6Unhandled (SeverWinasun leal( 4 spaces...
|
NULL
|
|
44532
|
NULL
|
0
|
2026-04-17T08:51:26.145566+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776415886145_m2.jpg...
|
PhpStorm
|
faVsco.js – console [EU]
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
"podcast_audio_url"
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
0 results
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Code changed:
Hide
Sync Changes
Hide This Notification
32
2
19
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\ServiceTraits;
use Carbon\Carbon;
use HubSpot\Client\Crm\Deals\Model\CollectionResponseAssociatedId;
use Jiminny\Exceptions\InvalidArgumentException;
use Jiminny\Models\Account;
use Exception;
use Jiminny\Component\DealInsights\Forecast\Forecast;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Exceptions\CrmException;
use Jiminny\Models\Opportunity;
use Illuminate\Support\Collection;
use Jiminny\Models\Stage;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Services\Crm\Hubspot\DealFieldsService;
use Jiminny\Services\Crm\Hubspot\OpportunitySyncStrategy\HubspotSingleSyncStrategy;
use Jiminny\Services\Crm\Hubspot\WebhookSyncBatchProcessor;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
/**
* Optimized sync methods for better performance
* These methods can be integrated into SyncCrmEntitiesTrait for significant performance gains
*/
trait OpportunitySyncTrait
{
private const int BATCH_SIZE = 100;
private const int BATCH_PROCESS_SIZE = 800;
protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
protected CrmEntityRepository $crmEntityRepository;
protected DealFieldsService $dealFieldsService;
private ?array $cachedClosedDealStages = null;
private array $cachedBusinessProcesses = [];
private array $cachedStages = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' .
$strategyName
);
$total = 0;
$lastId = null;
$buffer = [];
// HubspotWebhookBatchSyncStrategy returns empty generator, this is for other strategies
foreach ($syncStrategy->fetchOpportunities($parameters, $total, $lastId) as $hsOpportunity) {
$buffer[] = $hsOpportunity;
// process every 800 rows (fits < 1 000 association limit)
if (\count($buffer) >= self::BATCH_PROCESS_SIZE) {
$syncCount += $this->processOpportunityBatch($buffer);
$buffer = [];
}
}
// leftovers
if ($buffer) {
$syncCount += $this->processOpportunityBatch($buffer);
}
$reportedTotal += $total;
$lastSyncedId = $lastId;
}
} catch (\HubSpot\Client\Crm\Deals\ApiException | CrmException $e) {
$this->handleSyncException($e, $parameters);
}
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
]
);
return $reportedTotal;
}
private function handleSyncException(\Throwable $e, array $parameters): void
{
if (($parameters['since'] ?? null) instanceof Carbon) {
$parameters['since'] = $parameters['since']->toDateTimeString();
}
$parameters['config'] = $this->config->getId();
$this->logger->warning('[' . $this->getDisplayName() . '] Sync opportunities failed', [
'teamId' => $this->team->getUuid(),
'parameters' => $parameters,
'reason' => $e->getMessage(),
]);
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,
);
$parameters = [
'config' => $this->config,
'crm_id' => $crmId,
];
try {
if (! $strategy instanceof HubspotSingleSyncStrategy) {
throw new InvalidArgumentException('Strategy must by HubspotSingleSyncStrategy');
}
$hsOpportunity = $strategy->fetchOpportunity($parameters);
} catch (\HubSpot\Client\Crm\Deals\ApiException $e) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [
'teamId' => $this->team->getUuid(),
'crmId' => $crmId,
'reason' => $e->getMessage(),
]);
return null;
}
$hsOpportunity['associations'] = $this->convertDealAssociations($hsOpportunity['associations'] ?? []);
return $this->importOrUpdateOpportunity($hsOpportunity);
}
/**
* Process webhook-collected opportunity batches.
*
* Drains Redis sets containing company CRM IDs collected from webhook events
* and dispatches ImportOpportunityBatch jobs for batch processing.
*
* @return int Number of opportunity IDs dispatched to jobs
*/
public function batchSyncOpportunities(): int
{
$configId = $this->team->getCrmConfiguration()->getId();
return $this->batchProcessor->processBatchesForObjectType(
WebhookSyncBatchProcessor::OBJECT_TYPE_DEAL,
$configId
);
}
/**
* Import a batch of opportunities by their CRM IDs.
* Fetches opportunity data from HubSpot API and delegates to importOpportunityBatch().
*
* @param array<string> $crmIds HubSpot deal CRM IDs
*
* @return array{success: array, failed_ids: array, errors?: array<string, string>}
*/
public function importOpportunityBatchByIds(array $crmIds): array
{
$fields = $this->dealFieldsService->getFieldsForConfiguration($this->config);
$allDeals = [];
foreach (array_chunk($crmIds, self::BATCH_SIZE) as $chunk) {
$deals = $this->client->getOpportunitiesByIds($chunk, $fields);
foreach ($deals as $deal) {
$allDeals[] = $deal;
}
}
// IDs not returned by HubSpot are likely deleted or inaccessible deals.
// These are not failures — retrying won't bring them back.
$fetchedIds = array_map('strval', array_column($allDeals, 'id'));
$notFoundIds = array_values(array_diff(array_map('strval', $crmIds), $fetchedIds));
if (! empty($notFoundIds)) {
$this->logger->info('[' . $this->getDisplayName() . '] CRM IDs not found in HubSpot (likely deleted)', [
'teamId' => $this->team->getId(),
'notFoundCount' => \count($notFoundIds),
'notFoundIds' => $notFoundIds,
'requestedCount' => \count($crmIds),
'fetchedCount' => \count($allDeals),
]);
}
if (empty($allDeals)) {
return ['success' => [], 'failed_ids' => []];
}
return $this->importOpportunityBatch($allDeals);
}
private function getClosedDealStages(): array
{
if ($this->cachedClosedDealStages !== null) {
return $this->cachedClosedDealStages;
}
$stages = $this->crmEntityRepository->getOpportunityClosedStages($this->config);
$data = [
'lost' => [],
'won' => [],
];
foreach ($stages as $stage) {
if ($stage->probability == 0.00) {
$data['lost'][] = $stage->crm_provider_id;
}
if ($stage->probability == 100.00) {
$data['won'][] = $stage->crm_provider_id;
}
}
$this->cachedClosedDealStages = $data;
return $data;
}
/**
* Import deals into the database with pre-fetched associations.
*
* API calls here (getAssociationsData, getExistingOpportunityCrmIds) are NOT
* caught — if they throw, the exception propagates to ImportOpportunityBatch::handle()
* where Laravel retries the whole job with backoff. After all retries exhausted,
* failed() requeues all IDs to Redis.
*
* The per-deal loop catches exceptions individually. A deal can end up in three states:
* - success: imported/updated successfully
* - failed_ids: exception thrown (DB constraint violation, corrupt data, etc.)
* These are permanent issues — retrying won't fix them.
* - skipped (null): missing dependencies (no account, unknown pipeline/stage).
* This is acceptable — the deal cannot be imported until those exist.
*/
private function importOpportunityBatch(array $deals): array
{
$syncedOpportunities = [
'success' => [],
'failed_ids' => [],
];
$dealIds = array_column($deals, 'id');
// Shared association/existing-ID preparation is batch-level state. If it fails, rethrow so the
// queue job retries the whole batch and eventually requeues all deal IDs back to Redis.
try {
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$associationsData = $this->prepareAssociatedEntities($companyAssociations, $contactAssociations);
$existingCrmIds = $this->crmEntityRepository->getExistingOpportunityCrmIds(
$this->config,
array_map('strval', $dealIds)
);
$existingCrmIdSet = array_flip($existingCrmIds);
} catch (\Throwable $e) {
$this->logger->error('[' . $this->getDisplayName() . '] Failed to fetch associations or existing IDs', [
'teamId' => $this->team->getId(),
'dealCount' => count($dealIds),
'error' => $e->getMessage(),
]);
throw $e;
}
foreach ($deals as $deal) {
try {
$deal['associations'] = $this->prepareAssociationsForOpportunity(
$deal['id'],
$companyAssociations,
$contactAssociations,
$associationsData
);
$syncedOpportunity = $this->importOrUpdateOpportunity(
$deal,
isset($existingCrmIdSet[(string) $deal['id']])
);
if ($syncedOpportunity) {
$syncedOpportunities['success'][] = $syncedOpportunity;
}
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to import opportunity', [
'teamId' => $this->team->getId(),
'crmId' => $deal['id'],
'error' => $e->getMessage(),
]);
$syncedOpportunities['failed_ids'][] = $deal['id'];
$syncedOpportunities['errors'][$deal['id']] = $e->getMessage();
}
}
return $syncedOpportunities;
}
/**
* Prepare associated entities for opportunities with optimized batch processing
* Returns structured data with CRM ID to DB ID mappings for each opportunity
*/
private function prepareAssociatedEntities(array $companyAssociations, array $contactAssociations): array
{
// Step 1: Collect all unique company and contact IDs from associations
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
// Step 2: Batch sync missing entities and get CRM ID to DB ID mappings
$companyIdMappings = [];
$contactIdMappings = [];
if (! empty($allCompanyIds)) {
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
}
if (! empty($allContactIds)) {
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
}
return [
'company_id_mappings' => $companyIdMappings,
'contact_id_mappings' => $contactIdMappings,
];
}
/**
* Flatten association data to get unique IDs
*/
private function flattenAssociationIds(array $associations): array
{
$ids = [];
foreach ($associations as $dealAssociations) {
if (is_array($dealAssociations)) {
foreach ($dealAssociations as $id) {
$ids[$id] = true;
}
}
}
return array_keys($ids);
}
/**
* Batch sync missing accounts
*/
private function prepareAssociatedAccounts(array $companyIds): array
{
// Find which accounts already exist
$existingAccounts = $this->crmEntityRepository
->findAccountsByExternalIds($this->config, $companyIds);
$existingCompanyIds = $existingAccounts->pluck('crm_provider_id')->toArray();
$existingAccountsData = $existingAccounts->mapWithKeys(function ($account) {
return [$account->getCrmProviderId() => $account->getId()];
})->toArray();
$missingCompanyIds = array_diff($companyIds, $existingCompanyIds);
if (empty($missingCompanyIds)) {
return $existingAccountsData;
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing accounts', [
'teamId' => $this->team->getUuid(),
'total_companies' => count($companyIds),
'existing_companies' => count($existingCompanyIds),
'missing_companies' => count($missingCompanyIds),
]);
// we already have limit on opportunity ids count
// Initialize variable before try block
$syncedAccountsData = [];
try {
$syncedAccountsData = $this->batchSyncCrmObjects('companies', $missingCompanyIds);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing accounts', [
'size' => count($missingCompanyIds),
'error' => $e->getMessage(),
]);
$syncedAccountsData = [];
}
return $existingAccountsData + $syncedAccountsData;
}
/**
* Prepare associated contacts - find existing and sync missing ones
* Returns mapping of CRM ID to DB ID
*/
private function prepareAssociatedContacts(array $contactIds): array
{
// Find which contacts already exist
$existingContacts = $this->crmEntityRepository
->findContactsByExternalIds($this->config, $contactIds);
$existingContactIds = $existingContacts->pluck('crm_provider_id')->toArray();
// Create mapping for existing contacts
$existingContactsData = $existingContacts->mapWithKeys(function ($contact) {
return [$contact->getCrmProviderId() => $contact->getId()];
})->toArray();
$missingContactIds = array_diff($contactIds, $existingContactIds);
if (empty($missingContactIds)) {
return $existingContactsData;
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing contacts', [
'teamId' => $this->team->getUuid(),
'total_contacts' => count($contactIds),
'existing_contacts' => count($existingContactIds),
'missing_contacts' => count($missingContactIds),
]);
// Sync missing contacts using batch API
try {
$syncedContactsData = $this->batchSyncCrmObjects('contacts', $missingContactIds);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing contacts', [
'size' => count($missingContactIds),
'error' => $e->getMessage(),
]);
$syncedContactsData = [];
}
return $existingContactsData + $syncedContactsData;
}
private function batchSyncCrmObjects(string $objectType, array $crmIds): array
{
$syncObjects = [];
$crmObjectIds = array_values($crmIds);
foreach (array_chunk($crmObjectIds, self::BATCH_SIZE) as $chunk) {
try {
$objects = $objectType === 'companies' ?
$this->client->getCompaniesByIds($chunk, $this->getCompanyFields()) :
$this->client->getContactsByIds($chunk, $this->getContactFields());
foreach ($objects as $objectId => $objectData) {
$this->importCrmObject($objectType, (string) $objectId, $objectData, $syncObjects);
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch synced ' . $objectType, [
'requested_count' => count($chunk),
'synced_count' => count($objects),
]);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Batch ' . $objectType . ' sync failed', [
'ids' => $chunk,
'error' => $e->getMessage(),
]);
}
}
return $syncObjects;
}
private function importCrmObject(string $objectType, string $objectId, mixed $objectData, array &$syncObjects): void
{
try {
$object = $objectType === 'companies' ?
$this->importAccount($objectData) :
$this->importContact($objectData);
if ($object) {
$syncObjects[$object->getCrmProviderId()] = $object->getId();
}
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to import batch ' . $objectType, [
'id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
/**
* Prepare associations for a single opportunity
*
* The return value is an array with the following structure:
* [
* 'companies' => [
* $companyCrmId => $companyId,
* ...
* ],
* 'contacts' => [
* $contactCrmId => $contactId,
* ...
* ],
* 'account_id' => $accountId,
* ]
*/
private function prepareAssociationsForOpportunity(
string $oppCrmId,
array $companyAssociations,
array $contactAssociations,
array $associationsData
): array {
$associations = [
'companies' => [],
'contacts' => [],
'account_id' => null, // Primary account for opportunity
];
$oppCompanyIds = $companyAssociations[$oppCrmId] ?? [];
foreach ($oppCompanyIds as $companyCrmId) {
if (isset($associationsData['company_id_mappings'][$companyCrmId])) {
$associations['companies'][$companyCrmId] = $associationsData['company_id_mappings'][$companyCrmId];
// Set primary account (first company becomes primary account)
if ($associations['account_id'] === null) {
$associations['account_id'] = $associationsData['company_id_mappings'][$companyCrmId];
}
}
}
$oppContactIds = $contactAssociations[$oppCrmId] ?? [];
foreach ($oppContactIds as $contactCrmId) {
if (isset($associationsData['contact_id_mappings'][$contactCrmId])) {
$associations['contacts'][$contactCrmId] = $associationsData['contact_id_mappings'][$contactCrmId];
}
}
return $associations;
}
/**
* Update only associations for an opportunity
*/
private function updateOpportunityAssociations(Opportunity $opportunity, array $associations): void
{
// Update contact associations
$this->importOpportunityContacts($opportunity, $associations['contacts']);
// Update company (account) associations
$this->updateOpportunityAccount($opportunity, $associations['account_id']);
}
/**
* Remove all contact associations from an opportunity
*/
private function removeAllOpportunityContacts(Opportunity $opportunity): void
{
$currentCount = (int) $opportunity->contacts()->count();
if ($currentCount > 0) {
$opportunity->contacts()->detach();
$this->logger->info('[' . $this->getDisplayName() . '] Removed all contact associations', [
'opportunity_id' => $opportunity->getId(),
'removed_count' => $currentCount,
]);
}
}
private function updateOpportunityAccount(Opportunity $opportunity, ?int $accountId): void
{
if ($accountId === null) {
// No account ID provided - keep current account
return;
}
$currentAccountId = $opportunity->getAccountId();
// Only update if account has changed
if ($currentAccountId !== $accountId) {
$opportunity->account_id = $accountId;
$opportunity->save();
$this->logger->info('[' . $this->getDisplayName() . '] Updated opportunity account association', [
'opportunity_id' => $opportunity->getId(),
'old_account_id' => $currentAccountId,
'new_account_id' => $accountId,
]);
}
}
/**
* Find existing opportunities by external IDs (OPTIMIZED VERSION)
* Uses batch query for better performance
*/
private function findExistingOpportunities(array $crmIds): Collection
{
return $this->crmEntityRepository
->findOpportunitiesByExternalIds($this->config, $crmIds);
}
private function processOpportunityBatch(array $opportunities): int
{
$syncedOpportunities = $this->importOpportunityBatch($opportunities);
return count($syncedOpportunities['success'] ?? []);
}
/**
* Convert single deal associations from HubSpot format to internal format
* Handles both HubSpot SDK objects and array formats
*
* @param array $opportunityAssociations Raw associations from HubSpot API or pre-processed
*
* @return array Processed associations with DB IDs
*/
private function convertDealAssociations(array $opportunityAssociations): array
{
$associations = $this->initializeAssociationsStructure();
if (empty($opportunityAssociations)) {
return $associations;
}
$associationIds = $this->extractAssociationIds($opportunityAssociations);
$this->processCompanyAssociations($associationIds, $associations);
$this->processContactAssociations($associationIds, $associations);
return $associations;
}
private function initializeAssociationsStructure(): array
{
return [
'companies' => [],
'contacts' => [],
'account_id' => null, // Primary account for opportunity
];
}
private function extractAssociationIds(array $opportunityAssociations): array
{
$associationIds = [];
foreach ($opportunityAssociations as $type => $associationData) {
if (! empty($associationData)) {
$associationIds[$type] = $this->convertSingleDealAssociations($associationData);
}
}
return $associationIds;
}
private function processCompanyAssociations(array $associationIds, array &$associations): void
{
if (empty($associationIds['companies'])) {
return;
}
$companyId = $associationIds['companies'][0];
$account = $this->findOrSyncAccount($companyId);
if ($account instanceof Account) {
$associations['companies'][$companyId] = $account->getId();
$associations['account_id'] = $account->getId();
}
}
private function processContactAssociations(array $associationIds, array &$associations): void
{
if (empty($associationIds['contacts'])) {
return;
}
foreach ($associationIds['contacts'] as $contactId) {
$contact = $this->findOrSyncContact($contactId);
if ($contact instanceof Contact) {
$associations['contacts'][$contactId] = $contact->getId();
}
}
}
private function findOrSyncAccount(string $companyId): ?Account
{
$account = $this->crmEntityRepository->findAccountByExternalId($this->config, $companyId);
if (! $account instanceof Account) {
$account = $this->syncAccount($companyId);
}
return $account;
}
private function findOrSyncContact(string $contactId): ?Contact
{
$contact = $this->crmEntityRepository->findContactByExternalId($this->config, $contactId);
if (! $contact instanceof Contact) {
$contact = $this->syncContact($contactId);
}
return $contact;
}
private function convertSingleDealAssociations($opportunityAssociations = null): array
{
$associationData = [];
if ($opportunityAssociations === null) {
return $associationData;
}
// Handle array input (from extractAssociationIds)
if (is_array($opportunityAssociations)) {
return $opportunityAssociations;
}
// Handle CollectionResponseAssociatedId object
if ($opportunityAssociations instanceof CollectionResponseAssociatedId) {
foreach ($opportunityAssociations->getResults() as $association) {
$associationData[] = $association->getId();
}
}
return $associationData;
}
private function importOrUpdateOpportunity($crmData, ?bool $exists = null): ?Opportunity
{
if (empty($crmData['properties'])) {
return null;
}
$crmId = (string) $crmData['id'];
$properties = $crmData['properties'];
$associations = $crmData['associations'] ?? [];
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity($crmId, $properties, $associations);
} else {
return $this->createOpportunity($crmId, $properties, $associations);
}
}
/**
* Create new opportunity
*/
private function createOpportunity(string $crmId, array $properties, array $associations): ?Opportunity
{
$accountId = $this->resolveAccountId($associations);
if (! $accountId) {
return null;
}
$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);
if (! $businessProcess) {
return null;
}
$stage = $this->resolveStage($businessProcess, $properties['dealstage'] ?? null);
if (! $stage) {
return null;
}
$data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);
$attributes = [
'crm_configuration_id' => $this->config->getId(),
'crm_provider_id' => $crmId,
];
$values = array_merge($attributes, $data);
$opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);
$this->importExternalFieldData($properties, $opportunity->getId());
$this->importOpportunityContacts($opportunity, $associations['contacts']);
if ($opportunity->wasRecentlyCreated) {
MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());
}
return $opportunity;
}
/**
* Update existing opportunity
*/
private function updateOpportunity(string $crmId, array $properties, array $associations): Opportunity
{
$accountId = $this->resolveAccountId($associations);
$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);
$stage = $businessProcess ? $this->resolveStage($businessProcess, $properties['dealstage'] ?? null) : null;
$data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);
$attributes = [
'crm_configuration_id' => $this->config->getId(),
'crm_provider_id' => $crmId,
];
$values = array_merge($attributes, $data);
$opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);
$this->importExternalFieldData($properties, $opportunity->getId());
$this->updateOpportunityAssociations($opportunity, $associations);
return $opportunity;
}
private function resolveAccountId(array $associations): ?int
{
if (! empty($associations['accountId'])) {
return $associations['accountId'];
}
if (empty($associations)) {
return null;
}
// we can't resolve multiple account ids (currently SDK returns one company)
foreach ($associations['companies'] as $accountId) {
return $accountId;
}
return null;
}
private function buildOpportunityData(
array $properties,
?int $accountId,
?BusinessProcess $businessProcess,
?Stage $stage
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, (string) $ownerId);
}
$name = 'Unknown';
if (isset($properties['dealname'])) {
$name = mb_strimwidth($properties['dealname'], 0, 128);
}
$amount = $this->resolveAmount($properties);
$currency = $properties['deal_currency_code'] ?? null;
$closeDate = null;
if (! empty($properties['closedate'])) {
$closeDate = Carbon::parse($properties['closedate'])->format('Y-m-d');
}
$remotelyCreatedAt = null;
if (! empty($properties['createdate']) && strtotime($properties['createdate'])) {
$date = $this->parseCleanDatetime($properties['createdate']);
$remotelyCreatedAt = $date?->format('Y-m-d H:i:s');
}
$closedStages = $this->getClosedDealStages();
$isWon = in_array($properties['dealstage'], $closedStages['won']);
$isLost = in_array($properties['dealstage'], $closedStages['lost']);
$data = [
'team_id' => $this->team->getId(),
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => $name,
'value' => ! empty($amount) ? $amount : null,
'currency_code' => CurrencyFormatter::formatCode($currency),
'close_date' => $closeDate,
'is_closed' => $isWon || $isLost,
'is_won' => $isWon,
'remotely_created_at' => $remotelyCreatedAt,
'probability' => $this->resolveDealProbability($properties['hs_deal_stage_probability']),
'forecast_category' => $this->resolveForecastCategory($properties['hs_manual_forecast_category']),
];
if ($accountId) {
$data['account_id'] = $accountId;
}
if ($stage) {
$data['stage_id'] = $stage->id;
}
if ($businessProcess) {
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
if (isset($this->cachedBusinessProcesses[$pipelineId])) {
return $this->cachedBusinessProcesses[$pipelineId];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$pipelineId] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $businessProcess->getId() . ':' . $stageId;
if (isset($this->cachedStages[$cacheKey])) {
return $this->cachedStages[$cacheKey];
}
$stage = $this->crmEntityRepository->getPipelineStageByConditions(
$businessProcess,
[
'crm_provider_id' => $stageId,
'type' => Stage::TYPE_OPPORTUNITY,
]
);
if ($stage === null) {
$this->importStages(null, $stageId);
}
if ($stage === null) {
$this->logger->info('[HubSpot] Stage does not exist => ' . $stageId);
}
$this->cachedStages[$cacheKey] = $stage;
return $stage;
}
private function resolveAmount(array $properties): ?string
{
$amount = null;
if (! empty($properties['amount'])) {
$amount = str_replace(',', '', $properties['amount']);
}
if ($this->config->hasDefaultCurrencyFieldSet()) {
$valueFieldName = $this->config->getDefaultCurrencyField()->getCrmProviderId();
$amount = $properties[$valueFieldName] ?? $amount;
}
return $amount;
}
private function parseCleanDatetime(string $datetime): ?Carbon
{
// Treat pre-1980 values as invalid
$minValidDate = Carbon::parse('1980-01-01 00:00:00');
try {
$date = Carbon::parse($datetime);
if ($minValidDate->gt($date)) {
return null;
}
return $date;
} catch (Exception) {
return null; // On parse error, treat as null
}
}
private function resolveDealProbability(?string $stageProbability): int
{
if ($stageProbability === null) {
return 0;
}
$probability = (float) $stageProbability;
return $probability > 1 ? 0 : (int) ($probability * 100);
}
private function resolveForecastCategory(?string $forecastCategory): string
{
if (! $forecastCategory) {
return Forecast::FORECAST_CATEGORY_UNCATEGORIZED;
}
$forecastCategory = str_replace('_', ' ', $forecastCategory);
return ucwords(strtolower($forecastCategory));
}
private function importExternalFieldData(array $properties, int $opportunityId): void
{
$crmFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData($properties, $crmFields, $opportunityId);
}
private function importOpportunityContacts(Opportunity $opportunity, array $associations): void
{
// Handle empty or missing contact associations
if (empty($associations)) {
// Remove all existing contact associations if none provided
$this->removeAllOpportunityContacts($opportunity);
return;
}
// Use differential sync approach for better performance and accuracy
$this->syncOpportunityContactsDifferential($opportunity, $associations);
}
/**
* Sync opportunity contacts using differential approach
* This compares current vs new associations and only makes necessary changes
*/
private function syncOpportunityContactsDifferential(Opportunity $opportunity, array $contactAssociations): void
{
$currentContactCrmIds = $this->getCurrentContactCrmIds($opportunity);
$contactAssociationIds = array_keys($contactAssociations);
$contactsToAdd = array_diff($contactAssociationIds, $currentContactCrmIds);
$contactsToRemove = array_diff($currentContactCrmIds, $contactAssociationIds);
if (empty($contactsToAdd) && empty($contactsToRemove)) {
return;
}
$this->logContactAssociationChanges($opportunity, $currentContactCrmIds, $contactAssociations, $contactsToAdd, $contactsToRemove);
$this->removeContactAssociations($opportunity, $contactsToRemove);
$this->addContactAssociations($opportunity, $contactsToAdd, $contactAssociations);
}
private function getCurrentContactCrmIds(Opportunity $opportunity): array
{
return $opportunity->contacts()
->pluck('contacts.crm_provider_id')
->toArray();
}
private function logContactAssociationChanges(
Opportunity $opportunity,
array $currentContactCrmIds,
array $contactAssociations,
array $contactsToAdd,
array $contactsToRemove
): void {
$this->logger->info('[' . $this->getDisplayName() . '] Contact association changes', [
'opportunity_id' => $opportunity->getId(),
'current_contacts' => $currentContactCrmIds,
'new_contacts' => $contactAssociations,
'contacts_to_add' => $contactsToAdd,
'contacts_to_remove' => $contactsToRemove,
]);
}
private function removeContactAssociations(Opportunity $opportunity, array $contactsToRemove): void
{
if (empty($contactsToRemove)) {
return;
}
$contactsToDetach = $opportunity->contacts()
->whereIn('contacts.crm_provider_id', $contactsToRemove)
->pluck('contacts.id')
->toArray();
if (! empty($contactsToDetach)) {
$opportunity->contacts()->detach($contactsToDetach);
$this->logger->info('[' . $this->getDisplayName() . '] Removed contact associations', [
'opportunity_id' => $opportunity->getId(),
'removed_contact_crm_ids' => $contactsToRemove,
'removed_contact_count' => count($contactsToDetach),
]);
}
}
private function addContactAssociations(Opportunity $opportunity, array $contactsToAdd, array $contactAssociations): void
{
if (empty($contactsToAdd)) {
return;
}
$contactsAdded = [];
foreach ($contactsToAdd as $crmId) {
$id = $contactAssociations[$crmId];
if ($this->attachSingleContact($opportunity, (string) $crmId, $id)) {
$contactsAdded[] = $crmId;
}
}
$this->logAddedContacts($opportunity, $contactsAdded);
}
private function attachSingleContact(Opportunity $opportunity, string $crmId, int $id): bool
{
try {
$contact = $this->crmEntityRepository->findContactByConfigurationAndId($this->config, $id);
if (! $contact) {
return false;
}
return $this->performContactAttachment($opportunity, $contact, $crmId);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to add contact association', [
'opportunity_id' => $opportunity->getId(),
'contact_crm_id' => $crmId,
'error' => $e->getMessage(),
]);
return false;
}
}
private function performContactAttachment(Opportunity $opportunity, Contact $contact, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contact->getId(), [
'crm_provider_id' => $crmId,
]);
return true;
} catch (\Illuminate\Database\QueryException $e) {
if (str_contains($e->getMessage(), 'Duplicate entry')) {
$this->logger->info('[' . $this->getDisplayName() . '] Contact association already exists', [
'contact_id' => $contact->getId(),
'contact_crm_id' => $crmId,
'opportunity_id' => $opportunity->getId(),
]);
return false;
}
throw $e;
}
}
private function logAddedContacts(Opportunity $opportunity, array $contactsAdded): void
{
if (! empty($contactsAdded)) {
$this->logger->info('[' . $this->getDisplayName() . '] Added contact associations', [
'opportunity_id' => $opportunity->getId(),
'contacts_to_add_count' => count($contactsAdded),
'added_contact_crm_ids' => $contactsAdded,
'added_contacts_count' => count($contactsAdded),
]);
}
}
}
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...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.03046875,"top":0.017361112,"width":0.0453125,"height":0.022222223},"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#11894 on JY-18909-automated-reports-ask-jiminny, menu","depth":5,"bounds":{"left":0.07578125,"top":0.017361112,"width":0.14960937,"height":0.022222223},"help_text":"Pull request #11894 exists for current branch JY-18909-automated-reports-ask-jiminny, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.78515625,"top":0.017361112,"width":0.01328125,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AutomatedReportsCommandTest","depth":6,"bounds":{"left":0.803125,"top":0.017361112,"width":0.09765625,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AutomatedReportsCommandTest'","depth":6,"bounds":{"left":0.9007813,"top":0.017361112,"width":0.01328125,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AutomatedReportsCommandTest'","depth":6,"bounds":{"left":0.9140625,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9273437,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.96015626,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9734375,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9867188,"top":0.017361112,"width":0.013281226,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Show Replace Field","depth":4,"bounds":{"left":0.12382813,"top":0.24236111,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Search History","depth":3,"bounds":{"left":0.13867188,"top":0.24166666,"width":0.00859375,"height":0.015277778},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"\"podcast_audio_url\"","depth":4,"bounds":{"left":0.1515625,"top":0.24166666,"width":0.06367187,"height":0.013888889},"value":"\"podcast_audio_url\"","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"New Line","depth":3,"bounds":{"left":0.22578125,"top":0.24166666,"width":0.00859375,"height":0.015277778},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Match Case","depth":3,"bounds":{"left":0.2375,"top":0.24166666,"width":0.00859375,"height":0.015277778},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Words","depth":3,"bounds":{"left":0.24765626,"top":0.24166666,"width":0.00859375,"height":0.015277778},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Regex","depth":3,"bounds":{"left":0.2578125,"top":0.24166666,"width":0.00859375,"height":0.015277778},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Replace History","depth":3,"bounds":{"left":0.23320313,"top":1.0,"width":0.00859375,"height":0.0},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextField","text":"Replace","depth":4,"role_description":"text field","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"New Line","depth":3,"bounds":{"left":0.23320313,"top":1.0,"width":0.00859375,"height":0.0},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Preserve case","depth":3,"bounds":{"left":0.23320313,"top":1.0,"width":0.00859375,"height":0.0},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"0 results","depth":4,"bounds":{"left":0.27382812,"top":0.24097222,"width":0.030078124,"height":0.015277778},"role_description":"text"},{"role":"AXButton","text":"Previous Occurrence","depth":4,"bounds":{"left":0.30390626,"top":0.24027778,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Occurrence","depth":4,"bounds":{"left":0.3140625,"top":0.24027778,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Filter Search Results","depth":4,"bounds":{"left":0.32421875,"top":0.24027778,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open in Window, Multiple Cursors","depth":4,"bounds":{"left":0.334375,"top":0.24027778,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXLink","text":"Click to highlight","depth":4,"role_description":"link","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Close","depth":4,"bounds":{"left":0.39804688,"top":0.24027778,"width":0.01015625,"height":0.016666668},"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.23320313,"top":1.0,"width":0.049609374,"height":0.0},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.23320313,"top":1.0,"width":0.01015625,"height":0.0},"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.23320313,"top":1.0,"width":0.01015625,"height":0.0},"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.23320313,"top":1.0,"width":0.01015625,"height":0.0},"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"32","depth":4,"bounds":{"left":0.35703126,"top":0.2673611,"width":0.012109375,"height":0.013194445},"role_description":"text"},{"role":"AXStaticText","text":"2","depth":4,"bounds":{"left":0.37148437,"top":0.2673611,"width":0.009375,"height":0.013194445},"role_description":"text"},{"role":"AXStaticText","text":"19","depth":4,"bounds":{"left":0.38320312,"top":0.2673611,"width":0.011328125,"height":0.013194445},"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.39648438,"top":0.26597223,"width":0.00859375,"height":0.015972223},"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.4050781,"top":0.26597223,"width":0.008203125,"height":0.015972223},"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\\ServiceTraits;\n\nuse Carbon\\Carbon;\nuse HubSpot\\Client\\Crm\\Deals\\Model\\CollectionResponseAssociatedId;\nuse Jiminny\\Exceptions\\InvalidArgumentException;\nuse Jiminny\\Models\\Account;\nuse Exception;\nuse Jiminny\\Component\\DealInsights\\Forecast\\Forecast;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Models\\Opportunity;\nuse Illuminate\\Support\\Collection;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Services\\Crm\\Hubspot\\DealFieldsService;\nuse Jiminny\\Services\\Crm\\Hubspot\\OpportunitySyncStrategy\\HubspotSingleSyncStrategy;\nuse Jiminny\\Services\\Crm\\Hubspot\\WebhookSyncBatchProcessor;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\n\n/**\n * Optimized sync methods for better performance\n * These methods can be integrated into SyncCrmEntitiesTrait for significant performance gains\n */\ntrait OpportunitySyncTrait\n{\n private const int BATCH_SIZE = 100;\n private const int BATCH_PROCESS_SIZE = 800;\n\n protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n protected CrmEntityRepository $crmEntityRepository;\n protected DealFieldsService $dealFieldsService;\n\n private ?array $cachedClosedDealStages = null;\n private array $cachedBusinessProcesses = [];\n private array $cachedStages = [];\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n $parameters['config'] = $this->config;\n $syncCount = 0;\n $reportedTotal = 0;\n $lastSyncedId = [];\n\n try {\n foreach ($strategies as $strategyName => $syncStrategy) {\n $this->logger->info(\n '[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' .\n $strategyName\n );\n\n $total = 0;\n $lastId = null;\n $buffer = [];\n\n // HubspotWebhookBatchSyncStrategy returns empty generator, this is for other strategies\n foreach ($syncStrategy->fetchOpportunities($parameters, $total, $lastId) as $hsOpportunity) {\n $buffer[] = $hsOpportunity;\n\n // process every 800 rows (fits < 1 000 association limit)\n if (\\count($buffer) >= self::BATCH_PROCESS_SIZE) {\n $syncCount += $this->processOpportunityBatch($buffer);\n $buffer = [];\n }\n }\n\n // leftovers\n if ($buffer) {\n $syncCount += $this->processOpportunityBatch($buffer);\n }\n\n $reportedTotal += $total;\n $lastSyncedId = $lastId;\n }\n } catch (\\HubSpot\\Client\\Crm\\Deals\\ApiException | CrmException $e) {\n $this->handleSyncException($e, $parameters);\n }\n\n $this->logger->info(\n '[HubSpot] Synced opportunities',\n [\n 'team' => $this->team->getId(),\n 'sync_count' => $syncCount,\n 'total' => $reportedTotal,\n 'last_synced_id' => $lastSyncedId,\n ]\n );\n\n return $reportedTotal;\n }\n\n private function handleSyncException(\\Throwable $e, array $parameters): void\n {\n if (($parameters['since'] ?? null) instanceof Carbon) {\n $parameters['since'] = $parameters['since']->toDateTimeString();\n }\n $parameters['config'] = $this->config->getId();\n\n $this->logger->warning('[' . $this->getDisplayName() . '] Sync opportunities failed', [\n 'teamId' => $this->team->getUuid(),\n 'parameters' => $parameters,\n 'reason' => $e->getMessage(),\n ]);\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,\n );\n\n $parameters = [\n 'config' => $this->config,\n 'crm_id' => $crmId,\n ];\n\n try {\n if (! $strategy instanceof HubspotSingleSyncStrategy) {\n throw new InvalidArgumentException('Strategy must by HubspotSingleSyncStrategy');\n }\n\n $hsOpportunity = $strategy->fetchOpportunity($parameters);\n } catch (\\HubSpot\\Client\\Crm\\Deals\\ApiException $e) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [\n 'teamId' => $this->team->getUuid(),\n 'crmId' => $crmId,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n $hsOpportunity['associations'] = $this->convertDealAssociations($hsOpportunity['associations'] ?? []);\n\n return $this->importOrUpdateOpportunity($hsOpportunity);\n }\n\n /**\n * Process webhook-collected opportunity batches.\n *\n * Drains Redis sets containing company CRM IDs collected from webhook events\n * and dispatches ImportOpportunityBatch jobs for batch processing.\n *\n * @return int Number of opportunity IDs dispatched to jobs\n */\n public function batchSyncOpportunities(): int\n {\n $configId = $this->team->getCrmConfiguration()->getId();\n\n return $this->batchProcessor->processBatchesForObjectType(\n WebhookSyncBatchProcessor::OBJECT_TYPE_DEAL,\n $configId\n );\n }\n\n /**\n * Import a batch of opportunities by their CRM IDs.\n * Fetches opportunity data from HubSpot API and delegates to importOpportunityBatch().\n *\n * @param array<string> $crmIds HubSpot deal CRM IDs\n *\n * @return array{success: array, failed_ids: array, errors?: array<string, string>}\n */\n public function importOpportunityBatchByIds(array $crmIds): array\n {\n $fields = $this->dealFieldsService->getFieldsForConfiguration($this->config);\n\n $allDeals = [];\n foreach (array_chunk($crmIds, self::BATCH_SIZE) as $chunk) {\n $deals = $this->client->getOpportunitiesByIds($chunk, $fields);\n foreach ($deals as $deal) {\n $allDeals[] = $deal;\n }\n }\n\n // IDs not returned by HubSpot are likely deleted or inaccessible deals.\n // These are not failures — retrying won't bring them back.\n $fetchedIds = array_map('strval', array_column($allDeals, 'id'));\n $notFoundIds = array_values(array_diff(array_map('strval', $crmIds), $fetchedIds));\n\n if (! empty($notFoundIds)) {\n $this->logger->info('[' . $this->getDisplayName() . '] CRM IDs not found in HubSpot (likely deleted)', [\n 'teamId' => $this->team->getId(),\n 'notFoundCount' => \\count($notFoundIds),\n 'notFoundIds' => $notFoundIds,\n 'requestedCount' => \\count($crmIds),\n 'fetchedCount' => \\count($allDeals),\n ]);\n }\n\n if (empty($allDeals)) {\n return ['success' => [], 'failed_ids' => []];\n }\n\n return $this->importOpportunityBatch($allDeals);\n }\n\n private function getClosedDealStages(): array\n {\n if ($this->cachedClosedDealStages !== null) {\n return $this->cachedClosedDealStages;\n }\n\n $stages = $this->crmEntityRepository->getOpportunityClosedStages($this->config);\n $data = [\n 'lost' => [],\n 'won' => [],\n ];\n\n foreach ($stages as $stage) {\n if ($stage->probability == 0.00) {\n $data['lost'][] = $stage->crm_provider_id;\n }\n if ($stage->probability == 100.00) {\n $data['won'][] = $stage->crm_provider_id;\n }\n }\n\n $this->cachedClosedDealStages = $data;\n\n return $data;\n }\n\n /**\n * Import deals into the database with pre-fetched associations.\n *\n * API calls here (getAssociationsData, getExistingOpportunityCrmIds) are NOT\n * caught — if they throw, the exception propagates to ImportOpportunityBatch::handle()\n * where Laravel retries the whole job with backoff. After all retries exhausted,\n * failed() requeues all IDs to Redis.\n *\n * The per-deal loop catches exceptions individually. A deal can end up in three states:\n * - success: imported/updated successfully\n * - failed_ids: exception thrown (DB constraint violation, corrupt data, etc.)\n * These are permanent issues — retrying won't fix them.\n * - skipped (null): missing dependencies (no account, unknown pipeline/stage).\n * This is acceptable — the deal cannot be imported until those exist.\n */\n private function importOpportunityBatch(array $deals): array\n {\n $syncedOpportunities = [\n 'success' => [],\n 'failed_ids' => [],\n ];\n $dealIds = array_column($deals, 'id');\n\n // Shared association/existing-ID preparation is batch-level state. If it fails, rethrow so the\n // queue job retries the whole batch and eventually requeues all deal IDs back to Redis.\n try {\n $companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');\n $contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');\n\n $associationsData = $this->prepareAssociatedEntities($companyAssociations, $contactAssociations);\n\n $existingCrmIds = $this->crmEntityRepository->getExistingOpportunityCrmIds(\n $this->config,\n array_map('strval', $dealIds)\n );\n $existingCrmIdSet = array_flip($existingCrmIds);\n } catch (\\Throwable $e) {\n $this->logger->error('[' . $this->getDisplayName() . '] Failed to fetch associations or existing IDs', [\n 'teamId' => $this->team->getId(),\n 'dealCount' => count($dealIds),\n 'error' => $e->getMessage(),\n ]);\n\n throw $e;\n }\n\n foreach ($deals as $deal) {\n try {\n $deal['associations'] = $this->prepareAssociationsForOpportunity(\n $deal['id'],\n $companyAssociations,\n $contactAssociations,\n $associationsData\n );\n\n $syncedOpportunity = $this->importOrUpdateOpportunity(\n $deal,\n isset($existingCrmIdSet[(string) $deal['id']])\n );\n if ($syncedOpportunity) {\n $syncedOpportunities['success'][] = $syncedOpportunity;\n }\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to import opportunity', [\n 'teamId' => $this->team->getId(),\n 'crmId' => $deal['id'],\n 'error' => $e->getMessage(),\n ]);\n $syncedOpportunities['failed_ids'][] = $deal['id'];\n $syncedOpportunities['errors'][$deal['id']] = $e->getMessage();\n }\n }\n\n return $syncedOpportunities;\n }\n\n /**\n * Prepare associated entities for opportunities with optimized batch processing\n * Returns structured data with CRM ID to DB ID mappings for each opportunity\n */\n private function prepareAssociatedEntities(array $companyAssociations, array $contactAssociations): array\n {\n // Step 1: Collect all unique company and contact IDs from associations\n $allCompanyIds = $this->flattenAssociationIds($companyAssociations);\n $allContactIds = $this->flattenAssociationIds($contactAssociations);\n\n // Step 2: Batch sync missing entities and get CRM ID to DB ID mappings\n $companyIdMappings = [];\n $contactIdMappings = [];\n\n if (! empty($allCompanyIds)) {\n $companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);\n }\n\n if (! empty($allContactIds)) {\n $contactIdMappings = $this->prepareAssociatedContacts($allContactIds);\n }\n\n return [\n 'company_id_mappings' => $companyIdMappings,\n 'contact_id_mappings' => $contactIdMappings,\n ];\n }\n\n /**\n * Flatten association data to get unique IDs\n */\n private function flattenAssociationIds(array $associations): array\n {\n $ids = [];\n foreach ($associations as $dealAssociations) {\n if (is_array($dealAssociations)) {\n foreach ($dealAssociations as $id) {\n $ids[$id] = true;\n }\n }\n }\n\n return array_keys($ids);\n }\n\n /**\n * Batch sync missing accounts\n */\n private function prepareAssociatedAccounts(array $companyIds): array\n {\n // Find which accounts already exist\n $existingAccounts = $this->crmEntityRepository\n ->findAccountsByExternalIds($this->config, $companyIds);\n\n $existingCompanyIds = $existingAccounts->pluck('crm_provider_id')->toArray();\n\n $existingAccountsData = $existingAccounts->mapWithKeys(function ($account) {\n return [$account->getCrmProviderId() => $account->getId()];\n })->toArray();\n\n $missingCompanyIds = array_diff($companyIds, $existingCompanyIds);\n\n if (empty($missingCompanyIds)) {\n return $existingAccountsData;\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing accounts', [\n 'teamId' => $this->team->getUuid(),\n 'total_companies' => count($companyIds),\n 'existing_companies' => count($existingCompanyIds),\n 'missing_companies' => count($missingCompanyIds),\n ]);\n\n // we already have limit on opportunity ids count\n // Initialize variable before try block\n $syncedAccountsData = [];\n\n try {\n $syncedAccountsData = $this->batchSyncCrmObjects('companies', $missingCompanyIds);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing accounts', [\n 'size' => count($missingCompanyIds),\n 'error' => $e->getMessage(),\n ]);\n $syncedAccountsData = [];\n }\n\n return $existingAccountsData + $syncedAccountsData;\n }\n\n /**\n * Prepare associated contacts - find existing and sync missing ones\n * Returns mapping of CRM ID to DB ID\n */\n private function prepareAssociatedContacts(array $contactIds): array\n {\n // Find which contacts already exist\n $existingContacts = $this->crmEntityRepository\n ->findContactsByExternalIds($this->config, $contactIds);\n\n $existingContactIds = $existingContacts->pluck('crm_provider_id')->toArray();\n\n // Create mapping for existing contacts\n $existingContactsData = $existingContacts->mapWithKeys(function ($contact) {\n return [$contact->getCrmProviderId() => $contact->getId()];\n })->toArray();\n\n $missingContactIds = array_diff($contactIds, $existingContactIds);\n\n if (empty($missingContactIds)) {\n return $existingContactsData;\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing contacts', [\n 'teamId' => $this->team->getUuid(),\n 'total_contacts' => count($contactIds),\n 'existing_contacts' => count($existingContactIds),\n 'missing_contacts' => count($missingContactIds),\n ]);\n\n // Sync missing contacts using batch API\n try {\n $syncedContactsData = $this->batchSyncCrmObjects('contacts', $missingContactIds);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing contacts', [\n 'size' => count($missingContactIds),\n 'error' => $e->getMessage(),\n ]);\n $syncedContactsData = [];\n }\n\n return $existingContactsData + $syncedContactsData;\n }\n\n private function batchSyncCrmObjects(string $objectType, array $crmIds): array\n {\n $syncObjects = [];\n $crmObjectIds = array_values($crmIds);\n\n foreach (array_chunk($crmObjectIds, self::BATCH_SIZE) as $chunk) {\n try {\n $objects = $objectType === 'companies' ?\n $this->client->getCompaniesByIds($chunk, $this->getCompanyFields()) :\n $this->client->getContactsByIds($chunk, $this->getContactFields());\n\n foreach ($objects as $objectId => $objectData) {\n $this->importCrmObject($objectType, (string) $objectId, $objectData, $syncObjects);\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch synced ' . $objectType, [\n 'requested_count' => count($chunk),\n 'synced_count' => count($objects),\n ]);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Batch ' . $objectType . ' sync failed', [\n 'ids' => $chunk,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n return $syncObjects;\n }\n\n private function importCrmObject(string $objectType, string $objectId, mixed $objectData, array &$syncObjects): void\n {\n try {\n $object = $objectType === 'companies' ?\n $this->importAccount($objectData) :\n $this->importContact($objectData);\n\n if ($object) {\n $syncObjects[$object->getCrmProviderId()] = $object->getId();\n }\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to import batch ' . $objectType, [\n 'id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n /**\n * Prepare associations for a single opportunity\n *\n * The return value is an array with the following structure:\n * [\n * 'companies' => [\n * $companyCrmId => $companyId,\n * ...\n * ],\n * 'contacts' => [\n * $contactCrmId => $contactId,\n * ...\n * ],\n * 'account_id' => $accountId,\n * ]\n */\n private function prepareAssociationsForOpportunity(\n string $oppCrmId,\n array $companyAssociations,\n array $contactAssociations,\n array $associationsData\n ): array {\n $associations = [\n 'companies' => [],\n 'contacts' => [],\n 'account_id' => null, // Primary account for opportunity\n ];\n\n $oppCompanyIds = $companyAssociations[$oppCrmId] ?? [];\n foreach ($oppCompanyIds as $companyCrmId) {\n if (isset($associationsData['company_id_mappings'][$companyCrmId])) {\n $associations['companies'][$companyCrmId] = $associationsData['company_id_mappings'][$companyCrmId];\n\n // Set primary account (first company becomes primary account)\n if ($associations['account_id'] === null) {\n $associations['account_id'] = $associationsData['company_id_mappings'][$companyCrmId];\n }\n }\n }\n\n $oppContactIds = $contactAssociations[$oppCrmId] ?? [];\n foreach ($oppContactIds as $contactCrmId) {\n if (isset($associationsData['contact_id_mappings'][$contactCrmId])) {\n $associations['contacts'][$contactCrmId] = $associationsData['contact_id_mappings'][$contactCrmId];\n }\n }\n\n return $associations;\n }\n\n /**\n * Update only associations for an opportunity\n */\n private function updateOpportunityAssociations(Opportunity $opportunity, array $associations): void\n {\n // Update contact associations\n $this->importOpportunityContacts($opportunity, $associations['contacts']);\n\n // Update company (account) associations\n $this->updateOpportunityAccount($opportunity, $associations['account_id']);\n }\n\n /**\n * Remove all contact associations from an opportunity\n */\n private function removeAllOpportunityContacts(Opportunity $opportunity): void\n {\n $currentCount = (int) $opportunity->contacts()->count();\n\n if ($currentCount > 0) {\n $opportunity->contacts()->detach();\n\n $this->logger->info('[' . $this->getDisplayName() . '] Removed all contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'removed_count' => $currentCount,\n ]);\n }\n }\n\n private function updateOpportunityAccount(Opportunity $opportunity, ?int $accountId): void\n {\n if ($accountId === null) {\n // No account ID provided - keep current account\n return;\n }\n\n $currentAccountId = $opportunity->getAccountId();\n\n // Only update if account has changed\n if ($currentAccountId !== $accountId) {\n $opportunity->account_id = $accountId;\n $opportunity->save();\n\n $this->logger->info('[' . $this->getDisplayName() . '] Updated opportunity account association', [\n 'opportunity_id' => $opportunity->getId(),\n 'old_account_id' => $currentAccountId,\n 'new_account_id' => $accountId,\n ]);\n }\n }\n\n /**\n * Find existing opportunities by external IDs (OPTIMIZED VERSION)\n * Uses batch query for better performance\n */\n private function findExistingOpportunities(array $crmIds): Collection\n {\n return $this->crmEntityRepository\n ->findOpportunitiesByExternalIds($this->config, $crmIds);\n }\n\n private function processOpportunityBatch(array $opportunities): int\n {\n $syncedOpportunities = $this->importOpportunityBatch($opportunities);\n\n return count($syncedOpportunities['success'] ?? []);\n }\n\n /**\n * Convert single deal associations from HubSpot format to internal format\n * Handles both HubSpot SDK objects and array formats\n *\n * @param array $opportunityAssociations Raw associations from HubSpot API or pre-processed\n *\n * @return array Processed associations with DB IDs\n */\n private function convertDealAssociations(array $opportunityAssociations): array\n {\n $associations = $this->initializeAssociationsStructure();\n\n if (empty($opportunityAssociations)) {\n return $associations;\n }\n\n $associationIds = $this->extractAssociationIds($opportunityAssociations);\n\n $this->processCompanyAssociations($associationIds, $associations);\n $this->processContactAssociations($associationIds, $associations);\n\n return $associations;\n }\n\n private function initializeAssociationsStructure(): array\n {\n return [\n 'companies' => [],\n 'contacts' => [],\n 'account_id' => null, // Primary account for opportunity\n ];\n }\n\n private function extractAssociationIds(array $opportunityAssociations): array\n {\n $associationIds = [];\n\n foreach ($opportunityAssociations as $type => $associationData) {\n if (! empty($associationData)) {\n $associationIds[$type] = $this->convertSingleDealAssociations($associationData);\n }\n }\n\n return $associationIds;\n }\n\n private function processCompanyAssociations(array $associationIds, array &$associations): void\n {\n if (empty($associationIds['companies'])) {\n return;\n }\n\n $companyId = $associationIds['companies'][0];\n $account = $this->findOrSyncAccount($companyId);\n\n if ($account instanceof Account) {\n $associations['companies'][$companyId] = $account->getId();\n $associations['account_id'] = $account->getId();\n }\n }\n\n private function processContactAssociations(array $associationIds, array &$associations): void\n {\n if (empty($associationIds['contacts'])) {\n return;\n }\n\n foreach ($associationIds['contacts'] as $contactId) {\n $contact = $this->findOrSyncContact($contactId);\n\n if ($contact instanceof Contact) {\n $associations['contacts'][$contactId] = $contact->getId();\n }\n }\n }\n\n private function findOrSyncAccount(string $companyId): ?Account\n {\n $account = $this->crmEntityRepository->findAccountByExternalId($this->config, $companyId);\n\n if (! $account instanceof Account) {\n $account = $this->syncAccount($companyId);\n }\n\n return $account;\n }\n\n private function findOrSyncContact(string $contactId): ?Contact\n {\n $contact = $this->crmEntityRepository->findContactByExternalId($this->config, $contactId);\n\n if (! $contact instanceof Contact) {\n $contact = $this->syncContact($contactId);\n }\n\n return $contact;\n }\n\n private function convertSingleDealAssociations($opportunityAssociations = null): array\n {\n $associationData = [];\n\n if ($opportunityAssociations === null) {\n return $associationData;\n }\n\n // Handle array input (from extractAssociationIds)\n if (is_array($opportunityAssociations)) {\n return $opportunityAssociations;\n }\n\n // Handle CollectionResponseAssociatedId object\n if ($opportunityAssociations instanceof CollectionResponseAssociatedId) {\n foreach ($opportunityAssociations->getResults() as $association) {\n $associationData[] = $association->getId();\n }\n }\n\n return $associationData;\n }\n\n private function importOrUpdateOpportunity($crmData, ?bool $exists = null): ?Opportunity\n {\n if (empty($crmData['properties'])) {\n return null;\n }\n\n $crmId = (string) $crmData['id'];\n $properties = $crmData['properties'];\n $associations = $crmData['associations'] ?? [];\n\n $opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(\n $this->config,\n $crmId\n );\n\n if ($opportunityExists) {\n return $this->updateOpportunity($crmId, $properties, $associations);\n } else {\n return $this->createOpportunity($crmId, $properties, $associations);\n }\n }\n\n /**\n * Create new opportunity\n */\n private function createOpportunity(string $crmId, array $properties, array $associations): ?Opportunity\n {\n $accountId = $this->resolveAccountId($associations);\n if (! $accountId) {\n return null;\n }\n\n $businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);\n if (! $businessProcess) {\n return null;\n }\n\n $stage = $this->resolveStage($businessProcess, $properties['dealstage'] ?? null);\n if (! $stage) {\n return null;\n }\n\n $data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);\n\n $attributes = [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmId,\n ];\n\n $values = array_merge($attributes, $data);\n\n $opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);\n\n $this->importExternalFieldData($properties, $opportunity->getId());\n $this->importOpportunityContacts($opportunity, $associations['contacts']);\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n }\n\n /**\n * Update existing opportunity\n */\n private function updateOpportunity(string $crmId, array $properties, array $associations): Opportunity\n {\n $accountId = $this->resolveAccountId($associations);\n $businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);\n $stage = $businessProcess ? $this->resolveStage($businessProcess, $properties['dealstage'] ?? null) : null;\n\n $data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);\n\n $attributes = [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmId,\n ];\n\n $values = array_merge($attributes, $data);\n $opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);\n\n $this->importExternalFieldData($properties, $opportunity->getId());\n $this->updateOpportunityAssociations($opportunity, $associations);\n\n return $opportunity;\n }\n\n private function resolveAccountId(array $associations): ?int\n {\n if (! empty($associations['accountId'])) {\n return $associations['accountId'];\n }\n\n if (empty($associations)) {\n return null;\n }\n\n // we can't resolve multiple account ids (currently SDK returns one company)\n foreach ($associations['companies'] as $accountId) {\n return $accountId;\n }\n\n return null;\n }\n\n private function buildOpportunityData(\n array $properties,\n ?int $accountId,\n ?BusinessProcess $businessProcess,\n ?Stage $stage\n ): array {\n $ownerId = null;\n $profile = null;\n if (! empty($properties['hubspot_owner_id'])) {\n $ownerId = $properties['hubspot_owner_id'];\n $profile = $this->crmEntityRepository->findProfileByExternalId($this->config, (string) $ownerId);\n }\n\n $name = 'Unknown';\n if (isset($properties['dealname'])) {\n $name = mb_strimwidth($properties['dealname'], 0, 128);\n }\n\n $amount = $this->resolveAmount($properties);\n $currency = $properties['deal_currency_code'] ?? null;\n\n $closeDate = null;\n if (! empty($properties['closedate'])) {\n $closeDate = Carbon::parse($properties['closedate'])->format('Y-m-d');\n }\n\n $remotelyCreatedAt = null;\n if (! empty($properties['createdate']) && strtotime($properties['createdate'])) {\n $date = $this->parseCleanDatetime($properties['createdate']);\n $remotelyCreatedAt = $date?->format('Y-m-d H:i:s');\n }\n\n $closedStages = $this->getClosedDealStages();\n $isWon = in_array($properties['dealstage'], $closedStages['won']);\n $isLost = in_array($properties['dealstage'], $closedStages['lost']);\n\n $data = [\n 'team_id' => $this->team->getId(),\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => $name,\n 'value' => ! empty($amount) ? $amount : null,\n 'currency_code' => CurrencyFormatter::formatCode($currency),\n 'close_date' => $closeDate,\n 'is_closed' => $isWon || $isLost,\n 'is_won' => $isWon,\n 'remotely_created_at' => $remotelyCreatedAt,\n 'probability' => $this->resolveDealProbability($properties['hs_deal_stage_probability']),\n 'forecast_category' => $this->resolveForecastCategory($properties['hs_manual_forecast_category']),\n ];\n\n if ($accountId) {\n $data['account_id'] = $accountId;\n }\n\n if ($stage) {\n $data['stage_id'] = $stage->id;\n }\n\n if ($businessProcess) {\n $recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);\n if ($recordType) {\n $data['record_type_id'] = $recordType->id;\n }\n }\n\n return $data;\n }\n\n private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess\n {\n if ($pipelineId === null) {\n return null;\n }\n\n if (isset($this->cachedBusinessProcesses[$pipelineId])) {\n return $this->cachedBusinessProcesses[$pipelineId];\n }\n\n $businessProcess = $this->getBusinessProcess($pipelineId);\n\n if (! $businessProcess instanceof BusinessProcess) {\n $this->importStages();\n $businessProcess = $this->getBusinessProcess($pipelineId);\n }\n\n if (! $businessProcess instanceof BusinessProcess) {\n $this->logger->info(\n '[HubSpot] Deal is not attached to a pipeline',\n [\n 'pipeline' => $pipelineId]\n );\n }\n\n $this->cachedBusinessProcesses[$pipelineId] = $businessProcess;\n\n return $businessProcess;\n }\n\n private function getBusinessProcess(string $pipelineId): ?BusinessProcess\n {\n return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);\n }\n\n private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage\n {\n if (empty($stageId)) {\n return null;\n }\n\n $cacheKey = $businessProcess->getId() . ':' . $stageId;\n if (isset($this->cachedStages[$cacheKey])) {\n return $this->cachedStages[$cacheKey];\n }\n\n $stage = $this->crmEntityRepository->getPipelineStageByConditions(\n $businessProcess,\n [\n 'crm_provider_id' => $stageId,\n 'type' => Stage::TYPE_OPPORTUNITY,\n ]\n );\n\n if ($stage === null) {\n $this->importStages(null, $stageId);\n }\n\n if ($stage === null) {\n $this->logger->info('[HubSpot] Stage does not exist => ' . $stageId);\n }\n\n $this->cachedStages[$cacheKey] = $stage;\n\n return $stage;\n }\n\n private function resolveAmount(array $properties): ?string\n {\n $amount = null;\n if (! empty($properties['amount'])) {\n $amount = str_replace(',', '', $properties['amount']);\n }\n\n if ($this->config->hasDefaultCurrencyFieldSet()) {\n $valueFieldName = $this->config->getDefaultCurrencyField()->getCrmProviderId();\n $amount = $properties[$valueFieldName] ?? $amount;\n }\n\n return $amount;\n }\n\n private function parseCleanDatetime(string $datetime): ?Carbon\n {\n // Treat pre-1980 values as invalid\n $minValidDate = Carbon::parse('1980-01-01 00:00:00');\n\n try {\n $date = Carbon::parse($datetime);\n\n if ($minValidDate->gt($date)) {\n return null;\n }\n\n return $date;\n } catch (Exception) {\n return null; // On parse error, treat as null\n }\n }\n\n private function resolveDealProbability(?string $stageProbability): int\n {\n if ($stageProbability === null) {\n return 0;\n }\n\n $probability = (float) $stageProbability;\n\n return $probability > 1 ? 0 : (int) ($probability * 100);\n }\n\n private function resolveForecastCategory(?string $forecastCategory): string\n {\n if (! $forecastCategory) {\n return Forecast::FORECAST_CATEGORY_UNCATEGORIZED;\n }\n\n $forecastCategory = str_replace('_', ' ', $forecastCategory);\n\n return ucwords(strtolower($forecastCategory));\n }\n\n private function importExternalFieldData(array $properties, int $opportunityId): void\n {\n $crmFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData($properties, $crmFields, $opportunityId);\n }\n\n private function importOpportunityContacts(Opportunity $opportunity, array $associations): void\n {\n // Handle empty or missing contact associations\n if (empty($associations)) {\n // Remove all existing contact associations if none provided\n $this->removeAllOpportunityContacts($opportunity);\n\n return;\n }\n\n // Use differential sync approach for better performance and accuracy\n $this->syncOpportunityContactsDifferential($opportunity, $associations);\n }\n\n /**\n * Sync opportunity contacts using differential approach\n * This compares current vs new associations and only makes necessary changes\n */\n private function syncOpportunityContactsDifferential(Opportunity $opportunity, array $contactAssociations): void\n {\n $currentContactCrmIds = $this->getCurrentContactCrmIds($opportunity);\n $contactAssociationIds = array_keys($contactAssociations);\n\n $contactsToAdd = array_diff($contactAssociationIds, $currentContactCrmIds);\n $contactsToRemove = array_diff($currentContactCrmIds, $contactAssociationIds);\n\n if (empty($contactsToAdd) && empty($contactsToRemove)) {\n return;\n }\n\n $this->logContactAssociationChanges($opportunity, $currentContactCrmIds, $contactAssociations, $contactsToAdd, $contactsToRemove);\n\n $this->removeContactAssociations($opportunity, $contactsToRemove);\n $this->addContactAssociations($opportunity, $contactsToAdd, $contactAssociations);\n }\n\n private function getCurrentContactCrmIds(Opportunity $opportunity): array\n {\n return $opportunity->contacts()\n ->pluck('contacts.crm_provider_id')\n ->toArray();\n }\n\n private function logContactAssociationChanges(\n Opportunity $opportunity,\n array $currentContactCrmIds,\n array $contactAssociations,\n array $contactsToAdd,\n array $contactsToRemove\n ): void {\n $this->logger->info('[' . $this->getDisplayName() . '] Contact association changes', [\n 'opportunity_id' => $opportunity->getId(),\n 'current_contacts' => $currentContactCrmIds,\n 'new_contacts' => $contactAssociations,\n 'contacts_to_add' => $contactsToAdd,\n 'contacts_to_remove' => $contactsToRemove,\n ]);\n }\n\n private function removeContactAssociations(Opportunity $opportunity, array $contactsToRemove): void\n {\n if (empty($contactsToRemove)) {\n return;\n }\n\n $contactsToDetach = $opportunity->contacts()\n ->whereIn('contacts.crm_provider_id', $contactsToRemove)\n ->pluck('contacts.id')\n ->toArray();\n\n if (! empty($contactsToDetach)) {\n $opportunity->contacts()->detach($contactsToDetach);\n\n $this->logger->info('[' . $this->getDisplayName() . '] Removed contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'removed_contact_crm_ids' => $contactsToRemove,\n 'removed_contact_count' => count($contactsToDetach),\n ]);\n }\n }\n\n private function addContactAssociations(Opportunity $opportunity, array $contactsToAdd, array $contactAssociations): void\n {\n if (empty($contactsToAdd)) {\n return;\n }\n\n $contactsAdded = [];\n foreach ($contactsToAdd as $crmId) {\n $id = $contactAssociations[$crmId];\n\n if ($this->attachSingleContact($opportunity, (string) $crmId, $id)) {\n $contactsAdded[] = $crmId;\n }\n }\n\n $this->logAddedContacts($opportunity, $contactsAdded);\n }\n\n private function attachSingleContact(Opportunity $opportunity, string $crmId, int $id): bool\n {\n try {\n $contact = $this->crmEntityRepository->findContactByConfigurationAndId($this->config, $id);\n\n if (! $contact) {\n return false;\n }\n\n return $this->performContactAttachment($opportunity, $contact, $crmId);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to add contact association', [\n 'opportunity_id' => $opportunity->getId(),\n 'contact_crm_id' => $crmId,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n private function performContactAttachment(Opportunity $opportunity, Contact $contact, string $crmId): bool\n {\n try {\n $opportunity->contacts()->attach($contact->getId(), [\n 'crm_provider_id' => $crmId,\n ]);\n\n return true;\n } catch (\\Illuminate\\Database\\QueryException $e) {\n if (str_contains($e->getMessage(), 'Duplicate entry')) {\n $this->logger->info('[' . $this->getDisplayName() . '] Contact association already exists', [\n 'contact_id' => $contact->getId(),\n 'contact_crm_id' => $crmId,\n 'opportunity_id' => $opportunity->getId(),\n ]);\n\n return false;\n }\n\n throw $e;\n }\n }\n\n private function logAddedContacts(Opportunity $opportunity, array $contactsAdded): void\n {\n if (! empty($contactsAdded)) {\n $this->logger->info('[' . $this->getDisplayName() . '] Added contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'contacts_to_add_count' => count($contactsAdded),\n 'added_contact_crm_ids' => $contactsAdded,\n 'added_contacts_count' => count($contactsAdded),\n ]);\n }\n }\n}","depth":4,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\ServiceTraits;\n\nuse Carbon\\Carbon;\nuse HubSpot\\Client\\Crm\\Deals\\Model\\CollectionResponseAssociatedId;\nuse Jiminny\\Exceptions\\InvalidArgumentException;\nuse Jiminny\\Models\\Account;\nuse Exception;\nuse Jiminny\\Component\\DealInsights\\Forecast\\Forecast;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Models\\Opportunity;\nuse Illuminate\\Support\\Collection;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Services\\Crm\\Hubspot\\DealFieldsService;\nuse Jiminny\\Services\\Crm\\Hubspot\\OpportunitySyncStrategy\\HubspotSingleSyncStrategy;\nuse Jiminny\\Services\\Crm\\Hubspot\\WebhookSyncBatchProcessor;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\n\n/**\n * Optimized sync methods for better performance\n * These methods can be integrated into SyncCrmEntitiesTrait for significant performance gains\n */\ntrait OpportunitySyncTrait\n{\n private const int BATCH_SIZE = 100;\n private const int BATCH_PROCESS_SIZE = 800;\n\n protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n protected CrmEntityRepository $crmEntityRepository;\n protected DealFieldsService $dealFieldsService;\n\n private ?array $cachedClosedDealStages = null;\n private array $cachedBusinessProcesses = [];\n private array $cachedStages = [];\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n $parameters['config'] = $this->config;\n $syncCount = 0;\n $reportedTotal = 0;\n $lastSyncedId = [];\n\n try {\n foreach ($strategies as $strategyName => $syncStrategy) {\n $this->logger->info(\n '[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' .\n $strategyName\n );\n\n $total = 0;\n $lastId = null;\n $buffer = [];\n\n // HubspotWebhookBatchSyncStrategy returns empty generator, this is for other strategies\n foreach ($syncStrategy->fetchOpportunities($parameters, $total, $lastId) as $hsOpportunity) {\n $buffer[] = $hsOpportunity;\n\n // process every 800 rows (fits < 1 000 association limit)\n if (\\count($buffer) >= self::BATCH_PROCESS_SIZE) {\n $syncCount += $this->processOpportunityBatch($buffer);\n $buffer = [];\n }\n }\n\n // leftovers\n if ($buffer) {\n $syncCount += $this->processOpportunityBatch($buffer);\n }\n\n $reportedTotal += $total;\n $lastSyncedId = $lastId;\n }\n } catch (\\HubSpot\\Client\\Crm\\Deals\\ApiException | CrmException $e) {\n $this->handleSyncException($e, $parameters);\n }\n\n $this->logger->info(\n '[HubSpot] Synced opportunities',\n [\n 'team' => $this->team->getId(),\n 'sync_count' => $syncCount,\n 'total' => $reportedTotal,\n 'last_synced_id' => $lastSyncedId,\n ]\n );\n\n return $reportedTotal;\n }\n\n private function handleSyncException(\\Throwable $e, array $parameters): void\n {\n if (($parameters['since'] ?? null) instanceof Carbon) {\n $parameters['since'] = $parameters['since']->toDateTimeString();\n }\n $parameters['config'] = $this->config->getId();\n\n $this->logger->warning('[' . $this->getDisplayName() . '] Sync opportunities failed', [\n 'teamId' => $this->team->getUuid(),\n 'parameters' => $parameters,\n 'reason' => $e->getMessage(),\n ]);\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,\n );\n\n $parameters = [\n 'config' => $this->config,\n 'crm_id' => $crmId,\n ];\n\n try {\n if (! $strategy instanceof HubspotSingleSyncStrategy) {\n throw new InvalidArgumentException('Strategy must by HubspotSingleSyncStrategy');\n }\n\n $hsOpportunity = $strategy->fetchOpportunity($parameters);\n } catch (\\HubSpot\\Client\\Crm\\Deals\\ApiException $e) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [\n 'teamId' => $this->team->getUuid(),\n 'crmId' => $crmId,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n $hsOpportunity['associations'] = $this->convertDealAssociations($hsOpportunity['associations'] ?? []);\n\n return $this->importOrUpdateOpportunity($hsOpportunity);\n }\n\n /**\n * Process webhook-collected opportunity batches.\n *\n * Drains Redis sets containing company CRM IDs collected from webhook events\n * and dispatches ImportOpportunityBatch jobs for batch processing.\n *\n * @return int Number of opportunity IDs dispatched to jobs\n */\n public function batchSyncOpportunities(): int\n {\n $configId = $this->team->getCrmConfiguration()->getId();\n\n return $this->batchProcessor->processBatchesForObjectType(\n WebhookSyncBatchProcessor::OBJECT_TYPE_DEAL,\n $configId\n );\n }\n\n /**\n * Import a batch of opportunities by their CRM IDs.\n * Fetches opportunity data from HubSpot API and delegates to importOpportunityBatch().\n *\n * @param array<string> $crmIds HubSpot deal CRM IDs\n *\n * @return array{success: array, failed_ids: array, errors?: array<string, string>}\n */\n public function importOpportunityBatchByIds(array $crmIds): array\n {\n $fields = $this->dealFieldsService->getFieldsForConfiguration($this->config);\n\n $allDeals = [];\n foreach (array_chunk($crmIds, self::BATCH_SIZE) as $chunk) {\n $deals = $this->client->getOpportunitiesByIds($chunk, $fields);\n foreach ($deals as $deal) {\n $allDeals[] = $deal;\n }\n }\n\n // IDs not returned by HubSpot are likely deleted or inaccessible deals.\n // These are not failures — retrying won't bring them back.\n $fetchedIds = array_map('strval', array_column($allDeals, 'id'));\n $notFoundIds = array_values(array_diff(array_map('strval', $crmIds), $fetchedIds));\n\n if (! empty($notFoundIds)) {\n $this->logger->info('[' . $this->getDisplayName() . '] CRM IDs not found in HubSpot (likely deleted)', [\n 'teamId' => $this->team->getId(),\n 'notFoundCount' => \\count($notFoundIds),\n 'notFoundIds' => $notFoundIds,\n 'requestedCount' => \\count($crmIds),\n 'fetchedCount' => \\count($allDeals),\n ]);\n }\n\n if (empty($allDeals)) {\n return ['success' => [], 'failed_ids' => []];\n }\n\n return $this->importOpportunityBatch($allDeals);\n }\n\n private function getClosedDealStages(): array\n {\n if ($this->cachedClosedDealStages !== null) {\n return $this->cachedClosedDealStages;\n }\n\n $stages = $this->crmEntityRepository->getOpportunityClosedStages($this->config);\n $data = [\n 'lost' => [],\n 'won' => [],\n ];\n\n foreach ($stages as $stage) {\n if ($stage->probability == 0.00) {\n $data['lost'][] = $stage->crm_provider_id;\n }\n if ($stage->probability == 100.00) {\n $data['won'][] = $stage->crm_provider_id;\n }\n }\n\n $this->cachedClosedDealStages = $data;\n\n return $data;\n }\n\n /**\n * Import deals into the database with pre-fetched associations.\n *\n * API calls here (getAssociationsData, getExistingOpportunityCrmIds) are NOT\n * caught — if they throw, the exception propagates to ImportOpportunityBatch::handle()\n * where Laravel retries the whole job with backoff. After all retries exhausted,\n * failed() requeues all IDs to Redis.\n *\n * The per-deal loop catches exceptions individually. A deal can end up in three states:\n * - success: imported/updated successfully\n * - failed_ids: exception thrown (DB constraint violation, corrupt data, etc.)\n * These are permanent issues — retrying won't fix them.\n * - skipped (null): missing dependencies (no account, unknown pipeline/stage).\n * This is acceptable — the deal cannot be imported until those exist.\n */\n private function importOpportunityBatch(array $deals): array\n {\n $syncedOpportunities = [\n 'success' => [],\n 'failed_ids' => [],\n ];\n $dealIds = array_column($deals, 'id');\n\n // Shared association/existing-ID preparation is batch-level state. If it fails, rethrow so the\n // queue job retries the whole batch and eventually requeues all deal IDs back to Redis.\n try {\n $companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');\n $contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');\n\n $associationsData = $this->prepareAssociatedEntities($companyAssociations, $contactAssociations);\n\n $existingCrmIds = $this->crmEntityRepository->getExistingOpportunityCrmIds(\n $this->config,\n array_map('strval', $dealIds)\n );\n $existingCrmIdSet = array_flip($existingCrmIds);\n } catch (\\Throwable $e) {\n $this->logger->error('[' . $this->getDisplayName() . '] Failed to fetch associations or existing IDs', [\n 'teamId' => $this->team->getId(),\n 'dealCount' => count($dealIds),\n 'error' => $e->getMessage(),\n ]);\n\n throw $e;\n }\n\n foreach ($deals as $deal) {\n try {\n $deal['associations'] = $this->prepareAssociationsForOpportunity(\n $deal['id'],\n $companyAssociations,\n $contactAssociations,\n $associationsData\n );\n\n $syncedOpportunity = $this->importOrUpdateOpportunity(\n $deal,\n isset($existingCrmIdSet[(string) $deal['id']])\n );\n if ($syncedOpportunity) {\n $syncedOpportunities['success'][] = $syncedOpportunity;\n }\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to import opportunity', [\n 'teamId' => $this->team->getId(),\n 'crmId' => $deal['id'],\n 'error' => $e->getMessage(),\n ]);\n $syncedOpportunities['failed_ids'][] = $deal['id'];\n $syncedOpportunities['errors'][$deal['id']] = $e->getMessage();\n }\n }\n\n return $syncedOpportunities;\n }\n\n /**\n * Prepare associated entities for opportunities with optimized batch processing\n * Returns structured data with CRM ID to DB ID mappings for each opportunity\n */\n private function prepareAssociatedEntities(array $companyAssociations, array $contactAssociations): array\n {\n // Step 1: Collect all unique company and contact IDs from associations\n $allCompanyIds = $this->flattenAssociationIds($companyAssociations);\n $allContactIds = $this->flattenAssociationIds($contactAssociations);\n\n // Step 2: Batch sync missing entities and get CRM ID to DB ID mappings\n $companyIdMappings = [];\n $contactIdMappings = [];\n\n if (! empty($allCompanyIds)) {\n $companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);\n }\n\n if (! empty($allContactIds)) {\n $contactIdMappings = $this->prepareAssociatedContacts($allContactIds);\n }\n\n return [\n 'company_id_mappings' => $companyIdMappings,\n 'contact_id_mappings' => $contactIdMappings,\n ];\n }\n\n /**\n * Flatten association data to get unique IDs\n */\n private function flattenAssociationIds(array $associations): array\n {\n $ids = [];\n foreach ($associations as $dealAssociations) {\n if (is_array($dealAssociations)) {\n foreach ($dealAssociations as $id) {\n $ids[$id] = true;\n }\n }\n }\n\n return array_keys($ids);\n }\n\n /**\n * Batch sync missing accounts\n */\n private function prepareAssociatedAccounts(array $companyIds): array\n {\n // Find which accounts already exist\n $existingAccounts = $this->crmEntityRepository\n ->findAccountsByExternalIds($this->config, $companyIds);\n\n $existingCompanyIds = $existingAccounts->pluck('crm_provider_id')->toArray();\n\n $existingAccountsData = $existingAccounts->mapWithKeys(function ($account) {\n return [$account->getCrmProviderId() => $account->getId()];\n })->toArray();\n\n $missingCompanyIds = array_diff($companyIds, $existingCompanyIds);\n\n if (empty($missingCompanyIds)) {\n return $existingAccountsData;\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing accounts', [\n 'teamId' => $this->team->getUuid(),\n 'total_companies' => count($companyIds),\n 'existing_companies' => count($existingCompanyIds),\n 'missing_companies' => count($missingCompanyIds),\n ]);\n\n // we already have limit on opportunity ids count\n // Initialize variable before try block\n $syncedAccountsData = [];\n\n try {\n $syncedAccountsData = $this->batchSyncCrmObjects('companies', $missingCompanyIds);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing accounts', [\n 'size' => count($missingCompanyIds),\n 'error' => $e->getMessage(),\n ]);\n $syncedAccountsData = [];\n }\n\n return $existingAccountsData + $syncedAccountsData;\n }\n\n /**\n * Prepare associated contacts - find existing and sync missing ones\n * Returns mapping of CRM ID to DB ID\n */\n private function prepareAssociatedContacts(array $contactIds): array\n {\n // Find which contacts already exist\n $existingContacts = $this->crmEntityRepository\n ->findContactsByExternalIds($this->config, $contactIds);\n\n $existingContactIds = $existingContacts->pluck('crm_provider_id')->toArray();\n\n // Create mapping for existing contacts\n $existingContactsData = $existingContacts->mapWithKeys(function ($contact) {\n return [$contact->getCrmProviderId() => $contact->getId()];\n })->toArray();\n\n $missingContactIds = array_diff($contactIds, $existingContactIds);\n\n if (empty($missingContactIds)) {\n return $existingContactsData;\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing contacts', [\n 'teamId' => $this->team->getUuid(),\n 'total_contacts' => count($contactIds),\n 'existing_contacts' => count($existingContactIds),\n 'missing_contacts' => count($missingContactIds),\n ]);\n\n // Sync missing contacts using batch API\n try {\n $syncedContactsData = $this->batchSyncCrmObjects('contacts', $missingContactIds);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing contacts', [\n 'size' => count($missingContactIds),\n 'error' => $e->getMessage(),\n ]);\n $syncedContactsData = [];\n }\n\n return $existingContactsData + $syncedContactsData;\n }\n\n private function batchSyncCrmObjects(string $objectType, array $crmIds): array\n {\n $syncObjects = [];\n $crmObjectIds = array_values($crmIds);\n\n foreach (array_chunk($crmObjectIds, self::BATCH_SIZE) as $chunk) {\n try {\n $objects = $objectType === 'companies' ?\n $this->client->getCompaniesByIds($chunk, $this->getCompanyFields()) :\n $this->client->getContactsByIds($chunk, $this->getContactFields());\n\n foreach ($objects as $objectId => $objectData) {\n $this->importCrmObject($objectType, (string) $objectId, $objectData, $syncObjects);\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch synced ' . $objectType, [\n 'requested_count' => count($chunk),\n 'synced_count' => count($objects),\n ]);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Batch ' . $objectType . ' sync failed', [\n 'ids' => $chunk,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n return $syncObjects;\n }\n\n private function importCrmObject(string $objectType, string $objectId, mixed $objectData, array &$syncObjects): void\n {\n try {\n $object = $objectType === 'companies' ?\n $this->importAccount($objectData) :\n $this->importContact($objectData);\n\n if ($object) {\n $syncObjects[$object->getCrmProviderId()] = $object->getId();\n }\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to import batch ' . $objectType, [\n 'id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n /**\n * Prepare associations for a single opportunity\n *\n * The return value is an array with the following structure:\n * [\n * 'companies' => [\n * $companyCrmId => $companyId,\n * ...\n * ],\n * 'contacts' => [\n * $contactCrmId => $contactId,\n * ...\n * ],\n * 'account_id' => $accountId,\n * ]\n */\n private function prepareAssociationsForOpportunity(\n string $oppCrmId,\n array $companyAssociations,\n array $contactAssociations,\n array $associationsData\n ): array {\n $associations = [\n 'companies' => [],\n 'contacts' => [],\n 'account_id' => null, // Primary account for opportunity\n ];\n\n $oppCompanyIds = $companyAssociations[$oppCrmId] ?? [];\n foreach ($oppCompanyIds as $companyCrmId) {\n if (isset($associationsData['company_id_mappings'][$companyCrmId])) {\n $associations['companies'][$companyCrmId] = $associationsData['company_id_mappings'][$companyCrmId];\n\n // Set primary account (first company becomes primary account)\n if ($associations['account_id'] === null) {\n $associations['account_id'] = $associationsData['company_id_mappings'][$companyCrmId];\n }\n }\n }\n\n $oppContactIds = $contactAssociations[$oppCrmId] ?? [];\n foreach ($oppContactIds as $contactCrmId) {\n if (isset($associationsData['contact_id_mappings'][$contactCrmId])) {\n $associations['contacts'][$contactCrmId] = $associationsData['contact_id_mappings'][$contactCrmId];\n }\n }\n\n return $associations;\n }\n\n /**\n * Update only associations for an opportunity\n */\n private function updateOpportunityAssociations(Opportunity $opportunity, array $associations): void\n {\n // Update contact associations\n $this->importOpportunityContacts($opportunity, $associations['contacts']);\n\n // Update company (account) associations\n $this->updateOpportunityAccount($opportunity, $associations['account_id']);\n }\n\n /**\n * Remove all contact associations from an opportunity\n */\n private function removeAllOpportunityContacts(Opportunity $opportunity): void\n {\n $currentCount = (int) $opportunity->contacts()->count();\n\n if ($currentCount > 0) {\n $opportunity->contacts()->detach();\n\n $this->logger->info('[' . $this->getDisplayName() . '] Removed all contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'removed_count' => $currentCount,\n ]);\n }\n }\n\n private function updateOpportunityAccount(Opportunity $opportunity, ?int $accountId): void\n {\n if ($accountId === null) {\n // No account ID provided - keep current account\n return;\n }\n\n $currentAccountId = $opportunity->getAccountId();\n\n // Only update if account has changed\n if ($currentAccountId !== $accountId) {\n $opportunity->account_id = $accountId;\n $opportunity->save();\n\n $this->logger->info('[' . $this->getDisplayName() . '] Updated opportunity account association', [\n 'opportunity_id' => $opportunity->getId(),\n 'old_account_id' => $currentAccountId,\n 'new_account_id' => $accountId,\n ]);\n }\n }\n\n /**\n * Find existing opportunities by external IDs (OPTIMIZED VERSION)\n * Uses batch query for better performance\n */\n private function findExistingOpportunities(array $crmIds): Collection\n {\n return $this->crmEntityRepository\n ->findOpportunitiesByExternalIds($this->config, $crmIds);\n }\n\n private function processOpportunityBatch(array $opportunities): int\n {\n $syncedOpportunities = $this->importOpportunityBatch($opportunities);\n\n return count($syncedOpportunities['success'] ?? []);\n }\n\n /**\n * Convert single deal associations from HubSpot format to internal format\n * Handles both HubSpot SDK objects and array formats\n *\n * @param array $opportunityAssociations Raw associations from HubSpot API or pre-processed\n *\n * @return array Processed associations with DB IDs\n */\n private function convertDealAssociations(array $opportunityAssociations): array\n {\n $associations = $this->initializeAssociationsStructure();\n\n if (empty($opportunityAssociations)) {\n return $associations;\n }\n\n $associationIds = $this->extractAssociationIds($opportunityAssociations);\n\n $this->processCompanyAssociations($associationIds, $associations);\n $this->processContactAssociations($associationIds, $associations);\n\n return $associations;\n }\n\n private function initializeAssociationsStructure(): array\n {\n return [\n 'companies' => [],\n 'contacts' => [],\n 'account_id' => null, // Primary account for opportunity\n ];\n }\n\n private function extractAssociationIds(array $opportunityAssociations): array\n {\n $associationIds = [];\n\n foreach ($opportunityAssociations as $type => $associationData) {\n if (! empty($associationData)) {\n $associationIds[$type] = $this->convertSingleDealAssociations($associationData);\n }\n }\n\n return $associationIds;\n }\n\n private function processCompanyAssociations(array $associationIds, array &$associations): void\n {\n if (empty($associationIds['companies'])) {\n return;\n }\n\n $companyId = $associationIds['companies'][0];\n $account = $this->findOrSyncAccount($companyId);\n\n if ($account instanceof Account) {\n $associations['companies'][$companyId] = $account->getId();\n $associations['account_id'] = $account->getId();\n }\n }\n\n private function processContactAssociations(array $associationIds, array &$associations): void\n {\n if (empty($associationIds['contacts'])) {\n return;\n }\n\n foreach ($associationIds['contacts'] as $contactId) {\n $contact = $this->findOrSyncContact($contactId);\n\n if ($contact instanceof Contact) {\n $associations['contacts'][$contactId] = $contact->getId();\n }\n }\n }\n\n private function findOrSyncAccount(string $companyId): ?Account\n {\n $account = $this->crmEntityRepository->findAccountByExternalId($this->config, $companyId);\n\n if (! $account instanceof Account) {\n $account = $this->syncAccount($companyId);\n }\n\n return $account;\n }\n\n private function findOrSyncContact(string $contactId): ?Contact\n {\n $contact = $this->crmEntityRepository->findContactByExternalId($this->config, $contactId);\n\n if (! $contact instanceof Contact) {\n $contact = $this->syncContact($contactId);\n }\n\n return $contact;\n }\n\n private function convertSingleDealAssociations($opportunityAssociations = null): array\n {\n $associationData = [];\n\n if ($opportunityAssociations === null) {\n return $associationData;\n }\n\n // Handle array input (from extractAssociationIds)\n if (is_array($opportunityAssociations)) {\n return $opportunityAssociations;\n }\n\n // Handle CollectionResponseAssociatedId object\n if ($opportunityAssociations instanceof CollectionResponseAssociatedId) {\n foreach ($opportunityAssociations->getResults() as $association) {\n $associationData[] = $association->getId();\n }\n }\n\n return $associationData;\n }\n\n private function importOrUpdateOpportunity($crmData, ?bool $exists = null): ?Opportunity\n {\n if (empty($crmData['properties'])) {\n return null;\n }\n\n $crmId = (string) $crmData['id'];\n $properties = $crmData['properties'];\n $associations = $crmData['associations'] ?? [];\n\n $opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(\n $this->config,\n $crmId\n );\n\n if ($opportunityExists) {\n return $this->updateOpportunity($crmId, $properties, $associations);\n } else {\n return $this->createOpportunity($crmId, $properties, $associations);\n }\n }\n\n /**\n * Create new opportunity\n */\n private function createOpportunity(string $crmId, array $properties, array $associations): ?Opportunity\n {\n $accountId = $this->resolveAccountId($associations);\n if (! $accountId) {\n return null;\n }\n\n $businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);\n if (! $businessProcess) {\n return null;\n }\n\n $stage = $this->resolveStage($businessProcess, $properties['dealstage'] ?? null);\n if (! $stage) {\n return null;\n }\n\n $data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);\n\n $attributes = [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmId,\n ];\n\n $values = array_merge($attributes, $data);\n\n $opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);\n\n $this->importExternalFieldData($properties, $opportunity->getId());\n $this->importOpportunityContacts($opportunity, $associations['contacts']);\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n }\n\n /**\n * Update existing opportunity\n */\n private function updateOpportunity(string $crmId, array $properties, array $associations): Opportunity\n {\n $accountId = $this->resolveAccountId($associations);\n $businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);\n $stage = $businessProcess ? $this->resolveStage($businessProcess, $properties['dealstage'] ?? null) : null;\n\n $data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);\n\n $attributes = [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmId,\n ];\n\n $values = array_merge($attributes, $data);\n $opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);\n\n $this->importExternalFieldData($properties, $opportunity->getId());\n $this->updateOpportunityAssociations($opportunity, $associations);\n\n return $opportunity;\n }\n\n private function resolveAccountId(array $associations): ?int\n {\n if (! empty($associations['accountId'])) {\n return $associations['accountId'];\n }\n\n if (empty($associations)) {\n return null;\n }\n\n // we can't resolve multiple account ids (currently SDK returns one company)\n foreach ($associations['companies'] as $accountId) {\n return $accountId;\n }\n\n return null;\n }\n\n private function buildOpportunityData(\n array $properties,\n ?int $accountId,\n ?BusinessProcess $businessProcess,\n ?Stage $stage\n ): array {\n $ownerId = null;\n $profile = null;\n if (! empty($properties['hubspot_owner_id'])) {\n $ownerId = $properties['hubspot_owner_id'];\n $profile = $this->crmEntityRepository->findProfileByExternalId($this->config, (string) $ownerId);\n }\n\n $name = 'Unknown';\n if (isset($properties['dealname'])) {\n $name = mb_strimwidth($properties['dealname'], 0, 128);\n }\n\n $amount = $this->resolveAmount($properties);\n $currency = $properties['deal_currency_code'] ?? null;\n\n $closeDate = null;\n if (! empty($properties['closedate'])) {\n $closeDate = Carbon::parse($properties['closedate'])->format('Y-m-d');\n }\n\n $remotelyCreatedAt = null;\n if (! empty($properties['createdate']) && strtotime($properties['createdate'])) {\n $date = $this->parseCleanDatetime($properties['createdate']);\n $remotelyCreatedAt = $date?->format('Y-m-d H:i:s');\n }\n\n $closedStages = $this->getClosedDealStages();\n $isWon = in_array($properties['dealstage'], $closedStages['won']);\n $isLost = in_array($properties['dealstage'], $closedStages['lost']);\n\n $data = [\n 'team_id' => $this->team->getId(),\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => $name,\n 'value' => ! empty($amount) ? $amount : null,\n 'currency_code' => CurrencyFormatter::formatCode($currency),\n 'close_date' => $closeDate,\n 'is_closed' => $isWon || $isLost,\n 'is_won' => $isWon,\n 'remotely_created_at' => $remotelyCreatedAt,\n 'probability' => $this->resolveDealProbability($properties['hs_deal_stage_probability']),\n 'forecast_category' => $this->resolveForecastCategory($properties['hs_manual_forecast_category']),\n ];\n\n if ($accountId) {\n $data['account_id'] = $accountId;\n }\n\n if ($stage) {\n $data['stage_id'] = $stage->id;\n }\n\n if ($businessProcess) {\n $recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);\n if ($recordType) {\n $data['record_type_id'] = $recordType->id;\n }\n }\n\n return $data;\n }\n\n private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess\n {\n if ($pipelineId === null) {\n return null;\n }\n\n if (isset($this->cachedBusinessProcesses[$pipelineId])) {\n return $this->cachedBusinessProcesses[$pipelineId];\n }\n\n $businessProcess = $this->getBusinessProcess($pipelineId);\n\n if (! $businessProcess instanceof BusinessProcess) {\n $this->importStages();\n $businessProcess = $this->getBusinessProcess($pipelineId);\n }\n\n if (! $businessProcess instanceof BusinessProcess) {\n $this->logger->info(\n '[HubSpot] Deal is not attached to a pipeline',\n [\n 'pipeline' => $pipelineId]\n );\n }\n\n $this->cachedBusinessProcesses[$pipelineId] = $businessProcess;\n\n return $businessProcess;\n }\n\n private function getBusinessProcess(string $pipelineId): ?BusinessProcess\n {\n return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);\n }\n\n private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage\n {\n if (empty($stageId)) {\n return null;\n }\n\n $cacheKey = $businessProcess->getId() . ':' . $stageId;\n if (isset($this->cachedStages[$cacheKey])) {\n return $this->cachedStages[$cacheKey];\n }\n\n $stage = $this->crmEntityRepository->getPipelineStageByConditions(\n $businessProcess,\n [\n 'crm_provider_id' => $stageId,\n 'type' => Stage::TYPE_OPPORTUNITY,\n ]\n );\n\n if ($stage === null) {\n $this->importStages(null, $stageId);\n }\n\n if ($stage === null) {\n $this->logger->info('[HubSpot] Stage does not exist => ' . $stageId);\n }\n\n $this->cachedStages[$cacheKey] = $stage;\n\n return $stage;\n }\n\n private function resolveAmount(array $properties): ?string\n {\n $amount = null;\n if (! empty($properties['amount'])) {\n $amount = str_replace(',', '', $properties['amount']);\n }\n\n if ($this->config->hasDefaultCurrencyFieldSet()) {\n $valueFieldName = $this->config->getDefaultCurrencyField()->getCrmProviderId();\n $amount = $properties[$valueFieldName] ?? $amount;\n }\n\n return $amount;\n }\n\n private function parseCleanDatetime(string $datetime): ?Carbon\n {\n // Treat pre-1980 values as invalid\n $minValidDate = Carbon::parse('1980-01-01 00:00:00');\n\n try {\n $date = Carbon::parse($datetime);\n\n if ($minValidDate->gt($date)) {\n return null;\n }\n\n return $date;\n } catch (Exception) {\n return null; // On parse error, treat as null\n }\n }\n\n private function resolveDealProbability(?string $stageProbability): int\n {\n if ($stageProbability === null) {\n return 0;\n }\n\n $probability = (float) $stageProbability;\n\n return $probability > 1 ? 0 : (int) ($probability * 100);\n }\n\n private function resolveForecastCategory(?string $forecastCategory): string\n {\n if (! $forecastCategory) {\n return Forecast::FORECAST_CATEGORY_UNCATEGORIZED;\n }\n\n $forecastCategory = str_replace('_', ' ', $forecastCategory);\n\n return ucwords(strtolower($forecastCategory));\n }\n\n private function importExternalFieldData(array $properties, int $opportunityId): void\n {\n $crmFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData($properties, $crmFields, $opportunityId);\n }\n\n private function importOpportunityContacts(Opportunity $opportunity, array $associations): void\n {\n // Handle empty or missing contact associations\n if (empty($associations)) {\n // Remove all existing contact associations if none provided\n $this->removeAllOpportunityContacts($opportunity);\n\n return;\n }\n\n // Use differential sync approach for better performance and accuracy\n $this->syncOpportunityContactsDifferential($opportunity, $associations);\n }\n\n /**\n * Sync opportunity contacts using differential approach\n * This compares current vs new associations and only makes necessary changes\n */\n private function syncOpportunityContactsDifferential(Opportunity $opportunity, array $contactAssociations): void\n {\n $currentContactCrmIds = $this->getCurrentContactCrmIds($opportunity);\n $contactAssociationIds = array_keys($contactAssociations);\n\n $contactsToAdd = array_diff($contactAssociationIds, $currentContactCrmIds);\n $contactsToRemove = array_diff($currentContactCrmIds, $contactAssociationIds);\n\n if (empty($contactsToAdd) && empty($contactsToRemove)) {\n return;\n }\n\n $this->logContactAssociationChanges($opportunity, $currentContactCrmIds, $contactAssociations, $contactsToAdd, $contactsToRemove);\n\n $this->removeContactAssociations($opportunity, $contactsToRemove);\n $this->addContactAssociations($opportunity, $contactsToAdd, $contactAssociations);\n }\n\n private function getCurrentContactCrmIds(Opportunity $opportunity): array\n {\n return $opportunity->contacts()\n ->pluck('contacts.crm_provider_id')\n ->toArray();\n }\n\n private function logContactAssociationChanges(\n Opportunity $opportunity,\n array $currentContactCrmIds,\n array $contactAssociations,\n array $contactsToAdd,\n array $contactsToRemove\n ): void {\n $this->logger->info('[' . $this->getDisplayName() . '] Contact association changes', [\n 'opportunity_id' => $opportunity->getId(),\n 'current_contacts' => $currentContactCrmIds,\n 'new_contacts' => $contactAssociations,\n 'contacts_to_add' => $contactsToAdd,\n 'contacts_to_remove' => $contactsToRemove,\n ]);\n }\n\n private function removeContactAssociations(Opportunity $opportunity, array $contactsToRemove): void\n {\n if (empty($contactsToRemove)) {\n return;\n }\n\n $contactsToDetach = $opportunity->contacts()\n ->whereIn('contacts.crm_provider_id', $contactsToRemove)\n ->pluck('contacts.id')\n ->toArray();\n\n if (! empty($contactsToDetach)) {\n $opportunity->contacts()->detach($contactsToDetach);\n\n $this->logger->info('[' . $this->getDisplayName() . '] Removed contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'removed_contact_crm_ids' => $contactsToRemove,\n 'removed_contact_count' => count($contactsToDetach),\n ]);\n }\n }\n\n private function addContactAssociations(Opportunity $opportunity, array $contactsToAdd, array $contactAssociations): void\n {\n if (empty($contactsToAdd)) {\n return;\n }\n\n $contactsAdded = [];\n foreach ($contactsToAdd as $crmId) {\n $id = $contactAssociations[$crmId];\n\n if ($this->attachSingleContact($opportunity, (string) $crmId, $id)) {\n $contactsAdded[] = $crmId;\n }\n }\n\n $this->logAddedContacts($opportunity, $contactsAdded);\n }\n\n private function attachSingleContact(Opportunity $opportunity, string $crmId, int $id): bool\n {\n try {\n $contact = $this->crmEntityRepository->findContactByConfigurationAndId($this->config, $id);\n\n if (! $contact) {\n return false;\n }\n\n return $this->performContactAttachment($opportunity, $contact, $crmId);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to add contact association', [\n 'opportunity_id' => $opportunity->getId(),\n 'contact_crm_id' => $crmId,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n private function performContactAttachment(Opportunity $opportunity, Contact $contact, string $crmId): bool\n {\n try {\n $opportunity->contacts()->attach($contact->getId(), [\n 'crm_provider_id' => $crmId,\n ]);\n\n return true;\n } catch (\\Illuminate\\Database\\QueryException $e) {\n if (str_contains($e->getMessage(), 'Duplicate entry')) {\n $this->logger->info('[' . $this->getDisplayName() . '] Contact association already exists', [\n 'contact_id' => $contact->getId(),\n 'contact_crm_id' => $crmId,\n 'opportunity_id' => $opportunity->getId(),\n ]);\n\n return false;\n }\n\n throw $e;\n }\n }\n\n private function logAddedContacts(Opportunity $opportunity, array $contactsAdded): void\n {\n if (! empty($contactsAdded)) {\n $this->logger->info('[' . $this->getDisplayName() . '] Added contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'contacts_to_add_count' => count($contactsAdded),\n 'added_contact_crm_ids' => $contactsAdded,\n 'added_contacts_count' => count($contactsAdded),\n ]);\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.4152344,"top":0.10763889,"width":0.01015625,"height":0.016666668},"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.42539063,"top":0.10763889,"width":0.01015625,"height":0.016666668},"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.43828124,"top":0.10763889,"width":0.01015625,"height":0.016666668},"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.4484375,"top":0.10763889,"width":0.01015625,"height":0.016666668},"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.45859376,"top":0.10763889,"width":0.01015625,"height":0.016666668},"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.47148436,"top":0.10763889,"width":0.01015625,"height":0.016666668},"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.484375,"top":0.10763889,"width":0.028515626,"height":0.016666668},"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.515625,"top":0.10763889,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Playground","depth":4,"bounds":{"left":0.52851564,"top":0.10763889,"width":0.034765624,"height":0.016666668},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"jiminny","depth":4,"bounds":{"left":0.6917969,"top":0.10763889,"width":0.033203125,"height":0.016666668},"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.23320313,"top":1.0,"width":0.049609374,"height":0.0},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.23320313,"top":1.0,"width":0.01015625,"height":0.0},"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.23320313,"top":1.0,"width":0.01015625,"height":0.0},"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.23320313,"top":1.0,"width":0.01015625,"height":0.0},"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
2293154865818988745
|
-8178087410993360602
|
idle
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
"podcast_audio_url"
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
0 results
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Code changed:
Hide
Sync Changes
Hide This Notification
32
2
19
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\ServiceTraits;
use Carbon\Carbon;
use HubSpot\Client\Crm\Deals\Model\CollectionResponseAssociatedId;
use Jiminny\Exceptions\InvalidArgumentException;
use Jiminny\Models\Account;
use Exception;
use Jiminny\Component\DealInsights\Forecast\Forecast;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Exceptions\CrmException;
use Jiminny\Models\Opportunity;
use Illuminate\Support\Collection;
use Jiminny\Models\Stage;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Services\Crm\Hubspot\DealFieldsService;
use Jiminny\Services\Crm\Hubspot\OpportunitySyncStrategy\HubspotSingleSyncStrategy;
use Jiminny\Services\Crm\Hubspot\WebhookSyncBatchProcessor;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
/**
* Optimized sync methods for better performance
* These methods can be integrated into SyncCrmEntitiesTrait for significant performance gains
*/
trait OpportunitySyncTrait
{
private const int BATCH_SIZE = 100;
private const int BATCH_PROCESS_SIZE = 800;
protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
protected CrmEntityRepository $crmEntityRepository;
protected DealFieldsService $dealFieldsService;
private ?array $cachedClosedDealStages = null;
private array $cachedBusinessProcesses = [];
private array $cachedStages = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' .
$strategyName
);
$total = 0;
$lastId = null;
$buffer = [];
// HubspotWebhookBatchSyncStrategy returns empty generator, this is for other strategies
foreach ($syncStrategy->fetchOpportunities($parameters, $total, $lastId) as $hsOpportunity) {
$buffer[] = $hsOpportunity;
// process every 800 rows (fits < 1 000 association limit)
if (\count($buffer) >= self::BATCH_PROCESS_SIZE) {
$syncCount += $this->processOpportunityBatch($buffer);
$buffer = [];
}
}
// leftovers
if ($buffer) {
$syncCount += $this->processOpportunityBatch($buffer);
}
$reportedTotal += $total;
$lastSyncedId = $lastId;
}
} catch (\HubSpot\Client\Crm\Deals\ApiException | CrmException $e) {
$this->handleSyncException($e, $parameters);
}
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
]
);
return $reportedTotal;
}
private function handleSyncException(\Throwable $e, array $parameters): void
{
if (($parameters['since'] ?? null) instanceof Carbon) {
$parameters['since'] = $parameters['since']->toDateTimeString();
}
$parameters['config'] = $this->config->getId();
$this->logger->warning('[' . $this->getDisplayName() . '] Sync opportunities failed', [
'teamId' => $this->team->getUuid(),
'parameters' => $parameters,
'reason' => $e->getMessage(),
]);
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,
);
$parameters = [
'config' => $this->config,
'crm_id' => $crmId,
];
try {
if (! $strategy instanceof HubspotSingleSyncStrategy) {
throw new InvalidArgumentException('Strategy must by HubspotSingleSyncStrategy');
}
$hsOpportunity = $strategy->fetchOpportunity($parameters);
} catch (\HubSpot\Client\Crm\Deals\ApiException $e) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [
'teamId' => $this->team->getUuid(),
'crmId' => $crmId,
'reason' => $e->getMessage(),
]);
return null;
}
$hsOpportunity['associations'] = $this->convertDealAssociations($hsOpportunity['associations'] ?? []);
return $this->importOrUpdateOpportunity($hsOpportunity);
}
/**
* Process webhook-collected opportunity batches.
*
* Drains Redis sets containing company CRM IDs collected from webhook events
* and dispatches ImportOpportunityBatch jobs for batch processing.
*
* @return int Number of opportunity IDs dispatched to jobs
*/
public function batchSyncOpportunities(): int
{
$configId = $this->team->getCrmConfiguration()->getId();
return $this->batchProcessor->processBatchesForObjectType(
WebhookSyncBatchProcessor::OBJECT_TYPE_DEAL,
$configId
);
}
/**
* Import a batch of opportunities by their CRM IDs.
* Fetches opportunity data from HubSpot API and delegates to importOpportunityBatch().
*
* @param array<string> $crmIds HubSpot deal CRM IDs
*
* @return array{success: array, failed_ids: array, errors?: array<string, string>}
*/
public function importOpportunityBatchByIds(array $crmIds): array
{
$fields = $this->dealFieldsService->getFieldsForConfiguration($this->config);
$allDeals = [];
foreach (array_chunk($crmIds, self::BATCH_SIZE) as $chunk) {
$deals = $this->client->getOpportunitiesByIds($chunk, $fields);
foreach ($deals as $deal) {
$allDeals[] = $deal;
}
}
// IDs not returned by HubSpot are likely deleted or inaccessible deals.
// These are not failures — retrying won't bring them back.
$fetchedIds = array_map('strval', array_column($allDeals, 'id'));
$notFoundIds = array_values(array_diff(array_map('strval', $crmIds), $fetchedIds));
if (! empty($notFoundIds)) {
$this->logger->info('[' . $this->getDisplayName() . '] CRM IDs not found in HubSpot (likely deleted)', [
'teamId' => $this->team->getId(),
'notFoundCount' => \count($notFoundIds),
'notFoundIds' => $notFoundIds,
'requestedCount' => \count($crmIds),
'fetchedCount' => \count($allDeals),
]);
}
if (empty($allDeals)) {
return ['success' => [], 'failed_ids' => []];
}
return $this->importOpportunityBatch($allDeals);
}
private function getClosedDealStages(): array
{
if ($this->cachedClosedDealStages !== null) {
return $this->cachedClosedDealStages;
}
$stages = $this->crmEntityRepository->getOpportunityClosedStages($this->config);
$data = [
'lost' => [],
'won' => [],
];
foreach ($stages as $stage) {
if ($stage->probability == 0.00) {
$data['lost'][] = $stage->crm_provider_id;
}
if ($stage->probability == 100.00) {
$data['won'][] = $stage->crm_provider_id;
}
}
$this->cachedClosedDealStages = $data;
return $data;
}
/**
* Import deals into the database with pre-fetched associations.
*
* API calls here (getAssociationsData, getExistingOpportunityCrmIds) are NOT
* caught — if they throw, the exception propagates to ImportOpportunityBatch::handle()
* where Laravel retries the whole job with backoff. After all retries exhausted,
* failed() requeues all IDs to Redis.
*
* The per-deal loop catches exceptions individually. A deal can end up in three states:
* - success: imported/updated successfully
* - failed_ids: exception thrown (DB constraint violation, corrupt data, etc.)
* These are permanent issues — retrying won't fix them.
* - skipped (null): missing dependencies (no account, unknown pipeline/stage).
* This is acceptable — the deal cannot be imported until those exist.
*/
private function importOpportunityBatch(array $deals): array
{
$syncedOpportunities = [
'success' => [],
'failed_ids' => [],
];
$dealIds = array_column($deals, 'id');
// Shared association/existing-ID preparation is batch-level state. If it fails, rethrow so the
// queue job retries the whole batch and eventually requeues all deal IDs back to Redis.
try {
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$associationsData = $this->prepareAssociatedEntities($companyAssociations, $contactAssociations);
$existingCrmIds = $this->crmEntityRepository->getExistingOpportunityCrmIds(
$this->config,
array_map('strval', $dealIds)
);
$existingCrmIdSet = array_flip($existingCrmIds);
} catch (\Throwable $e) {
$this->logger->error('[' . $this->getDisplayName() . '] Failed to fetch associations or existing IDs', [
'teamId' => $this->team->getId(),
'dealCount' => count($dealIds),
'error' => $e->getMessage(),
]);
throw $e;
}
foreach ($deals as $deal) {
try {
$deal['associations'] = $this->prepareAssociationsForOpportunity(
$deal['id'],
$companyAssociations,
$contactAssociations,
$associationsData
);
$syncedOpportunity = $this->importOrUpdateOpportunity(
$deal,
isset($existingCrmIdSet[(string) $deal['id']])
);
if ($syncedOpportunity) {
$syncedOpportunities['success'][] = $syncedOpportunity;
}
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to import opportunity', [
'teamId' => $this->team->getId(),
'crmId' => $deal['id'],
'error' => $e->getMessage(),
]);
$syncedOpportunities['failed_ids'][] = $deal['id'];
$syncedOpportunities['errors'][$deal['id']] = $e->getMessage();
}
}
return $syncedOpportunities;
}
/**
* Prepare associated entities for opportunities with optimized batch processing
* Returns structured data with CRM ID to DB ID mappings for each opportunity
*/
private function prepareAssociatedEntities(array $companyAssociations, array $contactAssociations): array
{
// Step 1: Collect all unique company and contact IDs from associations
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
// Step 2: Batch sync missing entities and get CRM ID to DB ID mappings
$companyIdMappings = [];
$contactIdMappings = [];
if (! empty($allCompanyIds)) {
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
}
if (! empty($allContactIds)) {
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
}
return [
'company_id_mappings' => $companyIdMappings,
'contact_id_mappings' => $contactIdMappings,
];
}
/**
* Flatten association data to get unique IDs
*/
private function flattenAssociationIds(array $associations): array
{
$ids = [];
foreach ($associations as $dealAssociations) {
if (is_array($dealAssociations)) {
foreach ($dealAssociations as $id) {
$ids[$id] = true;
}
}
}
return array_keys($ids);
}
/**
* Batch sync missing accounts
*/
private function prepareAssociatedAccounts(array $companyIds): array
{
// Find which accounts already exist
$existingAccounts = $this->crmEntityRepository
->findAccountsByExternalIds($this->config, $companyIds);
$existingCompanyIds = $existingAccounts->pluck('crm_provider_id')->toArray();
$existingAccountsData = $existingAccounts->mapWithKeys(function ($account) {
return [$account->getCrmProviderId() => $account->getId()];
})->toArray();
$missingCompanyIds = array_diff($companyIds, $existingCompanyIds);
if (empty($missingCompanyIds)) {
return $existingAccountsData;
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing accounts', [
'teamId' => $this->team->getUuid(),
'total_companies' => count($companyIds),
'existing_companies' => count($existingCompanyIds),
'missing_companies' => count($missingCompanyIds),
]);
// we already have limit on opportunity ids count
// Initialize variable before try block
$syncedAccountsData = [];
try {
$syncedAccountsData = $this->batchSyncCrmObjects('companies', $missingCompanyIds);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing accounts', [
'size' => count($missingCompanyIds),
'error' => $e->getMessage(),
]);
$syncedAccountsData = [];
}
return $existingAccountsData + $syncedAccountsData;
}
/**
* Prepare associated contacts - find existing and sync missing ones
* Returns mapping of CRM ID to DB ID
*/
private function prepareAssociatedContacts(array $contactIds): array
{
// Find which contacts already exist
$existingContacts = $this->crmEntityRepository
->findContactsByExternalIds($this->config, $contactIds);
$existingContactIds = $existingContacts->pluck('crm_provider_id')->toArray();
// Create mapping for existing contacts
$existingContactsData = $existingContacts->mapWithKeys(function ($contact) {
return [$contact->getCrmProviderId() => $contact->getId()];
})->toArray();
$missingContactIds = array_diff($contactIds, $existingContactIds);
if (empty($missingContactIds)) {
return $existingContactsData;
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing contacts', [
'teamId' => $this->team->getUuid(),
'total_contacts' => count($contactIds),
'existing_contacts' => count($existingContactIds),
'missing_contacts' => count($missingContactIds),
]);
// Sync missing contacts using batch API
try {
$syncedContactsData = $this->batchSyncCrmObjects('contacts', $missingContactIds);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing contacts', [
'size' => count($missingContactIds),
'error' => $e->getMessage(),
]);
$syncedContactsData = [];
}
return $existingContactsData + $syncedContactsData;
}
private function batchSyncCrmObjects(string $objectType, array $crmIds): array
{
$syncObjects = [];
$crmObjectIds = array_values($crmIds);
foreach (array_chunk($crmObjectIds, self::BATCH_SIZE) as $chunk) {
try {
$objects = $objectType === 'companies' ?
$this->client->getCompaniesByIds($chunk, $this->getCompanyFields()) :
$this->client->getContactsByIds($chunk, $this->getContactFields());
foreach ($objects as $objectId => $objectData) {
$this->importCrmObject($objectType, (string) $objectId, $objectData, $syncObjects);
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch synced ' . $objectType, [
'requested_count' => count($chunk),
'synced_count' => count($objects),
]);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Batch ' . $objectType . ' sync failed', [
'ids' => $chunk,
'error' => $e->getMessage(),
]);
}
}
return $syncObjects;
}
private function importCrmObject(string $objectType, string $objectId, mixed $objectData, array &$syncObjects): void
{
try {
$object = $objectType === 'companies' ?
$this->importAccount($objectData) :
$this->importContact($objectData);
if ($object) {
$syncObjects[$object->getCrmProviderId()] = $object->getId();
}
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to import batch ' . $objectType, [
'id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
/**
* Prepare associations for a single opportunity
*
* The return value is an array with the following structure:
* [
* 'companies' => [
* $companyCrmId => $companyId,
* ...
* ],
* 'contacts' => [
* $contactCrmId => $contactId,
* ...
* ],
* 'account_id' => $accountId,
* ]
*/
private function prepareAssociationsForOpportunity(
string $oppCrmId,
array $companyAssociations,
array $contactAssociations,
array $associationsData
): array {
$associations = [
'companies' => [],
'contacts' => [],
'account_id' => null, // Primary account for opportunity
];
$oppCompanyIds = $companyAssociations[$oppCrmId] ?? [];
foreach ($oppCompanyIds as $companyCrmId) {
if (isset($associationsData['company_id_mappings'][$companyCrmId])) {
$associations['companies'][$companyCrmId] = $associationsData['company_id_mappings'][$companyCrmId];
// Set primary account (first company becomes primary account)
if ($associations['account_id'] === null) {
$associations['account_id'] = $associationsData['company_id_mappings'][$companyCrmId];
}
}
}
$oppContactIds = $contactAssociations[$oppCrmId] ?? [];
foreach ($oppContactIds as $contactCrmId) {
if (isset($associationsData['contact_id_mappings'][$contactCrmId])) {
$associations['contacts'][$contactCrmId] = $associationsData['contact_id_mappings'][$contactCrmId];
}
}
return $associations;
}
/**
* Update only associations for an opportunity
*/
private function updateOpportunityAssociations(Opportunity $opportunity, array $associations): void
{
// Update contact associations
$this->importOpportunityContacts($opportunity, $associations['contacts']);
// Update company (account) associations
$this->updateOpportunityAccount($opportunity, $associations['account_id']);
}
/**
* Remove all contact associations from an opportunity
*/
private function removeAllOpportunityContacts(Opportunity $opportunity): void
{
$currentCount = (int) $opportunity->contacts()->count();
if ($currentCount > 0) {
$opportunity->contacts()->detach();
$this->logger->info('[' . $this->getDisplayName() . '] Removed all contact associations', [
'opportunity_id' => $opportunity->getId(),
'removed_count' => $currentCount,
]);
}
}
private function updateOpportunityAccount(Opportunity $opportunity, ?int $accountId): void
{
if ($accountId === null) {
// No account ID provided - keep current account
return;
}
$currentAccountId = $opportunity->getAccountId();
// Only update if account has changed
if ($currentAccountId !== $accountId) {
$opportunity->account_id = $accountId;
$opportunity->save();
$this->logger->info('[' . $this->getDisplayName() . '] Updated opportunity account association', [
'opportunity_id' => $opportunity->getId(),
'old_account_id' => $currentAccountId,
'new_account_id' => $accountId,
]);
}
}
/**
* Find existing opportunities by external IDs (OPTIMIZED VERSION)
* Uses batch query for better performance
*/
private function findExistingOpportunities(array $crmIds): Collection
{
return $this->crmEntityRepository
->findOpportunitiesByExternalIds($this->config, $crmIds);
}
private function processOpportunityBatch(array $opportunities): int
{
$syncedOpportunities = $this->importOpportunityBatch($opportunities);
return count($syncedOpportunities['success'] ?? []);
}
/**
* Convert single deal associations from HubSpot format to internal format
* Handles both HubSpot SDK objects and array formats
*
* @param array $opportunityAssociations Raw associations from HubSpot API or pre-processed
*
* @return array Processed associations with DB IDs
*/
private function convertDealAssociations(array $opportunityAssociations): array
{
$associations = $this->initializeAssociationsStructure();
if (empty($opportunityAssociations)) {
return $associations;
}
$associationIds = $this->extractAssociationIds($opportunityAssociations);
$this->processCompanyAssociations($associationIds, $associations);
$this->processContactAssociations($associationIds, $associations);
return $associations;
}
private function initializeAssociationsStructure(): array
{
return [
'companies' => [],
'contacts' => [],
'account_id' => null, // Primary account for opportunity
];
}
private function extractAssociationIds(array $opportunityAssociations): array
{
$associationIds = [];
foreach ($opportunityAssociations as $type => $associationData) {
if (! empty($associationData)) {
$associationIds[$type] = $this->convertSingleDealAssociations($associationData);
}
}
return $associationIds;
}
private function processCompanyAssociations(array $associationIds, array &$associations): void
{
if (empty($associationIds['companies'])) {
return;
}
$companyId = $associationIds['companies'][0];
$account = $this->findOrSyncAccount($companyId);
if ($account instanceof Account) {
$associations['companies'][$companyId] = $account->getId();
$associations['account_id'] = $account->getId();
}
}
private function processContactAssociations(array $associationIds, array &$associations): void
{
if (empty($associationIds['contacts'])) {
return;
}
foreach ($associationIds['contacts'] as $contactId) {
$contact = $this->findOrSyncContact($contactId);
if ($contact instanceof Contact) {
$associations['contacts'][$contactId] = $contact->getId();
}
}
}
private function findOrSyncAccount(string $companyId): ?Account
{
$account = $this->crmEntityRepository->findAccountByExternalId($this->config, $companyId);
if (! $account instanceof Account) {
$account = $this->syncAccount($companyId);
}
return $account;
}
private function findOrSyncContact(string $contactId): ?Contact
{
$contact = $this->crmEntityRepository->findContactByExternalId($this->config, $contactId);
if (! $contact instanceof Contact) {
$contact = $this->syncContact($contactId);
}
return $contact;
}
private function convertSingleDealAssociations($opportunityAssociations = null): array
{
$associationData = [];
if ($opportunityAssociations === null) {
return $associationData;
}
// Handle array input (from extractAssociationIds)
if (is_array($opportunityAssociations)) {
return $opportunityAssociations;
}
// Handle CollectionResponseAssociatedId object
if ($opportunityAssociations instanceof CollectionResponseAssociatedId) {
foreach ($opportunityAssociations->getResults() as $association) {
$associationData[] = $association->getId();
}
}
return $associationData;
}
private function importOrUpdateOpportunity($crmData, ?bool $exists = null): ?Opportunity
{
if (empty($crmData['properties'])) {
return null;
}
$crmId = (string) $crmData['id'];
$properties = $crmData['properties'];
$associations = $crmData['associations'] ?? [];
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity($crmId, $properties, $associations);
} else {
return $this->createOpportunity($crmId, $properties, $associations);
}
}
/**
* Create new opportunity
*/
private function createOpportunity(string $crmId, array $properties, array $associations): ?Opportunity
{
$accountId = $this->resolveAccountId($associations);
if (! $accountId) {
return null;
}
$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);
if (! $businessProcess) {
return null;
}
$stage = $this->resolveStage($businessProcess, $properties['dealstage'] ?? null);
if (! $stage) {
return null;
}
$data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);
$attributes = [
'crm_configuration_id' => $this->config->getId(),
'crm_provider_id' => $crmId,
];
$values = array_merge($attributes, $data);
$opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);
$this->importExternalFieldData($properties, $opportunity->getId());
$this->importOpportunityContacts($opportunity, $associations['contacts']);
if ($opportunity->wasRecentlyCreated) {
MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());
}
return $opportunity;
}
/**
* Update existing opportunity
*/
private function updateOpportunity(string $crmId, array $properties, array $associations): Opportunity
{
$accountId = $this->resolveAccountId($associations);
$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);
$stage = $businessProcess ? $this->resolveStage($businessProcess, $properties['dealstage'] ?? null) : null;
$data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);
$attributes = [
'crm_configuration_id' => $this->config->getId(),
'crm_provider_id' => $crmId,
];
$values = array_merge($attributes, $data);
$opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);
$this->importExternalFieldData($properties, $opportunity->getId());
$this->updateOpportunityAssociations($opportunity, $associations);
return $opportunity;
}
private function resolveAccountId(array $associations): ?int
{
if (! empty($associations['accountId'])) {
return $associations['accountId'];
}
if (empty($associations)) {
return null;
}
// we can't resolve multiple account ids (currently SDK returns one company)
foreach ($associations['companies'] as $accountId) {
return $accountId;
}
return null;
}
private function buildOpportunityData(
array $properties,
?int $accountId,
?BusinessProcess $businessProcess,
?Stage $stage
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, (string) $ownerId);
}
$name = 'Unknown';
if (isset($properties['dealname'])) {
$name = mb_strimwidth($properties['dealname'], 0, 128);
}
$amount = $this->resolveAmount($properties);
$currency = $properties['deal_currency_code'] ?? null;
$closeDate = null;
if (! empty($properties['closedate'])) {
$closeDate = Carbon::parse($properties['closedate'])->format('Y-m-d');
}
$remotelyCreatedAt = null;
if (! empty($properties['createdate']) && strtotime($properties['createdate'])) {
$date = $this->parseCleanDatetime($properties['createdate']);
$remotelyCreatedAt = $date?->format('Y-m-d H:i:s');
}
$closedStages = $this->getClosedDealStages();
$isWon = in_array($properties['dealstage'], $closedStages['won']);
$isLost = in_array($properties['dealstage'], $closedStages['lost']);
$data = [
'team_id' => $this->team->getId(),
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => $name,
'value' => ! empty($amount) ? $amount : null,
'currency_code' => CurrencyFormatter::formatCode($currency),
'close_date' => $closeDate,
'is_closed' => $isWon || $isLost,
'is_won' => $isWon,
'remotely_created_at' => $remotelyCreatedAt,
'probability' => $this->resolveDealProbability($properties['hs_deal_stage_probability']),
'forecast_category' => $this->resolveForecastCategory($properties['hs_manual_forecast_category']),
];
if ($accountId) {
$data['account_id'] = $accountId;
}
if ($stage) {
$data['stage_id'] = $stage->id;
}
if ($businessProcess) {
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
if (isset($this->cachedBusinessProcesses[$pipelineId])) {
return $this->cachedBusinessProcesses[$pipelineId];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$pipelineId] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $businessProcess->getId() . ':' . $stageId;
if (isset($this->cachedStages[$cacheKey])) {
return $this->cachedStages[$cacheKey];
}
$stage = $this->crmEntityRepository->getPipelineStageByConditions(
$businessProcess,
[
'crm_provider_id' => $stageId,
'type' => Stage::TYPE_OPPORTUNITY,
]
);
if ($stage === null) {
$this->importStages(null, $stageId);
}
if ($stage === null) {
$this->logger->info('[HubSpot] Stage does not exist => ' . $stageId);
}
$this->cachedStages[$cacheKey] = $stage;
return $stage;
}
private function resolveAmount(array $properties): ?string
{
$amount = null;
if (! empty($properties['amount'])) {
$amount = str_replace(',', '', $properties['amount']);
}
if ($this->config->hasDefaultCurrencyFieldSet()) {
$valueFieldName = $this->config->getDefaultCurrencyField()->getCrmProviderId();
$amount = $properties[$valueFieldName] ?? $amount;
}
return $amount;
}
private function parseCleanDatetime(string $datetime): ?Carbon
{
// Treat pre-1980 values as invalid
$minValidDate = Carbon::parse('1980-01-01 00:00:00');
try {
$date = Carbon::parse($datetime);
if ($minValidDate->gt($date)) {
return null;
}
return $date;
} catch (Exception) {
return null; // On parse error, treat as null
}
}
private function resolveDealProbability(?string $stageProbability): int
{
if ($stageProbability === null) {
return 0;
}
$probability = (float) $stageProbability;
return $probability > 1 ? 0 : (int) ($probability * 100);
}
private function resolveForecastCategory(?string $forecastCategory): string
{
if (! $forecastCategory) {
return Forecast::FORECAST_CATEGORY_UNCATEGORIZED;
}
$forecastCategory = str_replace('_', ' ', $forecastCategory);
return ucwords(strtolower($forecastCategory));
}
private function importExternalFieldData(array $properties, int $opportunityId): void
{
$crmFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData($properties, $crmFields, $opportunityId);
}
private function importOpportunityContacts(Opportunity $opportunity, array $associations): void
{
// Handle empty or missing contact associations
if (empty($associations)) {
// Remove all existing contact associations if none provided
$this->removeAllOpportunityContacts($opportunity);
return;
}
// Use differential sync approach for better performance and accuracy
$this->syncOpportunityContactsDifferential($opportunity, $associations);
}
/**
* Sync opportunity contacts using differential approach
* This compares current vs new associations and only makes necessary changes
*/
private function syncOpportunityContactsDifferential(Opportunity $opportunity, array $contactAssociations): void
{
$currentContactCrmIds = $this->getCurrentContactCrmIds($opportunity);
$contactAssociationIds = array_keys($contactAssociations);
$contactsToAdd = array_diff($contactAssociationIds, $currentContactCrmIds);
$contactsToRemove = array_diff($currentContactCrmIds, $contactAssociationIds);
if (empty($contactsToAdd) && empty($contactsToRemove)) {
return;
}
$this->logContactAssociationChanges($opportunity, $currentContactCrmIds, $contactAssociations, $contactsToAdd, $contactsToRemove);
$this->removeContactAssociations($opportunity, $contactsToRemove);
$this->addContactAssociations($opportunity, $contactsToAdd, $contactAssociations);
}
private function getCurrentContactCrmIds(Opportunity $opportunity): array
{
return $opportunity->contacts()
->pluck('contacts.crm_provider_id')
->toArray();
}
private function logContactAssociationChanges(
Opportunity $opportunity,
array $currentContactCrmIds,
array $contactAssociations,
array $contactsToAdd,
array $contactsToRemove
): void {
$this->logger->info('[' . $this->getDisplayName() . '] Contact association changes', [
'opportunity_id' => $opportunity->getId(),
'current_contacts' => $currentContactCrmIds,
'new_contacts' => $contactAssociations,
'contacts_to_add' => $contactsToAdd,
'contacts_to_remove' => $contactsToRemove,
]);
}
private function removeContactAssociations(Opportunity $opportunity, array $contactsToRemove): void
{
if (empty($contactsToRemove)) {
return;
}
$contactsToDetach = $opportunity->contacts()
->whereIn('contacts.crm_provider_id', $contactsToRemove)
->pluck('contacts.id')
->toArray();
if (! empty($contactsToDetach)) {
$opportunity->contacts()->detach($contactsToDetach);
$this->logger->info('[' . $this->getDisplayName() . '] Removed contact associations', [
'opportunity_id' => $opportunity->getId(),
'removed_contact_crm_ids' => $contactsToRemove,
'removed_contact_count' => count($contactsToDetach),
]);
}
}
private function addContactAssociations(Opportunity $opportunity, array $contactsToAdd, array $contactAssociations): void
{
if (empty($contactsToAdd)) {
return;
}
$contactsAdded = [];
foreach ($contactsToAdd as $crmId) {
$id = $contactAssociations[$crmId];
if ($this->attachSingleContact($opportunity, (string) $crmId, $id)) {
$contactsAdded[] = $crmId;
}
}
$this->logAddedContacts($opportunity, $contactsAdded);
}
private function attachSingleContact(Opportunity $opportunity, string $crmId, int $id): bool
{
try {
$contact = $this->crmEntityRepository->findContactByConfigurationAndId($this->config, $id);
if (! $contact) {
return false;
}
return $this->performContactAttachment($opportunity, $contact, $crmId);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to add contact association', [
'opportunity_id' => $opportunity->getId(),
'contact_crm_id' => $crmId,
'error' => $e->getMessage(),
]);
return false;
}
}
private function performContactAttachment(Opportunity $opportunity, Contact $contact, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contact->getId(), [
'crm_provider_id' => $crmId,
]);
return true;
} catch (\Illuminate\Database\QueryException $e) {
if (str_contains($e->getMessage(), 'Duplicate entry')) {
$this->logger->info('[' . $this->getDisplayName() . '] Contact association already exists', [
'contact_id' => $contact->getId(),
'contact_crm_id' => $crmId,
'opportunity_id' => $opportunity->getId(),
]);
return false;
}
throw $e;
}
}
private function logAddedContacts(Opportunity $opportunity, array $contactsAdded): void
{
if (! empty($contactsAdded)) {
$this->logger->info('[' . $this->getDisplayName() . '] Added contact associations', [
'opportunity_id' => $opportunity->getId(),
'contacts_to_add_count' => count($contactsAdded),
'added_contact_crm_ids' => $contactsAdded,
'added_contacts_count' => count($contactsAdded),
]);
}
}
}
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...
|
NULL
|
|
44533
|
NULL
|
0
|
2026-04-17T08:51:30.893660+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776415890893_m1.jpg...
|
PhpStorm
|
faVsco.js – console [EU]
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
"podcast_audio_url"
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
0 results
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Code changed:
Hide
Sync Changes
Hide This Notification
32
2
19
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\ServiceTraits;
use Carbon\Carbon;
use HubSpot\Client\Crm\Deals\Model\CollectionResponseAssociatedId;
use Jiminny\Exceptions\InvalidArgumentException;
use Jiminny\Models\Account;
use Exception;
use Jiminny\Component\DealInsights\Forecast\Forecast;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Exceptions\CrmException;
use Jiminny\Models\Opportunity;
use Illuminate\Support\Collection;
use Jiminny\Models\Stage;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Services\Crm\Hubspot\DealFieldsService;
use Jiminny\Services\Crm\Hubspot\OpportunitySyncStrategy\HubspotSingleSyncStrategy;
use Jiminny\Services\Crm\Hubspot\WebhookSyncBatchProcessor;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
/**
* Optimized sync methods for better performance
* These methods can be integrated into SyncCrmEntitiesTrait for significant performance gains
*/
trait OpportunitySyncTrait
{
private const int BATCH_SIZE = 100;
private const int BATCH_PROCESS_SIZE = 800;
protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
protected CrmEntityRepository $crmEntityRepository;
protected DealFieldsService $dealFieldsService;
private ?array $cachedClosedDealStages = null;
private array $cachedBusinessProcesses = [];
private array $cachedStages = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' .
$strategyName
);
$total = 0;
$lastId = null;
$buffer = [];
// HubspotWebhookBatchSyncStrategy returns empty generator, this is for other strategies
foreach ($syncStrategy->fetchOpportunities($parameters, $total, $lastId) as $hsOpportunity) {
$buffer[] = $hsOpportunity;
// process every 800 rows (fits < 1 000 association limit)
if (\count($buffer) >= self::BATCH_PROCESS_SIZE) {
$syncCount += $this->processOpportunityBatch($buffer);
$buffer = [];
}
}
// leftovers
if ($buffer) {
$syncCount += $this->processOpportunityBatch($buffer);
}
$reportedTotal += $total;
$lastSyncedId = $lastId;
}
} catch (\HubSpot\Client\Crm\Deals\ApiException | CrmException $e) {
$this->handleSyncException($e, $parameters);
}
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
]
);
return $reportedTotal;
}
private function handleSyncException(\Throwable $e, array $parameters): void
{
if (($parameters['since'] ?? null) instanceof Carbon) {
$parameters['since'] = $parameters['since']->toDateTimeString();
}
$parameters['config'] = $this->config->getId();
$this->logger->warning('[' . $this->getDisplayName() . '] Sync opportunities failed', [
'teamId' => $this->team->getUuid(),
'parameters' => $parameters,
'reason' => $e->getMessage(),
]);
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,
);
$parameters = [
'config' => $this->config,
'crm_id' => $crmId,
];
try {
if (! $strategy instanceof HubspotSingleSyncStrategy) {
throw new InvalidArgumentException('Strategy must by HubspotSingleSyncStrategy');
}
$hsOpportunity = $strategy->fetchOpportunity($parameters);
} catch (\HubSpot\Client\Crm\Deals\ApiException $e) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [
'teamId' => $this->team->getUuid(),
'crmId' => $crmId,
'reason' => $e->getMessage(),
]);
return null;
}
$hsOpportunity['associations'] = $this->convertDealAssociations($hsOpportunity['associations'] ?? []);
return $this->importOrUpdateOpportunity($hsOpportunity);
}
/**
* Process webhook-collected opportunity batches.
*
* Drains Redis sets containing company CRM IDs collected from webhook events
* and dispatches ImportOpportunityBatch jobs for batch processing.
*
* @return int Number of opportunity IDs dispatched to jobs
*/
public function batchSyncOpportunities(): int
{
$configId = $this->team->getCrmConfiguration()->getId();
return $this->batchProcessor->processBatchesForObjectType(
WebhookSyncBatchProcessor::OBJECT_TYPE_DEAL,
$configId
);
}
/**
* Import a batch of opportunities by their CRM IDs.
* Fetches opportunity data from HubSpot API and delegates to importOpportunityBatch().
*
* @param array<string> $crmIds HubSpot deal CRM IDs
*
* @return array{success: array, failed_ids: array, errors?: array<string, string>}
*/
public function importOpportunityBatchByIds(array $crmIds): array
{
$fields = $this->dealFieldsService->getFieldsForConfiguration($this->config);
$allDeals = [];
foreach (array_chunk($crmIds, self::BATCH_SIZE) as $chunk) {
$deals = $this->client->getOpportunitiesByIds($chunk, $fields);
foreach ($deals as $deal) {
$allDeals[] = $deal;
}
}
// IDs not returned by HubSpot are likely deleted or inaccessible deals.
// These are not failures — retrying won't bring them back.
$fetchedIds = array_map('strval', array_column($allDeals, 'id'));
$notFoundIds = array_values(array_diff(array_map('strval', $crmIds), $fetchedIds));
if (! empty($notFoundIds)) {
$this->logger->info('[' . $this->getDisplayName() . '] CRM IDs not found in HubSpot (likely deleted)', [
'teamId' => $this->team->getId(),
'notFoundCount' => \count($notFoundIds),
'notFoundIds' => $notFoundIds,
'requestedCount' => \count($crmIds),
'fetchedCount' => \count($allDeals),
]);
}
if (empty($allDeals)) {
return ['success' => [], 'failed_ids' => []];
}
return $this->importOpportunityBatch($allDeals);
}
private function getClosedDealStages(): array
{
if ($this->cachedClosedDealStages !== null) {
return $this->cachedClosedDealStages;
}
$stages = $this->crmEntityRepository->getOpportunityClosedStages($this->config);
$data = [
'lost' => [],
'won' => [],
];
foreach ($stages as $stage) {
if ($stage->probability == 0.00) {
$data['lost'][] = $stage->crm_provider_id;
}
if ($stage->probability == 100.00) {
$data['won'][] = $stage->crm_provider_id;
}
}
$this->cachedClosedDealStages = $data;
return $data;
}
/**
* Import deals into the database with pre-fetched associations.
*
* API calls here (getAssociationsData, getExistingOpportunityCrmIds) are NOT
* caught — if they throw, the exception propagates to ImportOpportunityBatch::handle()
* where Laravel retries the whole job with backoff. After all retries exhausted,
* failed() requeues all IDs to Redis.
*
* The per-deal loop catches exceptions individually. A deal can end up in three states:
* - success: imported/updated successfully
* - failed_ids: exception thrown (DB constraint violation, corrupt data, etc.)
* These are permanent issues — retrying won't fix them.
* - skipped (null): missing dependencies (no account, unknown pipeline/stage).
* This is acceptable — the deal cannot be imported until those exist.
*/
private function importOpportunityBatch(array $deals): array
{
$syncedOpportunities = [
'success' => [],
'failed_ids' => [],
];
$dealIds = array_column($deals, 'id');
// Shared association/existing-ID preparation is batch-level state. If it fails, rethrow so the
// queue job retries the whole batch and eventually requeues all deal IDs back to Redis.
try {
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$associationsData = $this->prepareAssociatedEntities($companyAssociations, $contactAssociations);
$existingCrmIds = $this->crmEntityRepository->getExistingOpportunityCrmIds(
$this->config,
array_map('strval', $dealIds)
);
$existingCrmIdSet = array_flip($existingCrmIds);
} catch (\Throwable $e) {
$this->logger->error('[' . $this->getDisplayName() . '] Failed to fetch associations or existing IDs', [
'teamId' => $this->team->getId(),
'dealCount' => count($dealIds),
'error' => $e->getMessage(),
]);
throw $e;
}
foreach ($deals as $deal) {
try {
$deal['associations'] = $this->prepareAssociationsForOpportunity(
$deal['id'],
$companyAssociations,
$contactAssociations,
$associationsData
);
$syncedOpportunity = $this->importOrUpdateOpportunity(
$deal,
isset($existingCrmIdSet[(string) $deal['id']])
);
if ($syncedOpportunity) {
$syncedOpportunities['success'][] = $syncedOpportunity;
}
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to import opportunity', [
'teamId' => $this->team->getId(),
'crmId' => $deal['id'],
'error' => $e->getMessage(),
]);
$syncedOpportunities['failed_ids'][] = $deal['id'];
$syncedOpportunities['errors'][$deal['id']] = $e->getMessage();
}
}
return $syncedOpportunities;
}
/**
* Prepare associated entities for opportunities with optimized batch processing
* Returns structured data with CRM ID to DB ID mappings for each opportunity
*/
private function prepareAssociatedEntities(array $companyAssociations, array $contactAssociations): array
{
// Step 1: Collect all unique company and contact IDs from associations
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
// Step 2: Batch sync missing entities and get CRM ID to DB ID mappings
$companyIdMappings = [];
$contactIdMappings = [];
if (! empty($allCompanyIds)) {
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
}
if (! empty($allContactIds)) {
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
}
return [
'company_id_mappings' => $companyIdMappings,
'contact_id_mappings' => $contactIdMappings,
];
}
/**
* Flatten association data to get unique IDs
*/
private function flattenAssociationIds(array $associations): array
{
$ids = [];
foreach ($associations as $dealAssociations) {
if (is_array($dealAssociations)) {
foreach ($dealAssociations as $id) {
$ids[$id] = true;
}
}
}
return array_keys($ids);
}
/**
* Batch sync missing accounts
*/
private function prepareAssociatedAccounts(array $companyIds): array
{
// Find which accounts already exist
$existingAccounts = $this->crmEntityRepository
->findAccountsByExternalIds($this->config, $companyIds);
$existingCompanyIds = $existingAccounts->pluck('crm_provider_id')->toArray();
$existingAccountsData = $existingAccounts->mapWithKeys(function ($account) {
return [$account->getCrmProviderId() => $account->getId()];
})->toArray();
$missingCompanyIds = array_diff($companyIds, $existingCompanyIds);
if (empty($missingCompanyIds)) {
return $existingAccountsData;
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing accounts', [
'teamId' => $this->team->getUuid(),
'total_companies' => count($companyIds),
'existing_companies' => count($existingCompanyIds),
'missing_companies' => count($missingCompanyIds),
]);
// we already have limit on opportunity ids count
// Initialize variable before try block
$syncedAccountsData = [];
try {
$syncedAccountsData = $this->batchSyncCrmObjects('companies', $missingCompanyIds);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing accounts', [
'size' => count($missingCompanyIds),
'error' => $e->getMessage(),
]);
$syncedAccountsData = [];
}
return $existingAccountsData + $syncedAccountsData;
}
/**
* Prepare associated contacts - find existing and sync missing ones
* Returns mapping of CRM ID to DB ID
*/
private function prepareAssociatedContacts(array $contactIds): array
{
// Find which contacts already exist
$existingContacts = $this->crmEntityRepository
->findContactsByExternalIds($this->config, $contactIds);
$existingContactIds = $existingContacts->pluck('crm_provider_id')->toArray();
// Create mapping for existing contacts
$existingContactsData = $existingContacts->mapWithKeys(function ($contact) {
return [$contact->getCrmProviderId() => $contact->getId()];
})->toArray();
$missingContactIds = array_diff($contactIds, $existingContactIds);
if (empty($missingContactIds)) {
return $existingContactsData;
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing contacts', [
'teamId' => $this->team->getUuid(),
'total_contacts' => count($contactIds),
'existing_contacts' => count($existingContactIds),
'missing_contacts' => count($missingContactIds),
]);
// Sync missing contacts using batch API
try {
$syncedContactsData = $this->batchSyncCrmObjects('contacts', $missingContactIds);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing contacts', [
'size' => count($missingContactIds),
'error' => $e->getMessage(),
]);
$syncedContactsData = [];
}
return $existingContactsData + $syncedContactsData;
}
private function batchSyncCrmObjects(string $objectType, array $crmIds): array
{
$syncObjects = [];
$crmObjectIds = array_values($crmIds);
foreach (array_chunk($crmObjectIds, self::BATCH_SIZE) as $chunk) {
try {
$objects = $objectType === 'companies' ?
$this->client->getCompaniesByIds($chunk, $this->getCompanyFields()) :
$this->client->getContactsByIds($chunk, $this->getContactFields());
foreach ($objects as $objectId => $objectData) {
$this->importCrmObject($objectType, (string) $objectId, $objectData, $syncObjects);
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch synced ' . $objectType, [
'requested_count' => count($chunk),
'synced_count' => count($objects),
]);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Batch ' . $objectType . ' sync failed', [
'ids' => $chunk,
'error' => $e->getMessage(),
]);
}
}
return $syncObjects;
}
private function importCrmObject(string $objectType, string $objectId, mixed $objectData, array &$syncObjects): void
{
try {
$object = $objectType === 'companies' ?
$this->importAccount($objectData) :
$this->importContact($objectData);
if ($object) {
$syncObjects[$object->getCrmProviderId()] = $object->getId();
}
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to import batch ' . $objectType, [
'id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
/**
* Prepare associations for a single opportunity
*
* The return value is an array with the following structure:
* [
* 'companies' => [
* $companyCrmId => $companyId,
* ...
* ],
* 'contacts' => [
* $contactCrmId => $contactId,
* ...
* ],
* 'account_id' => $accountId,
* ]
*/
private function prepareAssociationsForOpportunity(
string $oppCrmId,
array $companyAssociations,
array $contactAssociations,
array $associationsData
): array {
$associations = [
'companies' => [],
'contacts' => [],
'account_id' => null, // Primary account for opportunity
];
$oppCompanyIds = $companyAssociations[$oppCrmId] ?? [];
foreach ($oppCompanyIds as $companyCrmId) {
if (isset($associationsData['company_id_mappings'][$companyCrmId])) {
$associations['companies'][$companyCrmId] = $associationsData['company_id_mappings'][$companyCrmId];
// Set primary account (first company becomes primary account)
if ($associations['account_id'] === null) {
$associations['account_id'] = $associationsData['company_id_mappings'][$companyCrmId];
}
}
}
$oppContactIds = $contactAssociations[$oppCrmId] ?? [];
foreach ($oppContactIds as $contactCrmId) {
if (isset($associationsData['contact_id_mappings'][$contactCrmId])) {
$associations['contacts'][$contactCrmId] = $associationsData['contact_id_mappings'][$contactCrmId];
}
}
return $associations;
}
/**
* Update only associations for an opportunity
*/
private function updateOpportunityAssociations(Opportunity $opportunity, array $associations): void
{
// Update contact associations
$this->importOpportunityContacts($opportunity, $associations['contacts']);
// Update company (account) associations
$this->updateOpportunityAccount($opportunity, $associations['account_id']);
}
/**
* Remove all contact associations from an opportunity
*/
private function removeAllOpportunityContacts(Opportunity $opportunity): void
{
$currentCount = (int) $opportunity->contacts()->count();
if ($currentCount > 0) {
$opportunity->contacts()->detach();
$this->logger->info('[' . $this->getDisplayName() . '] Removed all contact associations', [
'opportunity_id' => $opportunity->getId(),
'removed_count' => $currentCount,
]);
}
}
private function updateOpportunityAccount(Opportunity $opportunity, ?int $accountId): void
{
if ($accountId === null) {
// No account ID provided - keep current account
return;
}
$currentAccountId = $opportunity->getAccountId();
// Only update if account has changed
if ($currentAccountId !== $accountId) {
$opportunity->account_id = $accountId;
$opportunity->save();
$this->logger->info('[' . $this->getDisplayName() . '] Updated opportunity account association', [
'opportunity_id' => $opportunity->getId(),
'old_account_id' => $currentAccountId,
'new_account_id' => $accountId,
]);
}
}
/**
* Find existing opportunities by external IDs (OPTIMIZED VERSION)
* Uses batch query for better performance
*/
private function findExistingOpportunities(array $crmIds): Collection
{
return $this->crmEntityRepository
->findOpportunitiesByExternalIds($this->config, $crmIds);
}
private function processOpportunityBatch(array $opportunities): int
{
$syncedOpportunities = $this->importOpportunityBatch($opportunities);
return count($syncedOpportunities['success'] ?? []);
}
/**
* Convert single deal associations from HubSpot format to internal format
* Handles both HubSpot SDK objects and array formats
*
* @param array $opportunityAssociations Raw associations from HubSpot API or pre-processed
*
* @return array Processed associations with DB IDs
*/
private function convertDealAssociations(array $opportunityAssociations): array
{
$associations = $this->initializeAssociationsStructure();
if (empty($opportunityAssociations)) {
return $associations;
}
$associationIds = $this->extractAssociationIds($opportunityAssociations);
$this->processCompanyAssociations($associationIds, $associations);
$this->processContactAssociations($associationIds, $associations);
return $associations;
}
private function initializeAssociationsStructure(): array
{
return [
'companies' => [],
'contacts' => [],
'account_id' => null, // Primary account for opportunity
];
}
private function extractAssociationIds(array $opportunityAssociations): array
{
$associationIds = [];
foreach ($opportunityAssociations as $type => $associationData) {
if (! empty($associationData)) {
$associationIds[$type] = $this->convertSingleDealAssociations($associationData);
}
}
return $associationIds;
}
private function processCompanyAssociations(array $associationIds, array &$associations): void
{
if (empty($associationIds['companies'])) {
return;
}
$companyId = $associationIds['companies'][0];
$account = $this->findOrSyncAccount($companyId);
if ($account instanceof Account) {
$associations['companies'][$companyId] = $account->getId();
$associations['account_id'] = $account->getId();
}
}
private function processContactAssociations(array $associationIds, array &$associations): void
{
if (empty($associationIds['contacts'])) {
return;
}
foreach ($associationIds['contacts'] as $contactId) {
$contact = $this->findOrSyncContact($contactId);
if ($contact instanceof Contact) {
$associations['contacts'][$contactId] = $contact->getId();
}
}
}
private function findOrSyncAccount(string $companyId): ?Account
{
$account = $this->crmEntityRepository->findAccountByExternalId($this->config, $companyId);
if (! $account instanceof Account) {
$account = $this->syncAccount($companyId);
}
return $account;
}
private function findOrSyncContact(string $contactId): ?Contact
{
$contact = $this->crmEntityRepository->findContactByExternalId($this->config, $contactId);
if (! $contact instanceof Contact) {
$contact = $this->syncContact($contactId);
}
return $contact;
}
private function convertSingleDealAssociations($opportunityAssociations = null): array
{
$associationData = [];
if ($opportunityAssociations === null) {
return $associationData;
}
// Handle array input (from extractAssociationIds)
if (is_array($opportunityAssociations)) {
return $opportunityAssociations;
}
// Handle CollectionResponseAssociatedId object
if ($opportunityAssociations instanceof CollectionResponseAssociatedId) {
foreach ($opportunityAssociations->getResults() as $association) {
$associationData[] = $association->getId();
}
}
return $associationData;
}
private function importOrUpdateOpportunity($crmData, ?bool $exists = null): ?Opportunity
{
if (empty($crmData['properties'])) {
return null;
}
$crmId = (string) $crmData['id'];
$properties = $crmData['properties'];
$associations = $crmData['associations'] ?? [];
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity($crmId, $properties, $associations);
} else {
return $this->createOpportunity($crmId, $properties, $associations);
}
}
/**
* Create new opportunity
*/
private function createOpportunity(string $crmId, array $properties, array $associations): ?Opportunity
{
$accountId = $this->resolveAccountId($associations);
if (! $accountId) {
return null;
}
$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);
if (! $businessProcess) {
return null;
}
$stage = $this->resolveStage($businessProcess, $properties['dealstage'] ?? null);
if (! $stage) {
return null;
}
$data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);
$attributes = [
'crm_configuration_id' => $this->config->getId(),
'crm_provider_id' => $crmId,
];
$values = array_merge($attributes, $data);
$opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);
$this->importExternalFieldData($properties, $opportunity->getId());
$this->importOpportunityContacts($opportunity, $associations['contacts']);
if ($opportunity->wasRecentlyCreated) {
MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());
}
return $opportunity;
}
/**
* Update existing opportunity
*/
private function updateOpportunity(string $crmId, array $properties, array $associations): Opportunity
{
$accountId = $this->resolveAccountId($associations);
$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);
$stage = $businessProcess ? $this->resolveStage($businessProcess, $properties['dealstage'] ?? null) : null;
$data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);
$attributes = [
'crm_configuration_id' => $this->config->getId(),
'crm_provider_id' => $crmId,
];
$values = array_merge($attributes, $data);
$opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);
$this->importExternalFieldData($properties, $opportunity->getId());
$this->updateOpportunityAssociations($opportunity, $associations);
return $opportunity;
}
private function resolveAccountId(array $associations): ?int
{
if (! empty($associations['accountId'])) {
return $associations['accountId'];
}
if (empty($associations)) {
return null;
}
// we can't resolve multiple account ids (currently SDK returns one company)
foreach ($associations['companies'] as $accountId) {
return $accountId;
}
return null;
}
private function buildOpportunityData(
array $properties,
?int $accountId,
?BusinessProcess $businessProcess,
?Stage $stage
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, (string) $ownerId);
}
$name = 'Unknown';
if (isset($properties['dealname'])) {
$name = mb_strimwidth($properties['dealname'], 0, 128);
}
$amount = $this->resolveAmount($properties);
$currency = $properties['deal_currency_code'] ?? null;
$closeDate = null;
if (! empty($properties['closedate'])) {
$closeDate = Carbon::parse($properties['closedate'])->format('Y-m-d');
}
$remotelyCreatedAt = null;
if (! empty($properties['createdate']) && strtotime($properties['createdate'])) {
$date = $this->parseCleanDatetime($properties['createdate']);
$remotelyCreatedAt = $date?->format('Y-m-d H:i:s');
}
$closedStages = $this->getClosedDealStages();
$isWon = in_array($properties['dealstage'], $closedStages['won']);
$isLost = in_array($properties['dealstage'], $closedStages['lost']);
$data = [
'team_id' => $this->team->getId(),
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => $name,
'value' => ! empty($amount) ? $amount : null,
'currency_code' => CurrencyFormatter::formatCode($currency),
'close_date' => $closeDate,
'is_closed' => $isWon || $isLost,
'is_won' => $isWon,
'remotely_created_at' => $remotelyCreatedAt,
'probability' => $this->resolveDealProbability($properties['hs_deal_stage_probability']),
'forecast_category' => $this->resolveForecastCategory($properties['hs_manual_forecast_category']),
];
if ($accountId) {
$data['account_id'] = $accountId;
}
if ($stage) {
$data['stage_id'] = $stage->id;
}
if ($businessProcess) {
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
if (isset($this->cachedBusinessProcesses[$pipelineId])) {
return $this->cachedBusinessProcesses[$pipelineId];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$pipelineId] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $businessProcess->getId() . ':' . $stageId;
if (isset($this->cachedStages[$cacheKey])) {
return $this->cachedStages[$cacheKey];
}
$stage = $this->crmEntityRepository->getPipelineStageByConditions(
$businessProcess,
[
'crm_provider_id' => $stageId,
'type' => Stage::TYPE_OPPORTUNITY,
]
);
if ($stage === null) {
$this->importStages(null, $stageId);
}
if ($stage === null) {
$this->logger->info('[HubSpot] Stage does not exist => ' . $stageId);
}
$this->cachedStages[$cacheKey] = $stage;
return $stage;
}
private function resolveAmount(array $properties): ?string
{
$amount = null;
if (! empty($properties['amount'])) {
$amount = str_replace(',', '', $properties['amount']);
}
if ($this->config->hasDefaultCurrencyFieldSet()) {
$valueFieldName = $this->config->getDefaultCurrencyField()->getCrmProviderId();
$amount = $properties[$valueFieldName] ?? $amount;
}
return $amount;
}
private function parseCleanDatetime(string $datetime): ?Carbon
{
// Treat pre-1980 values as invalid
$minValidDate = Carbon::parse('1980-01-01 00:00:00');
try {
$date = Carbon::parse($datetime);
if ($minValidDate->gt($date)) {
return null;
}
return $date;
} catch (Exception) {
return null; // On parse error, treat as null
}
}
private function resolveDealProbability(?string $stageProbability): int
{
if ($stageProbability === null) {
return 0;
}
$probability = (float) $stageProbability;
return $probability > 1 ? 0 : (int) ($probability * 100);
}
private function resolveForecastCategory(?string $forecastCategory): string
{
if (! $forecastCategory) {
return Forecast::FORECAST_CATEGORY_UNCATEGORIZED;
}
$forecastCategory = str_replace('_', ' ', $forecastCategory);
return ucwords(strtolower($forecastCategory));
}
private function importExternalFieldData(array $properties, int $opportunityId): void
{
$crmFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData($properties, $crmFields, $opportunityId);
}
private function importOpportunityContacts(Opportunity $opportunity, array $associations): void
{
// Handle empty or missing contact associations
if (empty($associations)) {
// Remove all existing contact associations if none provided
$this->removeAllOpportunityContacts($opportunity);
return;
}
// Use differential sync approach for better performance and accuracy
$this->syncOpportunityContactsDifferential($opportunity, $associations);
}
/**
* Sync opportunity contacts using differential approach
* This compares current vs new associations and only makes necessary changes
*/
private function syncOpportunityContactsDifferential(Opportunity $opportunity, array $contactAssociations): void
{
$currentContactCrmIds = $this->getCurrentContactCrmIds($opportunity);
$contactAssociationIds = array_keys($contactAssociations);
$contactsToAdd = array_diff($contactAssociationIds, $currentContactCrmIds);
$contactsToRemove = array_diff($currentContactCrmIds, $contactAssociationIds);
if (empty($contactsToAdd) && empty($contactsToRemove)) {
return;
}
$this->logContactAssociationChanges($opportunity, $currentContactCrmIds, $contactAssociations, $contactsToAdd, $contactsToRemove);
$this->removeContactAssociations($opportunity, $contactsToRemove);
$this->addContactAssociations($opportunity, $contactsToAdd, $contactAssociations);
}
private function getCurrentContactCrmIds(Opportunity $opportunity): array
{
return $opportunity->contacts()
->pluck('contacts.crm_provider_id')
->toArray();
}
private function logContactAssociationChanges(
Opportunity $opportunity,
array $currentContactCrmIds,
array $contactAssociations,
array $contactsToAdd,
array $contactsToRemove
): void {
$this->logger->info('[' . $this->getDisplayName() . '] Contact association changes', [
'opportunity_id' => $opportunity->getId(),
'current_contacts' => $currentContactCrmIds,
'new_contacts' => $contactAssociations,
'contacts_to_add' => $contactsToAdd,
'contacts_to_remove' => $contactsToRemove,
]);
}
private function removeContactAssociations(Opportunity $opportunity, array $contactsToRemove): void
{
if (empty($contactsToRemove)) {
return;
}
$contactsToDetach = $opportunity->contacts()
->whereIn('contacts.crm_provider_id', $contactsToRemove)
->pluck('contacts.id')
->toArray();
if (! empty($contactsToDetach)) {
$opportunity->contacts()->detach($contactsToDetach);
$this->logger->info('[' . $this->getDisplayName() . '] Removed contact associations', [
'opportunity_id' => $opportunity->getId(),
'removed_contact_crm_ids' => $contactsToRemove,
'removed_contact_count' => count($contactsToDetach),
]);
}
}
private function addContactAssociations(Opportunity $opportunity, array $contactsToAdd, array $contactAssociations): void
{
if (empty($contactsToAdd)) {
return;
}
$contactsAdded = [];
foreach ($contactsToAdd as $crmId) {
$id = $contactAssociations[$crmId];
if ($this->attachSingleContact($opportunity, (string) $crmId, $id)) {
$contactsAdded[] = $crmId;
}
}
$this->logAddedContacts($opportunity, $contactsAdded);
}
private function attachSingleContact(Opportunity $opportunity, string $crmId, int $id): bool
{
try {
$contact = $this->crmEntityRepository->findContactByConfigurationAndId($this->config, $id);
if (! $contact) {
return false;
}
return $this->performContactAttachment($opportunity, $contact, $crmId);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to add contact association', [
'opportunity_id' => $opportunity->getId(),
'contact_crm_id' => $crmId,
'error' => $e->getMessage(),
]);
return false;
}
}
private function performContactAttachment(Opportunity $opportunity, Contact $contact, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contact->getId(), [
'crm_provider_id' => $crmId,
]);
return true;
} catch (\Illuminate\Database\QueryException $e) {
if (str_contains($e->getMessage(), 'Duplicate entry')) {
$this->logger->info('[' . $this->getDisplayName() . '] Contact association already exists', [
'contact_id' => $contact->getId(),
'contact_crm_id' => $crmId,
'opportunity_id' => $opportunity->getId(),
]);
return false;
}
throw $e;
}
}
private function logAddedContacts(Opportunity $opportunity, array $contactsAdded): void
{
if (! empty($contactsAdded)) {
$this->logger->info('[' . $this->getDisplayName() . '] Added contact associations', [
'opportunity_id' => $opportunity->getId(),
'contacts_to_add_count' => count($contactsAdded),
'added_contact_crm_ids' => $contactsAdded,
'added_contacts_count' => count($contactsAdded),
]);
}
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#11894 on JY-18909-automated-reports-ask-jiminny, menu","depth":5,"help_text":"Pull request #11894 exists for current branch JY-18909-automated-reports-ask-jiminny, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AutomatedReportsCommandTest","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AutomatedReportsCommandTest'","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AutomatedReportsCommandTest'","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Show Replace Field","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Search History","depth":3,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"\"podcast_audio_url\"","depth":4,"value":"\"podcast_audio_url\"","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"New Line","depth":3,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Match Case","depth":3,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Words","depth":3,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Regex","depth":3,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Replace History","depth":3,"bounds":{"left":0.0,"top":0.0,"width":0.015277778,"height":0.024444444},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextField","text":"Replace","depth":4,"role_description":"text field","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"New Line","depth":3,"bounds":{"left":0.0,"top":0.0,"width":0.015277778,"height":0.024444444},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Preserve case","depth":3,"bounds":{"left":0.0,"top":0.0,"width":0.015277778,"height":0.024444444},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"0 results","depth":4,"role_description":"text"},{"role":"AXButton","text":"Previous Occurrence","depth":4,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Occurrence","depth":4,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Filter Search Results","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open in Window, Multiple Cursors","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXLink","text":"Click to highlight","depth":4,"role_description":"link","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Close","depth":4,"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.0,"top":0.0,"width":0.088194445,"height":0.027777778},"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},"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},"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},"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"32","depth":4,"role_description":"text"},{"role":"AXStaticText","text":"2","depth":4,"role_description":"text"},{"role":"AXStaticText","text":"19","depth":4,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"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\\ServiceTraits;\n\nuse Carbon\\Carbon;\nuse HubSpot\\Client\\Crm\\Deals\\Model\\CollectionResponseAssociatedId;\nuse Jiminny\\Exceptions\\InvalidArgumentException;\nuse Jiminny\\Models\\Account;\nuse Exception;\nuse Jiminny\\Component\\DealInsights\\Forecast\\Forecast;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Models\\Opportunity;\nuse Illuminate\\Support\\Collection;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Services\\Crm\\Hubspot\\DealFieldsService;\nuse Jiminny\\Services\\Crm\\Hubspot\\OpportunitySyncStrategy\\HubspotSingleSyncStrategy;\nuse Jiminny\\Services\\Crm\\Hubspot\\WebhookSyncBatchProcessor;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\n\n/**\n * Optimized sync methods for better performance\n * These methods can be integrated into SyncCrmEntitiesTrait for significant performance gains\n */\ntrait OpportunitySyncTrait\n{\n private const int BATCH_SIZE = 100;\n private const int BATCH_PROCESS_SIZE = 800;\n\n protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n protected CrmEntityRepository $crmEntityRepository;\n protected DealFieldsService $dealFieldsService;\n\n private ?array $cachedClosedDealStages = null;\n private array $cachedBusinessProcesses = [];\n private array $cachedStages = [];\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n $parameters['config'] = $this->config;\n $syncCount = 0;\n $reportedTotal = 0;\n $lastSyncedId = [];\n\n try {\n foreach ($strategies as $strategyName => $syncStrategy) {\n $this->logger->info(\n '[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' .\n $strategyName\n );\n\n $total = 0;\n $lastId = null;\n $buffer = [];\n\n // HubspotWebhookBatchSyncStrategy returns empty generator, this is for other strategies\n foreach ($syncStrategy->fetchOpportunities($parameters, $total, $lastId) as $hsOpportunity) {\n $buffer[] = $hsOpportunity;\n\n // process every 800 rows (fits < 1 000 association limit)\n if (\\count($buffer) >= self::BATCH_PROCESS_SIZE) {\n $syncCount += $this->processOpportunityBatch($buffer);\n $buffer = [];\n }\n }\n\n // leftovers\n if ($buffer) {\n $syncCount += $this->processOpportunityBatch($buffer);\n }\n\n $reportedTotal += $total;\n $lastSyncedId = $lastId;\n }\n } catch (\\HubSpot\\Client\\Crm\\Deals\\ApiException | CrmException $e) {\n $this->handleSyncException($e, $parameters);\n }\n\n $this->logger->info(\n '[HubSpot] Synced opportunities',\n [\n 'team' => $this->team->getId(),\n 'sync_count' => $syncCount,\n 'total' => $reportedTotal,\n 'last_synced_id' => $lastSyncedId,\n ]\n );\n\n return $reportedTotal;\n }\n\n private function handleSyncException(\\Throwable $e, array $parameters): void\n {\n if (($parameters['since'] ?? null) instanceof Carbon) {\n $parameters['since'] = $parameters['since']->toDateTimeString();\n }\n $parameters['config'] = $this->config->getId();\n\n $this->logger->warning('[' . $this->getDisplayName() . '] Sync opportunities failed', [\n 'teamId' => $this->team->getUuid(),\n 'parameters' => $parameters,\n 'reason' => $e->getMessage(),\n ]);\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,\n );\n\n $parameters = [\n 'config' => $this->config,\n 'crm_id' => $crmId,\n ];\n\n try {\n if (! $strategy instanceof HubspotSingleSyncStrategy) {\n throw new InvalidArgumentException('Strategy must by HubspotSingleSyncStrategy');\n }\n\n $hsOpportunity = $strategy->fetchOpportunity($parameters);\n } catch (\\HubSpot\\Client\\Crm\\Deals\\ApiException $e) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [\n 'teamId' => $this->team->getUuid(),\n 'crmId' => $crmId,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n $hsOpportunity['associations'] = $this->convertDealAssociations($hsOpportunity['associations'] ?? []);\n\n return $this->importOrUpdateOpportunity($hsOpportunity);\n }\n\n /**\n * Process webhook-collected opportunity batches.\n *\n * Drains Redis sets containing company CRM IDs collected from webhook events\n * and dispatches ImportOpportunityBatch jobs for batch processing.\n *\n * @return int Number of opportunity IDs dispatched to jobs\n */\n public function batchSyncOpportunities(): int\n {\n $configId = $this->team->getCrmConfiguration()->getId();\n\n return $this->batchProcessor->processBatchesForObjectType(\n WebhookSyncBatchProcessor::OBJECT_TYPE_DEAL,\n $configId\n );\n }\n\n /**\n * Import a batch of opportunities by their CRM IDs.\n * Fetches opportunity data from HubSpot API and delegates to importOpportunityBatch().\n *\n * @param array<string> $crmIds HubSpot deal CRM IDs\n *\n * @return array{success: array, failed_ids: array, errors?: array<string, string>}\n */\n public function importOpportunityBatchByIds(array $crmIds): array\n {\n $fields = $this->dealFieldsService->getFieldsForConfiguration($this->config);\n\n $allDeals = [];\n foreach (array_chunk($crmIds, self::BATCH_SIZE) as $chunk) {\n $deals = $this->client->getOpportunitiesByIds($chunk, $fields);\n foreach ($deals as $deal) {\n $allDeals[] = $deal;\n }\n }\n\n // IDs not returned by HubSpot are likely deleted or inaccessible deals.\n // These are not failures — retrying won't bring them back.\n $fetchedIds = array_map('strval', array_column($allDeals, 'id'));\n $notFoundIds = array_values(array_diff(array_map('strval', $crmIds), $fetchedIds));\n\n if (! empty($notFoundIds)) {\n $this->logger->info('[' . $this->getDisplayName() . '] CRM IDs not found in HubSpot (likely deleted)', [\n 'teamId' => $this->team->getId(),\n 'notFoundCount' => \\count($notFoundIds),\n 'notFoundIds' => $notFoundIds,\n 'requestedCount' => \\count($crmIds),\n 'fetchedCount' => \\count($allDeals),\n ]);\n }\n\n if (empty($allDeals)) {\n return ['success' => [], 'failed_ids' => []];\n }\n\n return $this->importOpportunityBatch($allDeals);\n }\n\n private function getClosedDealStages(): array\n {\n if ($this->cachedClosedDealStages !== null) {\n return $this->cachedClosedDealStages;\n }\n\n $stages = $this->crmEntityRepository->getOpportunityClosedStages($this->config);\n $data = [\n 'lost' => [],\n 'won' => [],\n ];\n\n foreach ($stages as $stage) {\n if ($stage->probability == 0.00) {\n $data['lost'][] = $stage->crm_provider_id;\n }\n if ($stage->probability == 100.00) {\n $data['won'][] = $stage->crm_provider_id;\n }\n }\n\n $this->cachedClosedDealStages = $data;\n\n return $data;\n }\n\n /**\n * Import deals into the database with pre-fetched associations.\n *\n * API calls here (getAssociationsData, getExistingOpportunityCrmIds) are NOT\n * caught — if they throw, the exception propagates to ImportOpportunityBatch::handle()\n * where Laravel retries the whole job with backoff. After all retries exhausted,\n * failed() requeues all IDs to Redis.\n *\n * The per-deal loop catches exceptions individually. A deal can end up in three states:\n * - success: imported/updated successfully\n * - failed_ids: exception thrown (DB constraint violation, corrupt data, etc.)\n * These are permanent issues — retrying won't fix them.\n * - skipped (null): missing dependencies (no account, unknown pipeline/stage).\n * This is acceptable — the deal cannot be imported until those exist.\n */\n private function importOpportunityBatch(array $deals): array\n {\n $syncedOpportunities = [\n 'success' => [],\n 'failed_ids' => [],\n ];\n $dealIds = array_column($deals, 'id');\n\n // Shared association/existing-ID preparation is batch-level state. If it fails, rethrow so the\n // queue job retries the whole batch and eventually requeues all deal IDs back to Redis.\n try {\n $companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');\n $contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');\n\n $associationsData = $this->prepareAssociatedEntities($companyAssociations, $contactAssociations);\n\n $existingCrmIds = $this->crmEntityRepository->getExistingOpportunityCrmIds(\n $this->config,\n array_map('strval', $dealIds)\n );\n $existingCrmIdSet = array_flip($existingCrmIds);\n } catch (\\Throwable $e) {\n $this->logger->error('[' . $this->getDisplayName() . '] Failed to fetch associations or existing IDs', [\n 'teamId' => $this->team->getId(),\n 'dealCount' => count($dealIds),\n 'error' => $e->getMessage(),\n ]);\n\n throw $e;\n }\n\n foreach ($deals as $deal) {\n try {\n $deal['associations'] = $this->prepareAssociationsForOpportunity(\n $deal['id'],\n $companyAssociations,\n $contactAssociations,\n $associationsData\n );\n\n $syncedOpportunity = $this->importOrUpdateOpportunity(\n $deal,\n isset($existingCrmIdSet[(string) $deal['id']])\n );\n if ($syncedOpportunity) {\n $syncedOpportunities['success'][] = $syncedOpportunity;\n }\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to import opportunity', [\n 'teamId' => $this->team->getId(),\n 'crmId' => $deal['id'],\n 'error' => $e->getMessage(),\n ]);\n $syncedOpportunities['failed_ids'][] = $deal['id'];\n $syncedOpportunities['errors'][$deal['id']] = $e->getMessage();\n }\n }\n\n return $syncedOpportunities;\n }\n\n /**\n * Prepare associated entities for opportunities with optimized batch processing\n * Returns structured data with CRM ID to DB ID mappings for each opportunity\n */\n private function prepareAssociatedEntities(array $companyAssociations, array $contactAssociations): array\n {\n // Step 1: Collect all unique company and contact IDs from associations\n $allCompanyIds = $this->flattenAssociationIds($companyAssociations);\n $allContactIds = $this->flattenAssociationIds($contactAssociations);\n\n // Step 2: Batch sync missing entities and get CRM ID to DB ID mappings\n $companyIdMappings = [];\n $contactIdMappings = [];\n\n if (! empty($allCompanyIds)) {\n $companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);\n }\n\n if (! empty($allContactIds)) {\n $contactIdMappings = $this->prepareAssociatedContacts($allContactIds);\n }\n\n return [\n 'company_id_mappings' => $companyIdMappings,\n 'contact_id_mappings' => $contactIdMappings,\n ];\n }\n\n /**\n * Flatten association data to get unique IDs\n */\n private function flattenAssociationIds(array $associations): array\n {\n $ids = [];\n foreach ($associations as $dealAssociations) {\n if (is_array($dealAssociations)) {\n foreach ($dealAssociations as $id) {\n $ids[$id] = true;\n }\n }\n }\n\n return array_keys($ids);\n }\n\n /**\n * Batch sync missing accounts\n */\n private function prepareAssociatedAccounts(array $companyIds): array\n {\n // Find which accounts already exist\n $existingAccounts = $this->crmEntityRepository\n ->findAccountsByExternalIds($this->config, $companyIds);\n\n $existingCompanyIds = $existingAccounts->pluck('crm_provider_id')->toArray();\n\n $existingAccountsData = $existingAccounts->mapWithKeys(function ($account) {\n return [$account->getCrmProviderId() => $account->getId()];\n })->toArray();\n\n $missingCompanyIds = array_diff($companyIds, $existingCompanyIds);\n\n if (empty($missingCompanyIds)) {\n return $existingAccountsData;\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing accounts', [\n 'teamId' => $this->team->getUuid(),\n 'total_companies' => count($companyIds),\n 'existing_companies' => count($existingCompanyIds),\n 'missing_companies' => count($missingCompanyIds),\n ]);\n\n // we already have limit on opportunity ids count\n // Initialize variable before try block\n $syncedAccountsData = [];\n\n try {\n $syncedAccountsData = $this->batchSyncCrmObjects('companies', $missingCompanyIds);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing accounts', [\n 'size' => count($missingCompanyIds),\n 'error' => $e->getMessage(),\n ]);\n $syncedAccountsData = [];\n }\n\n return $existingAccountsData + $syncedAccountsData;\n }\n\n /**\n * Prepare associated contacts - find existing and sync missing ones\n * Returns mapping of CRM ID to DB ID\n */\n private function prepareAssociatedContacts(array $contactIds): array\n {\n // Find which contacts already exist\n $existingContacts = $this->crmEntityRepository\n ->findContactsByExternalIds($this->config, $contactIds);\n\n $existingContactIds = $existingContacts->pluck('crm_provider_id')->toArray();\n\n // Create mapping for existing contacts\n $existingContactsData = $existingContacts->mapWithKeys(function ($contact) {\n return [$contact->getCrmProviderId() => $contact->getId()];\n })->toArray();\n\n $missingContactIds = array_diff($contactIds, $existingContactIds);\n\n if (empty($missingContactIds)) {\n return $existingContactsData;\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing contacts', [\n 'teamId' => $this->team->getUuid(),\n 'total_contacts' => count($contactIds),\n 'existing_contacts' => count($existingContactIds),\n 'missing_contacts' => count($missingContactIds),\n ]);\n\n // Sync missing contacts using batch API\n try {\n $syncedContactsData = $this->batchSyncCrmObjects('contacts', $missingContactIds);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing contacts', [\n 'size' => count($missingContactIds),\n 'error' => $e->getMessage(),\n ]);\n $syncedContactsData = [];\n }\n\n return $existingContactsData + $syncedContactsData;\n }\n\n private function batchSyncCrmObjects(string $objectType, array $crmIds): array\n {\n $syncObjects = [];\n $crmObjectIds = array_values($crmIds);\n\n foreach (array_chunk($crmObjectIds, self::BATCH_SIZE) as $chunk) {\n try {\n $objects = $objectType === 'companies' ?\n $this->client->getCompaniesByIds($chunk, $this->getCompanyFields()) :\n $this->client->getContactsByIds($chunk, $this->getContactFields());\n\n foreach ($objects as $objectId => $objectData) {\n $this->importCrmObject($objectType, (string) $objectId, $objectData, $syncObjects);\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch synced ' . $objectType, [\n 'requested_count' => count($chunk),\n 'synced_count' => count($objects),\n ]);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Batch ' . $objectType . ' sync failed', [\n 'ids' => $chunk,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n return $syncObjects;\n }\n\n private function importCrmObject(string $objectType, string $objectId, mixed $objectData, array &$syncObjects): void\n {\n try {\n $object = $objectType === 'companies' ?\n $this->importAccount($objectData) :\n $this->importContact($objectData);\n\n if ($object) {\n $syncObjects[$object->getCrmProviderId()] = $object->getId();\n }\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to import batch ' . $objectType, [\n 'id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n /**\n * Prepare associations for a single opportunity\n *\n * The return value is an array with the following structure:\n * [\n * 'companies' => [\n * $companyCrmId => $companyId,\n * ...\n * ],\n * 'contacts' => [\n * $contactCrmId => $contactId,\n * ...\n * ],\n * 'account_id' => $accountId,\n * ]\n */\n private function prepareAssociationsForOpportunity(\n string $oppCrmId,\n array $companyAssociations,\n array $contactAssociations,\n array $associationsData\n ): array {\n $associations = [\n 'companies' => [],\n 'contacts' => [],\n 'account_id' => null, // Primary account for opportunity\n ];\n\n $oppCompanyIds = $companyAssociations[$oppCrmId] ?? [];\n foreach ($oppCompanyIds as $companyCrmId) {\n if (isset($associationsData['company_id_mappings'][$companyCrmId])) {\n $associations['companies'][$companyCrmId] = $associationsData['company_id_mappings'][$companyCrmId];\n\n // Set primary account (first company becomes primary account)\n if ($associations['account_id'] === null) {\n $associations['account_id'] = $associationsData['company_id_mappings'][$companyCrmId];\n }\n }\n }\n\n $oppContactIds = $contactAssociations[$oppCrmId] ?? [];\n foreach ($oppContactIds as $contactCrmId) {\n if (isset($associationsData['contact_id_mappings'][$contactCrmId])) {\n $associations['contacts'][$contactCrmId] = $associationsData['contact_id_mappings'][$contactCrmId];\n }\n }\n\n return $associations;\n }\n\n /**\n * Update only associations for an opportunity\n */\n private function updateOpportunityAssociations(Opportunity $opportunity, array $associations): void\n {\n // Update contact associations\n $this->importOpportunityContacts($opportunity, $associations['contacts']);\n\n // Update company (account) associations\n $this->updateOpportunityAccount($opportunity, $associations['account_id']);\n }\n\n /**\n * Remove all contact associations from an opportunity\n */\n private function removeAllOpportunityContacts(Opportunity $opportunity): void\n {\n $currentCount = (int) $opportunity->contacts()->count();\n\n if ($currentCount > 0) {\n $opportunity->contacts()->detach();\n\n $this->logger->info('[' . $this->getDisplayName() . '] Removed all contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'removed_count' => $currentCount,\n ]);\n }\n }\n\n private function updateOpportunityAccount(Opportunity $opportunity, ?int $accountId): void\n {\n if ($accountId === null) {\n // No account ID provided - keep current account\n return;\n }\n\n $currentAccountId = $opportunity->getAccountId();\n\n // Only update if account has changed\n if ($currentAccountId !== $accountId) {\n $opportunity->account_id = $accountId;\n $opportunity->save();\n\n $this->logger->info('[' . $this->getDisplayName() . '] Updated opportunity account association', [\n 'opportunity_id' => $opportunity->getId(),\n 'old_account_id' => $currentAccountId,\n 'new_account_id' => $accountId,\n ]);\n }\n }\n\n /**\n * Find existing opportunities by external IDs (OPTIMIZED VERSION)\n * Uses batch query for better performance\n */\n private function findExistingOpportunities(array $crmIds): Collection\n {\n return $this->crmEntityRepository\n ->findOpportunitiesByExternalIds($this->config, $crmIds);\n }\n\n private function processOpportunityBatch(array $opportunities): int\n {\n $syncedOpportunities = $this->importOpportunityBatch($opportunities);\n\n return count($syncedOpportunities['success'] ?? []);\n }\n\n /**\n * Convert single deal associations from HubSpot format to internal format\n * Handles both HubSpot SDK objects and array formats\n *\n * @param array $opportunityAssociations Raw associations from HubSpot API or pre-processed\n *\n * @return array Processed associations with DB IDs\n */\n private function convertDealAssociations(array $opportunityAssociations): array\n {\n $associations = $this->initializeAssociationsStructure();\n\n if (empty($opportunityAssociations)) {\n return $associations;\n }\n\n $associationIds = $this->extractAssociationIds($opportunityAssociations);\n\n $this->processCompanyAssociations($associationIds, $associations);\n $this->processContactAssociations($associationIds, $associations);\n\n return $associations;\n }\n\n private function initializeAssociationsStructure(): array\n {\n return [\n 'companies' => [],\n 'contacts' => [],\n 'account_id' => null, // Primary account for opportunity\n ];\n }\n\n private function extractAssociationIds(array $opportunityAssociations): array\n {\n $associationIds = [];\n\n foreach ($opportunityAssociations as $type => $associationData) {\n if (! empty($associationData)) {\n $associationIds[$type] = $this->convertSingleDealAssociations($associationData);\n }\n }\n\n return $associationIds;\n }\n\n private function processCompanyAssociations(array $associationIds, array &$associations): void\n {\n if (empty($associationIds['companies'])) {\n return;\n }\n\n $companyId = $associationIds['companies'][0];\n $account = $this->findOrSyncAccount($companyId);\n\n if ($account instanceof Account) {\n $associations['companies'][$companyId] = $account->getId();\n $associations['account_id'] = $account->getId();\n }\n }\n\n private function processContactAssociations(array $associationIds, array &$associations): void\n {\n if (empty($associationIds['contacts'])) {\n return;\n }\n\n foreach ($associationIds['contacts'] as $contactId) {\n $contact = $this->findOrSyncContact($contactId);\n\n if ($contact instanceof Contact) {\n $associations['contacts'][$contactId] = $contact->getId();\n }\n }\n }\n\n private function findOrSyncAccount(string $companyId): ?Account\n {\n $account = $this->crmEntityRepository->findAccountByExternalId($this->config, $companyId);\n\n if (! $account instanceof Account) {\n $account = $this->syncAccount($companyId);\n }\n\n return $account;\n }\n\n private function findOrSyncContact(string $contactId): ?Contact\n {\n $contact = $this->crmEntityRepository->findContactByExternalId($this->config, $contactId);\n\n if (! $contact instanceof Contact) {\n $contact = $this->syncContact($contactId);\n }\n\n return $contact;\n }\n\n private function convertSingleDealAssociations($opportunityAssociations = null): array\n {\n $associationData = [];\n\n if ($opportunityAssociations === null) {\n return $associationData;\n }\n\n // Handle array input (from extractAssociationIds)\n if (is_array($opportunityAssociations)) {\n return $opportunityAssociations;\n }\n\n // Handle CollectionResponseAssociatedId object\n if ($opportunityAssociations instanceof CollectionResponseAssociatedId) {\n foreach ($opportunityAssociations->getResults() as $association) {\n $associationData[] = $association->getId();\n }\n }\n\n return $associationData;\n }\n\n private function importOrUpdateOpportunity($crmData, ?bool $exists = null): ?Opportunity\n {\n if (empty($crmData['properties'])) {\n return null;\n }\n\n $crmId = (string) $crmData['id'];\n $properties = $crmData['properties'];\n $associations = $crmData['associations'] ?? [];\n\n $opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(\n $this->config,\n $crmId\n );\n\n if ($opportunityExists) {\n return $this->updateOpportunity($crmId, $properties, $associations);\n } else {\n return $this->createOpportunity($crmId, $properties, $associations);\n }\n }\n\n /**\n * Create new opportunity\n */\n private function createOpportunity(string $crmId, array $properties, array $associations): ?Opportunity\n {\n $accountId = $this->resolveAccountId($associations);\n if (! $accountId) {\n return null;\n }\n\n $businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);\n if (! $businessProcess) {\n return null;\n }\n\n $stage = $this->resolveStage($businessProcess, $properties['dealstage'] ?? null);\n if (! $stage) {\n return null;\n }\n\n $data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);\n\n $attributes = [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmId,\n ];\n\n $values = array_merge($attributes, $data);\n\n $opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);\n\n $this->importExternalFieldData($properties, $opportunity->getId());\n $this->importOpportunityContacts($opportunity, $associations['contacts']);\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n }\n\n /**\n * Update existing opportunity\n */\n private function updateOpportunity(string $crmId, array $properties, array $associations): Opportunity\n {\n $accountId = $this->resolveAccountId($associations);\n $businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);\n $stage = $businessProcess ? $this->resolveStage($businessProcess, $properties['dealstage'] ?? null) : null;\n\n $data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);\n\n $attributes = [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmId,\n ];\n\n $values = array_merge($attributes, $data);\n $opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);\n\n $this->importExternalFieldData($properties, $opportunity->getId());\n $this->updateOpportunityAssociations($opportunity, $associations);\n\n return $opportunity;\n }\n\n private function resolveAccountId(array $associations): ?int\n {\n if (! empty($associations['accountId'])) {\n return $associations['accountId'];\n }\n\n if (empty($associations)) {\n return null;\n }\n\n // we can't resolve multiple account ids (currently SDK returns one company)\n foreach ($associations['companies'] as $accountId) {\n return $accountId;\n }\n\n return null;\n }\n\n private function buildOpportunityData(\n array $properties,\n ?int $accountId,\n ?BusinessProcess $businessProcess,\n ?Stage $stage\n ): array {\n $ownerId = null;\n $profile = null;\n if (! empty($properties['hubspot_owner_id'])) {\n $ownerId = $properties['hubspot_owner_id'];\n $profile = $this->crmEntityRepository->findProfileByExternalId($this->config, (string) $ownerId);\n }\n\n $name = 'Unknown';\n if (isset($properties['dealname'])) {\n $name = mb_strimwidth($properties['dealname'], 0, 128);\n }\n\n $amount = $this->resolveAmount($properties);\n $currency = $properties['deal_currency_code'] ?? null;\n\n $closeDate = null;\n if (! empty($properties['closedate'])) {\n $closeDate = Carbon::parse($properties['closedate'])->format('Y-m-d');\n }\n\n $remotelyCreatedAt = null;\n if (! empty($properties['createdate']) && strtotime($properties['createdate'])) {\n $date = $this->parseCleanDatetime($properties['createdate']);\n $remotelyCreatedAt = $date?->format('Y-m-d H:i:s');\n }\n\n $closedStages = $this->getClosedDealStages();\n $isWon = in_array($properties['dealstage'], $closedStages['won']);\n $isLost = in_array($properties['dealstage'], $closedStages['lost']);\n\n $data = [\n 'team_id' => $this->team->getId(),\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => $name,\n 'value' => ! empty($amount) ? $amount : null,\n 'currency_code' => CurrencyFormatter::formatCode($currency),\n 'close_date' => $closeDate,\n 'is_closed' => $isWon || $isLost,\n 'is_won' => $isWon,\n 'remotely_created_at' => $remotelyCreatedAt,\n 'probability' => $this->resolveDealProbability($properties['hs_deal_stage_probability']),\n 'forecast_category' => $this->resolveForecastCategory($properties['hs_manual_forecast_category']),\n ];\n\n if ($accountId) {\n $data['account_id'] = $accountId;\n }\n\n if ($stage) {\n $data['stage_id'] = $stage->id;\n }\n\n if ($businessProcess) {\n $recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);\n if ($recordType) {\n $data['record_type_id'] = $recordType->id;\n }\n }\n\n return $data;\n }\n\n private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess\n {\n if ($pipelineId === null) {\n return null;\n }\n\n if (isset($this->cachedBusinessProcesses[$pipelineId])) {\n return $this->cachedBusinessProcesses[$pipelineId];\n }\n\n $businessProcess = $this->getBusinessProcess($pipelineId);\n\n if (! $businessProcess instanceof BusinessProcess) {\n $this->importStages();\n $businessProcess = $this->getBusinessProcess($pipelineId);\n }\n\n if (! $businessProcess instanceof BusinessProcess) {\n $this->logger->info(\n '[HubSpot] Deal is not attached to a pipeline',\n [\n 'pipeline' => $pipelineId]\n );\n }\n\n $this->cachedBusinessProcesses[$pipelineId] = $businessProcess;\n\n return $businessProcess;\n }\n\n private function getBusinessProcess(string $pipelineId): ?BusinessProcess\n {\n return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);\n }\n\n private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage\n {\n if (empty($stageId)) {\n return null;\n }\n\n $cacheKey = $businessProcess->getId() . ':' . $stageId;\n if (isset($this->cachedStages[$cacheKey])) {\n return $this->cachedStages[$cacheKey];\n }\n\n $stage = $this->crmEntityRepository->getPipelineStageByConditions(\n $businessProcess,\n [\n 'crm_provider_id' => $stageId,\n 'type' => Stage::TYPE_OPPORTUNITY,\n ]\n );\n\n if ($stage === null) {\n $this->importStages(null, $stageId);\n }\n\n if ($stage === null) {\n $this->logger->info('[HubSpot] Stage does not exist => ' . $stageId);\n }\n\n $this->cachedStages[$cacheKey] = $stage;\n\n return $stage;\n }\n\n private function resolveAmount(array $properties): ?string\n {\n $amount = null;\n if (! empty($properties['amount'])) {\n $amount = str_replace(',', '', $properties['amount']);\n }\n\n if ($this->config->hasDefaultCurrencyFieldSet()) {\n $valueFieldName = $this->config->getDefaultCurrencyField()->getCrmProviderId();\n $amount = $properties[$valueFieldName] ?? $amount;\n }\n\n return $amount;\n }\n\n private function parseCleanDatetime(string $datetime): ?Carbon\n {\n // Treat pre-1980 values as invalid\n $minValidDate = Carbon::parse('1980-01-01 00:00:00');\n\n try {\n $date = Carbon::parse($datetime);\n\n if ($minValidDate->gt($date)) {\n return null;\n }\n\n return $date;\n } catch (Exception) {\n return null; // On parse error, treat as null\n }\n }\n\n private function resolveDealProbability(?string $stageProbability): int\n {\n if ($stageProbability === null) {\n return 0;\n }\n\n $probability = (float) $stageProbability;\n\n return $probability > 1 ? 0 : (int) ($probability * 100);\n }\n\n private function resolveForecastCategory(?string $forecastCategory): string\n {\n if (! $forecastCategory) {\n return Forecast::FORECAST_CATEGORY_UNCATEGORIZED;\n }\n\n $forecastCategory = str_replace('_', ' ', $forecastCategory);\n\n return ucwords(strtolower($forecastCategory));\n }\n\n private function importExternalFieldData(array $properties, int $opportunityId): void\n {\n $crmFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData($properties, $crmFields, $opportunityId);\n }\n\n private function importOpportunityContacts(Opportunity $opportunity, array $associations): void\n {\n // Handle empty or missing contact associations\n if (empty($associations)) {\n // Remove all existing contact associations if none provided\n $this->removeAllOpportunityContacts($opportunity);\n\n return;\n }\n\n // Use differential sync approach for better performance and accuracy\n $this->syncOpportunityContactsDifferential($opportunity, $associations);\n }\n\n /**\n * Sync opportunity contacts using differential approach\n * This compares current vs new associations and only makes necessary changes\n */\n private function syncOpportunityContactsDifferential(Opportunity $opportunity, array $contactAssociations): void\n {\n $currentContactCrmIds = $this->getCurrentContactCrmIds($opportunity);\n $contactAssociationIds = array_keys($contactAssociations);\n\n $contactsToAdd = array_diff($contactAssociationIds, $currentContactCrmIds);\n $contactsToRemove = array_diff($currentContactCrmIds, $contactAssociationIds);\n\n if (empty($contactsToAdd) && empty($contactsToRemove)) {\n return;\n }\n\n $this->logContactAssociationChanges($opportunity, $currentContactCrmIds, $contactAssociations, $contactsToAdd, $contactsToRemove);\n\n $this->removeContactAssociations($opportunity, $contactsToRemove);\n $this->addContactAssociations($opportunity, $contactsToAdd, $contactAssociations);\n }\n\n private function getCurrentContactCrmIds(Opportunity $opportunity): array\n {\n return $opportunity->contacts()\n ->pluck('contacts.crm_provider_id')\n ->toArray();\n }\n\n private function logContactAssociationChanges(\n Opportunity $opportunity,\n array $currentContactCrmIds,\n array $contactAssociations,\n array $contactsToAdd,\n array $contactsToRemove\n ): void {\n $this->logger->info('[' . $this->getDisplayName() . '] Contact association changes', [\n 'opportunity_id' => $opportunity->getId(),\n 'current_contacts' => $currentContactCrmIds,\n 'new_contacts' => $contactAssociations,\n 'contacts_to_add' => $contactsToAdd,\n 'contacts_to_remove' => $contactsToRemove,\n ]);\n }\n\n private function removeContactAssociations(Opportunity $opportunity, array $contactsToRemove): void\n {\n if (empty($contactsToRemove)) {\n return;\n }\n\n $contactsToDetach = $opportunity->contacts()\n ->whereIn('contacts.crm_provider_id', $contactsToRemove)\n ->pluck('contacts.id')\n ->toArray();\n\n if (! empty($contactsToDetach)) {\n $opportunity->contacts()->detach($contactsToDetach);\n\n $this->logger->info('[' . $this->getDisplayName() . '] Removed contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'removed_contact_crm_ids' => $contactsToRemove,\n 'removed_contact_count' => count($contactsToDetach),\n ]);\n }\n }\n\n private function addContactAssociations(Opportunity $opportunity, array $contactsToAdd, array $contactAssociations): void\n {\n if (empty($contactsToAdd)) {\n return;\n }\n\n $contactsAdded = [];\n foreach ($contactsToAdd as $crmId) {\n $id = $contactAssociations[$crmId];\n\n if ($this->attachSingleContact($opportunity, (string) $crmId, $id)) {\n $contactsAdded[] = $crmId;\n }\n }\n\n $this->logAddedContacts($opportunity, $contactsAdded);\n }\n\n private function attachSingleContact(Opportunity $opportunity, string $crmId, int $id): bool\n {\n try {\n $contact = $this->crmEntityRepository->findContactByConfigurationAndId($this->config, $id);\n\n if (! $contact) {\n return false;\n }\n\n return $this->performContactAttachment($opportunity, $contact, $crmId);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to add contact association', [\n 'opportunity_id' => $opportunity->getId(),\n 'contact_crm_id' => $crmId,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n private function performContactAttachment(Opportunity $opportunity, Contact $contact, string $crmId): bool\n {\n try {\n $opportunity->contacts()->attach($contact->getId(), [\n 'crm_provider_id' => $crmId,\n ]);\n\n return true;\n } catch (\\Illuminate\\Database\\QueryException $e) {\n if (str_contains($e->getMessage(), 'Duplicate entry')) {\n $this->logger->info('[' . $this->getDisplayName() . '] Contact association already exists', [\n 'contact_id' => $contact->getId(),\n 'contact_crm_id' => $crmId,\n 'opportunity_id' => $opportunity->getId(),\n ]);\n\n return false;\n }\n\n throw $e;\n }\n }\n\n private function logAddedContacts(Opportunity $opportunity, array $contactsAdded): void\n {\n if (! empty($contactsAdded)) {\n $this->logger->info('[' . $this->getDisplayName() . '] Added contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'contacts_to_add_count' => count($contactsAdded),\n 'added_contact_crm_ids' => $contactsAdded,\n 'added_contacts_count' => count($contactsAdded),\n ]);\n }\n }\n}","depth":4,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\ServiceTraits;\n\nuse Carbon\\Carbon;\nuse HubSpot\\Client\\Crm\\Deals\\Model\\CollectionResponseAssociatedId;\nuse Jiminny\\Exceptions\\InvalidArgumentException;\nuse Jiminny\\Models\\Account;\nuse Exception;\nuse Jiminny\\Component\\DealInsights\\Forecast\\Forecast;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Models\\Opportunity;\nuse Illuminate\\Support\\Collection;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Services\\Crm\\Hubspot\\DealFieldsService;\nuse Jiminny\\Services\\Crm\\Hubspot\\OpportunitySyncStrategy\\HubspotSingleSyncStrategy;\nuse Jiminny\\Services\\Crm\\Hubspot\\WebhookSyncBatchProcessor;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\n\n/**\n * Optimized sync methods for better performance\n * These methods can be integrated into SyncCrmEntitiesTrait for significant performance gains\n */\ntrait OpportunitySyncTrait\n{\n private const int BATCH_SIZE = 100;\n private const int BATCH_PROCESS_SIZE = 800;\n\n protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n protected CrmEntityRepository $crmEntityRepository;\n protected DealFieldsService $dealFieldsService;\n\n private ?array $cachedClosedDealStages = null;\n private array $cachedBusinessProcesses = [];\n private array $cachedStages = [];\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n $parameters['config'] = $this->config;\n $syncCount = 0;\n $reportedTotal = 0;\n $lastSyncedId = [];\n\n try {\n foreach ($strategies as $strategyName => $syncStrategy) {\n $this->logger->info(\n '[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' .\n $strategyName\n );\n\n $total = 0;\n $lastId = null;\n $buffer = [];\n\n // HubspotWebhookBatchSyncStrategy returns empty generator, this is for other strategies\n foreach ($syncStrategy->fetchOpportunities($parameters, $total, $lastId) as $hsOpportunity) {\n $buffer[] = $hsOpportunity;\n\n // process every 800 rows (fits < 1 000 association limit)\n if (\\count($buffer) >= self::BATCH_PROCESS_SIZE) {\n $syncCount += $this->processOpportunityBatch($buffer);\n $buffer = [];\n }\n }\n\n // leftovers\n if ($buffer) {\n $syncCount += $this->processOpportunityBatch($buffer);\n }\n\n $reportedTotal += $total;\n $lastSyncedId = $lastId;\n }\n } catch (\\HubSpot\\Client\\Crm\\Deals\\ApiException | CrmException $e) {\n $this->handleSyncException($e, $parameters);\n }\n\n $this->logger->info(\n '[HubSpot] Synced opportunities',\n [\n 'team' => $this->team->getId(),\n 'sync_count' => $syncCount,\n 'total' => $reportedTotal,\n 'last_synced_id' => $lastSyncedId,\n ]\n );\n\n return $reportedTotal;\n }\n\n private function handleSyncException(\\Throwable $e, array $parameters): void\n {\n if (($parameters['since'] ?? null) instanceof Carbon) {\n $parameters['since'] = $parameters['since']->toDateTimeString();\n }\n $parameters['config'] = $this->config->getId();\n\n $this->logger->warning('[' . $this->getDisplayName() . '] Sync opportunities failed', [\n 'teamId' => $this->team->getUuid(),\n 'parameters' => $parameters,\n 'reason' => $e->getMessage(),\n ]);\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,\n );\n\n $parameters = [\n 'config' => $this->config,\n 'crm_id' => $crmId,\n ];\n\n try {\n if (! $strategy instanceof HubspotSingleSyncStrategy) {\n throw new InvalidArgumentException('Strategy must by HubspotSingleSyncStrategy');\n }\n\n $hsOpportunity = $strategy->fetchOpportunity($parameters);\n } catch (\\HubSpot\\Client\\Crm\\Deals\\ApiException $e) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [\n 'teamId' => $this->team->getUuid(),\n 'crmId' => $crmId,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n $hsOpportunity['associations'] = $this->convertDealAssociations($hsOpportunity['associations'] ?? []);\n\n return $this->importOrUpdateOpportunity($hsOpportunity);\n }\n\n /**\n * Process webhook-collected opportunity batches.\n *\n * Drains Redis sets containing company CRM IDs collected from webhook events\n * and dispatches ImportOpportunityBatch jobs for batch processing.\n *\n * @return int Number of opportunity IDs dispatched to jobs\n */\n public function batchSyncOpportunities(): int\n {\n $configId = $this->team->getCrmConfiguration()->getId();\n\n return $this->batchProcessor->processBatchesForObjectType(\n WebhookSyncBatchProcessor::OBJECT_TYPE_DEAL,\n $configId\n );\n }\n\n /**\n * Import a batch of opportunities by their CRM IDs.\n * Fetches opportunity data from HubSpot API and delegates to importOpportunityBatch().\n *\n * @param array<string> $crmIds HubSpot deal CRM IDs\n *\n * @return array{success: array, failed_ids: array, errors?: array<string, string>}\n */\n public function importOpportunityBatchByIds(array $crmIds): array\n {\n $fields = $this->dealFieldsService->getFieldsForConfiguration($this->config);\n\n $allDeals = [];\n foreach (array_chunk($crmIds, self::BATCH_SIZE) as $chunk) {\n $deals = $this->client->getOpportunitiesByIds($chunk, $fields);\n foreach ($deals as $deal) {\n $allDeals[] = $deal;\n }\n }\n\n // IDs not returned by HubSpot are likely deleted or inaccessible deals.\n // These are not failures — retrying won't bring them back.\n $fetchedIds = array_map('strval', array_column($allDeals, 'id'));\n $notFoundIds = array_values(array_diff(array_map('strval', $crmIds), $fetchedIds));\n\n if (! empty($notFoundIds)) {\n $this->logger->info('[' . $this->getDisplayName() . '] CRM IDs not found in HubSpot (likely deleted)', [\n 'teamId' => $this->team->getId(),\n 'notFoundCount' => \\count($notFoundIds),\n 'notFoundIds' => $notFoundIds,\n 'requestedCount' => \\count($crmIds),\n 'fetchedCount' => \\count($allDeals),\n ]);\n }\n\n if (empty($allDeals)) {\n return ['success' => [], 'failed_ids' => []];\n }\n\n return $this->importOpportunityBatch($allDeals);\n }\n\n private function getClosedDealStages(): array\n {\n if ($this->cachedClosedDealStages !== null) {\n return $this->cachedClosedDealStages;\n }\n\n $stages = $this->crmEntityRepository->getOpportunityClosedStages($this->config);\n $data = [\n 'lost' => [],\n 'won' => [],\n ];\n\n foreach ($stages as $stage) {\n if ($stage->probability == 0.00) {\n $data['lost'][] = $stage->crm_provider_id;\n }\n if ($stage->probability == 100.00) {\n $data['won'][] = $stage->crm_provider_id;\n }\n }\n\n $this->cachedClosedDealStages = $data;\n\n return $data;\n }\n\n /**\n * Import deals into the database with pre-fetched associations.\n *\n * API calls here (getAssociationsData, getExistingOpportunityCrmIds) are NOT\n * caught — if they throw, the exception propagates to ImportOpportunityBatch::handle()\n * where Laravel retries the whole job with backoff. After all retries exhausted,\n * failed() requeues all IDs to Redis.\n *\n * The per-deal loop catches exceptions individually. A deal can end up in three states:\n * - success: imported/updated successfully\n * - failed_ids: exception thrown (DB constraint violation, corrupt data, etc.)\n * These are permanent issues — retrying won't fix them.\n * - skipped (null): missing dependencies (no account, unknown pipeline/stage).\n * This is acceptable — the deal cannot be imported until those exist.\n */\n private function importOpportunityBatch(array $deals): array\n {\n $syncedOpportunities = [\n 'success' => [],\n 'failed_ids' => [],\n ];\n $dealIds = array_column($deals, 'id');\n\n // Shared association/existing-ID preparation is batch-level state. If it fails, rethrow so the\n // queue job retries the whole batch and eventually requeues all deal IDs back to Redis.\n try {\n $companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');\n $contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');\n\n $associationsData = $this->prepareAssociatedEntities($companyAssociations, $contactAssociations);\n\n $existingCrmIds = $this->crmEntityRepository->getExistingOpportunityCrmIds(\n $this->config,\n array_map('strval', $dealIds)\n );\n $existingCrmIdSet = array_flip($existingCrmIds);\n } catch (\\Throwable $e) {\n $this->logger->error('[' . $this->getDisplayName() . '] Failed to fetch associations or existing IDs', [\n 'teamId' => $this->team->getId(),\n 'dealCount' => count($dealIds),\n 'error' => $e->getMessage(),\n ]);\n\n throw $e;\n }\n\n foreach ($deals as $deal) {\n try {\n $deal['associations'] = $this->prepareAssociationsForOpportunity(\n $deal['id'],\n $companyAssociations,\n $contactAssociations,\n $associationsData\n );\n\n $syncedOpportunity = $this->importOrUpdateOpportunity(\n $deal,\n isset($existingCrmIdSet[(string) $deal['id']])\n );\n if ($syncedOpportunity) {\n $syncedOpportunities['success'][] = $syncedOpportunity;\n }\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to import opportunity', [\n 'teamId' => $this->team->getId(),\n 'crmId' => $deal['id'],\n 'error' => $e->getMessage(),\n ]);\n $syncedOpportunities['failed_ids'][] = $deal['id'];\n $syncedOpportunities['errors'][$deal['id']] = $e->getMessage();\n }\n }\n\n return $syncedOpportunities;\n }\n\n /**\n * Prepare associated entities for opportunities with optimized batch processing\n * Returns structured data with CRM ID to DB ID mappings for each opportunity\n */\n private function prepareAssociatedEntities(array $companyAssociations, array $contactAssociations): array\n {\n // Step 1: Collect all unique company and contact IDs from associations\n $allCompanyIds = $this->flattenAssociationIds($companyAssociations);\n $allContactIds = $this->flattenAssociationIds($contactAssociations);\n\n // Step 2: Batch sync missing entities and get CRM ID to DB ID mappings\n $companyIdMappings = [];\n $contactIdMappings = [];\n\n if (! empty($allCompanyIds)) {\n $companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);\n }\n\n if (! empty($allContactIds)) {\n $contactIdMappings = $this->prepareAssociatedContacts($allContactIds);\n }\n\n return [\n 'company_id_mappings' => $companyIdMappings,\n 'contact_id_mappings' => $contactIdMappings,\n ];\n }\n\n /**\n * Flatten association data to get unique IDs\n */\n private function flattenAssociationIds(array $associations): array\n {\n $ids = [];\n foreach ($associations as $dealAssociations) {\n if (is_array($dealAssociations)) {\n foreach ($dealAssociations as $id) {\n $ids[$id] = true;\n }\n }\n }\n\n return array_keys($ids);\n }\n\n /**\n * Batch sync missing accounts\n */\n private function prepareAssociatedAccounts(array $companyIds): array\n {\n // Find which accounts already exist\n $existingAccounts = $this->crmEntityRepository\n ->findAccountsByExternalIds($this->config, $companyIds);\n\n $existingCompanyIds = $existingAccounts->pluck('crm_provider_id')->toArray();\n\n $existingAccountsData = $existingAccounts->mapWithKeys(function ($account) {\n return [$account->getCrmProviderId() => $account->getId()];\n })->toArray();\n\n $missingCompanyIds = array_diff($companyIds, $existingCompanyIds);\n\n if (empty($missingCompanyIds)) {\n return $existingAccountsData;\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing accounts', [\n 'teamId' => $this->team->getUuid(),\n 'total_companies' => count($companyIds),\n 'existing_companies' => count($existingCompanyIds),\n 'missing_companies' => count($missingCompanyIds),\n ]);\n\n // we already have limit on opportunity ids count\n // Initialize variable before try block\n $syncedAccountsData = [];\n\n try {\n $syncedAccountsData = $this->batchSyncCrmObjects('companies', $missingCompanyIds);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing accounts', [\n 'size' => count($missingCompanyIds),\n 'error' => $e->getMessage(),\n ]);\n $syncedAccountsData = [];\n }\n\n return $existingAccountsData + $syncedAccountsData;\n }\n\n /**\n * Prepare associated contacts - find existing and sync missing ones\n * Returns mapping of CRM ID to DB ID\n */\n private function prepareAssociatedContacts(array $contactIds): array\n {\n // Find which contacts already exist\n $existingContacts = $this->crmEntityRepository\n ->findContactsByExternalIds($this->config, $contactIds);\n\n $existingContactIds = $existingContacts->pluck('crm_provider_id')->toArray();\n\n // Create mapping for existing contacts\n $existingContactsData = $existingContacts->mapWithKeys(function ($contact) {\n return [$contact->getCrmProviderId() => $contact->getId()];\n })->toArray();\n\n $missingContactIds = array_diff($contactIds, $existingContactIds);\n\n if (empty($missingContactIds)) {\n return $existingContactsData;\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing contacts', [\n 'teamId' => $this->team->getUuid(),\n 'total_contacts' => count($contactIds),\n 'existing_contacts' => count($existingContactIds),\n 'missing_contacts' => count($missingContactIds),\n ]);\n\n // Sync missing contacts using batch API\n try {\n $syncedContactsData = $this->batchSyncCrmObjects('contacts', $missingContactIds);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing contacts', [\n 'size' => count($missingContactIds),\n 'error' => $e->getMessage(),\n ]);\n $syncedContactsData = [];\n }\n\n return $existingContactsData + $syncedContactsData;\n }\n\n private function batchSyncCrmObjects(string $objectType, array $crmIds): array\n {\n $syncObjects = [];\n $crmObjectIds = array_values($crmIds);\n\n foreach (array_chunk($crmObjectIds, self::BATCH_SIZE) as $chunk) {\n try {\n $objects = $objectType === 'companies' ?\n $this->client->getCompaniesByIds($chunk, $this->getCompanyFields()) :\n $this->client->getContactsByIds($chunk, $this->getContactFields());\n\n foreach ($objects as $objectId => $objectData) {\n $this->importCrmObject($objectType, (string) $objectId, $objectData, $syncObjects);\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch synced ' . $objectType, [\n 'requested_count' => count($chunk),\n 'synced_count' => count($objects),\n ]);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Batch ' . $objectType . ' sync failed', [\n 'ids' => $chunk,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n return $syncObjects;\n }\n\n private function importCrmObject(string $objectType, string $objectId, mixed $objectData, array &$syncObjects): void\n {\n try {\n $object = $objectType === 'companies' ?\n $this->importAccount($objectData) :\n $this->importContact($objectData);\n\n if ($object) {\n $syncObjects[$object->getCrmProviderId()] = $object->getId();\n }\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to import batch ' . $objectType, [\n 'id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n /**\n * Prepare associations for a single opportunity\n *\n * The return value is an array with the following structure:\n * [\n * 'companies' => [\n * $companyCrmId => $companyId,\n * ...\n * ],\n * 'contacts' => [\n * $contactCrmId => $contactId,\n * ...\n * ],\n * 'account_id' => $accountId,\n * ]\n */\n private function prepareAssociationsForOpportunity(\n string $oppCrmId,\n array $companyAssociations,\n array $contactAssociations,\n array $associationsData\n ): array {\n $associations = [\n 'companies' => [],\n 'contacts' => [],\n 'account_id' => null, // Primary account for opportunity\n ];\n\n $oppCompanyIds = $companyAssociations[$oppCrmId] ?? [];\n foreach ($oppCompanyIds as $companyCrmId) {\n if (isset($associationsData['company_id_mappings'][$companyCrmId])) {\n $associations['companies'][$companyCrmId] = $associationsData['company_id_mappings'][$companyCrmId];\n\n // Set primary account (first company becomes primary account)\n if ($associations['account_id'] === null) {\n $associations['account_id'] = $associationsData['company_id_mappings'][$companyCrmId];\n }\n }\n }\n\n $oppContactIds = $contactAssociations[$oppCrmId] ?? [];\n foreach ($oppContactIds as $contactCrmId) {\n if (isset($associationsData['contact_id_mappings'][$contactCrmId])) {\n $associations['contacts'][$contactCrmId] = $associationsData['contact_id_mappings'][$contactCrmId];\n }\n }\n\n return $associations;\n }\n\n /**\n * Update only associations for an opportunity\n */\n private function updateOpportunityAssociations(Opportunity $opportunity, array $associations): void\n {\n // Update contact associations\n $this->importOpportunityContacts($opportunity, $associations['contacts']);\n\n // Update company (account) associations\n $this->updateOpportunityAccount($opportunity, $associations['account_id']);\n }\n\n /**\n * Remove all contact associations from an opportunity\n */\n private function removeAllOpportunityContacts(Opportunity $opportunity): void\n {\n $currentCount = (int) $opportunity->contacts()->count();\n\n if ($currentCount > 0) {\n $opportunity->contacts()->detach();\n\n $this->logger->info('[' . $this->getDisplayName() . '] Removed all contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'removed_count' => $currentCount,\n ]);\n }\n }\n\n private function updateOpportunityAccount(Opportunity $opportunity, ?int $accountId): void\n {\n if ($accountId === null) {\n // No account ID provided - keep current account\n return;\n }\n\n $currentAccountId = $opportunity->getAccountId();\n\n // Only update if account has changed\n if ($currentAccountId !== $accountId) {\n $opportunity->account_id = $accountId;\n $opportunity->save();\n\n $this->logger->info('[' . $this->getDisplayName() . '] Updated opportunity account association', [\n 'opportunity_id' => $opportunity->getId(),\n 'old_account_id' => $currentAccountId,\n 'new_account_id' => $accountId,\n ]);\n }\n }\n\n /**\n * Find existing opportunities by external IDs (OPTIMIZED VERSION)\n * Uses batch query for better performance\n */\n private function findExistingOpportunities(array $crmIds): Collection\n {\n return $this->crmEntityRepository\n ->findOpportunitiesByExternalIds($this->config, $crmIds);\n }\n\n private function processOpportunityBatch(array $opportunities): int\n {\n $syncedOpportunities = $this->importOpportunityBatch($opportunities);\n\n return count($syncedOpportunities['success'] ?? []);\n }\n\n /**\n * Convert single deal associations from HubSpot format to internal format\n * Handles both HubSpot SDK objects and array formats\n *\n * @param array $opportunityAssociations Raw associations from HubSpot API or pre-processed\n *\n * @return array Processed associations with DB IDs\n */\n private function convertDealAssociations(array $opportunityAssociations): array\n {\n $associations = $this->initializeAssociationsStructure();\n\n if (empty($opportunityAssociations)) {\n return $associations;\n }\n\n $associationIds = $this->extractAssociationIds($opportunityAssociations);\n\n $this->processCompanyAssociations($associationIds, $associations);\n $this->processContactAssociations($associationIds, $associations);\n\n return $associations;\n }\n\n private function initializeAssociationsStructure(): array\n {\n return [\n 'companies' => [],\n 'contacts' => [],\n 'account_id' => null, // Primary account for opportunity\n ];\n }\n\n private function extractAssociationIds(array $opportunityAssociations): array\n {\n $associationIds = [];\n\n foreach ($opportunityAssociations as $type => $associationData) {\n if (! empty($associationData)) {\n $associationIds[$type] = $this->convertSingleDealAssociations($associationData);\n }\n }\n\n return $associationIds;\n }\n\n private function processCompanyAssociations(array $associationIds, array &$associations): void\n {\n if (empty($associationIds['companies'])) {\n return;\n }\n\n $companyId = $associationIds['companies'][0];\n $account = $this->findOrSyncAccount($companyId);\n\n if ($account instanceof Account) {\n $associations['companies'][$companyId] = $account->getId();\n $associations['account_id'] = $account->getId();\n }\n }\n\n private function processContactAssociations(array $associationIds, array &$associations): void\n {\n if (empty($associationIds['contacts'])) {\n return;\n }\n\n foreach ($associationIds['contacts'] as $contactId) {\n $contact = $this->findOrSyncContact($contactId);\n\n if ($contact instanceof Contact) {\n $associations['contacts'][$contactId] = $contact->getId();\n }\n }\n }\n\n private function findOrSyncAccount(string $companyId): ?Account\n {\n $account = $this->crmEntityRepository->findAccountByExternalId($this->config, $companyId);\n\n if (! $account instanceof Account) {\n $account = $this->syncAccount($companyId);\n }\n\n return $account;\n }\n\n private function findOrSyncContact(string $contactId): ?Contact\n {\n $contact = $this->crmEntityRepository->findContactByExternalId($this->config, $contactId);\n\n if (! $contact instanceof Contact) {\n $contact = $this->syncContact($contactId);\n }\n\n return $contact;\n }\n\n private function convertSingleDealAssociations($opportunityAssociations = null): array\n {\n $associationData = [];\n\n if ($opportunityAssociations === null) {\n return $associationData;\n }\n\n // Handle array input (from extractAssociationIds)\n if (is_array($opportunityAssociations)) {\n return $opportunityAssociations;\n }\n\n // Handle CollectionResponseAssociatedId object\n if ($opportunityAssociations instanceof CollectionResponseAssociatedId) {\n foreach ($opportunityAssociations->getResults() as $association) {\n $associationData[] = $association->getId();\n }\n }\n\n return $associationData;\n }\n\n private function importOrUpdateOpportunity($crmData, ?bool $exists = null): ?Opportunity\n {\n if (empty($crmData['properties'])) {\n return null;\n }\n\n $crmId = (string) $crmData['id'];\n $properties = $crmData['properties'];\n $associations = $crmData['associations'] ?? [];\n\n $opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(\n $this->config,\n $crmId\n );\n\n if ($opportunityExists) {\n return $this->updateOpportunity($crmId, $properties, $associations);\n } else {\n return $this->createOpportunity($crmId, $properties, $associations);\n }\n }\n\n /**\n * Create new opportunity\n */\n private function createOpportunity(string $crmId, array $properties, array $associations): ?Opportunity\n {\n $accountId = $this->resolveAccountId($associations);\n if (! $accountId) {\n return null;\n }\n\n $businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);\n if (! $businessProcess) {\n return null;\n }\n\n $stage = $this->resolveStage($businessProcess, $properties['dealstage'] ?? null);\n if (! $stage) {\n return null;\n }\n\n $data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);\n\n $attributes = [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmId,\n ];\n\n $values = array_merge($attributes, $data);\n\n $opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);\n\n $this->importExternalFieldData($properties, $opportunity->getId());\n $this->importOpportunityContacts($opportunity, $associations['contacts']);\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n }\n\n /**\n * Update existing opportunity\n */\n private function updateOpportunity(string $crmId, array $properties, array $associations): Opportunity\n {\n $accountId = $this->resolveAccountId($associations);\n $businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);\n $stage = $businessProcess ? $this->resolveStage($businessProcess, $properties['dealstage'] ?? null) : null;\n\n $data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);\n\n $attributes = [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmId,\n ];\n\n $values = array_merge($attributes, $data);\n $opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);\n\n $this->importExternalFieldData($properties, $opportunity->getId());\n $this->updateOpportunityAssociations($opportunity, $associations);\n\n return $opportunity;\n }\n\n private function resolveAccountId(array $associations): ?int\n {\n if (! empty($associations['accountId'])) {\n return $associations['accountId'];\n }\n\n if (empty($associations)) {\n return null;\n }\n\n // we can't resolve multiple account ids (currently SDK returns one company)\n foreach ($associations['companies'] as $accountId) {\n return $accountId;\n }\n\n return null;\n }\n\n private function buildOpportunityData(\n array $properties,\n ?int $accountId,\n ?BusinessProcess $businessProcess,\n ?Stage $stage\n ): array {\n $ownerId = null;\n $profile = null;\n if (! empty($properties['hubspot_owner_id'])) {\n $ownerId = $properties['hubspot_owner_id'];\n $profile = $this->crmEntityRepository->findProfileByExternalId($this->config, (string) $ownerId);\n }\n\n $name = 'Unknown';\n if (isset($properties['dealname'])) {\n $name = mb_strimwidth($properties['dealname'], 0, 128);\n }\n\n $amount = $this->resolveAmount($properties);\n $currency = $properties['deal_currency_code'] ?? null;\n\n $closeDate = null;\n if (! empty($properties['closedate'])) {\n $closeDate = Carbon::parse($properties['closedate'])->format('Y-m-d');\n }\n\n $remotelyCreatedAt = null;\n if (! empty($properties['createdate']) && strtotime($properties['createdate'])) {\n $date = $this->parseCleanDatetime($properties['createdate']);\n $remotelyCreatedAt = $date?->format('Y-m-d H:i:s');\n }\n\n $closedStages = $this->getClosedDealStages();\n $isWon = in_array($properties['dealstage'], $closedStages['won']);\n $isLost = in_array($properties['dealstage'], $closedStages['lost']);\n\n $data = [\n 'team_id' => $this->team->getId(),\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => $name,\n 'value' => ! empty($amount) ? $amount : null,\n 'currency_code' => CurrencyFormatter::formatCode($currency),\n 'close_date' => $closeDate,\n 'is_closed' => $isWon || $isLost,\n 'is_won' => $isWon,\n 'remotely_created_at' => $remotelyCreatedAt,\n 'probability' => $this->resolveDealProbability($properties['hs_deal_stage_probability']),\n 'forecast_category' => $this->resolveForecastCategory($properties['hs_manual_forecast_category']),\n ];\n\n if ($accountId) {\n $data['account_id'] = $accountId;\n }\n\n if ($stage) {\n $data['stage_id'] = $stage->id;\n }\n\n if ($businessProcess) {\n $recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);\n if ($recordType) {\n $data['record_type_id'] = $recordType->id;\n }\n }\n\n return $data;\n }\n\n private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess\n {\n if ($pipelineId === null) {\n return null;\n }\n\n if (isset($this->cachedBusinessProcesses[$pipelineId])) {\n return $this->cachedBusinessProcesses[$pipelineId];\n }\n\n $businessProcess = $this->getBusinessProcess($pipelineId);\n\n if (! $businessProcess instanceof BusinessProcess) {\n $this->importStages();\n $businessProcess = $this->getBusinessProcess($pipelineId);\n }\n\n if (! $businessProcess instanceof BusinessProcess) {\n $this->logger->info(\n '[HubSpot] Deal is not attached to a pipeline',\n [\n 'pipeline' => $pipelineId]\n );\n }\n\n $this->cachedBusinessProcesses[$pipelineId] = $businessProcess;\n\n return $businessProcess;\n }\n\n private function getBusinessProcess(string $pipelineId): ?BusinessProcess\n {\n return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);\n }\n\n private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage\n {\n if (empty($stageId)) {\n return null;\n }\n\n $cacheKey = $businessProcess->getId() . ':' . $stageId;\n if (isset($this->cachedStages[$cacheKey])) {\n return $this->cachedStages[$cacheKey];\n }\n\n $stage = $this->crmEntityRepository->getPipelineStageByConditions(\n $businessProcess,\n [\n 'crm_provider_id' => $stageId,\n 'type' => Stage::TYPE_OPPORTUNITY,\n ]\n );\n\n if ($stage === null) {\n $this->importStages(null, $stageId);\n }\n\n if ($stage === null) {\n $this->logger->info('[HubSpot] Stage does not exist => ' . $stageId);\n }\n\n $this->cachedStages[$cacheKey] = $stage;\n\n return $stage;\n }\n\n private function resolveAmount(array $properties): ?string\n {\n $amount = null;\n if (! empty($properties['amount'])) {\n $amount = str_replace(',', '', $properties['amount']);\n }\n\n if ($this->config->hasDefaultCurrencyFieldSet()) {\n $valueFieldName = $this->config->getDefaultCurrencyField()->getCrmProviderId();\n $amount = $properties[$valueFieldName] ?? $amount;\n }\n\n return $amount;\n }\n\n private function parseCleanDatetime(string $datetime): ?Carbon\n {\n // Treat pre-1980 values as invalid\n $minValidDate = Carbon::parse('1980-01-01 00:00:00');\n\n try {\n $date = Carbon::parse($datetime);\n\n if ($minValidDate->gt($date)) {\n return null;\n }\n\n return $date;\n } catch (Exception) {\n return null; // On parse error, treat as null\n }\n }\n\n private function resolveDealProbability(?string $stageProbability): int\n {\n if ($stageProbability === null) {\n return 0;\n }\n\n $probability = (float) $stageProbability;\n\n return $probability > 1 ? 0 : (int) ($probability * 100);\n }\n\n private function resolveForecastCategory(?string $forecastCategory): string\n {\n if (! $forecastCategory) {\n return Forecast::FORECAST_CATEGORY_UNCATEGORIZED;\n }\n\n $forecastCategory = str_replace('_', ' ', $forecastCategory);\n\n return ucwords(strtolower($forecastCategory));\n }\n\n private function importExternalFieldData(array $properties, int $opportunityId): void\n {\n $crmFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData($properties, $crmFields, $opportunityId);\n }\n\n private function importOpportunityContacts(Opportunity $opportunity, array $associations): void\n {\n // Handle empty or missing contact associations\n if (empty($associations)) {\n // Remove all existing contact associations if none provided\n $this->removeAllOpportunityContacts($opportunity);\n\n return;\n }\n\n // Use differential sync approach for better performance and accuracy\n $this->syncOpportunityContactsDifferential($opportunity, $associations);\n }\n\n /**\n * Sync opportunity contacts using differential approach\n * This compares current vs new associations and only makes necessary changes\n */\n private function syncOpportunityContactsDifferential(Opportunity $opportunity, array $contactAssociations): void\n {\n $currentContactCrmIds = $this->getCurrentContactCrmIds($opportunity);\n $contactAssociationIds = array_keys($contactAssociations);\n\n $contactsToAdd = array_diff($contactAssociationIds, $currentContactCrmIds);\n $contactsToRemove = array_diff($currentContactCrmIds, $contactAssociationIds);\n\n if (empty($contactsToAdd) && empty($contactsToRemove)) {\n return;\n }\n\n $this->logContactAssociationChanges($opportunity, $currentContactCrmIds, $contactAssociations, $contactsToAdd, $contactsToRemove);\n\n $this->removeContactAssociations($opportunity, $contactsToRemove);\n $this->addContactAssociations($opportunity, $contactsToAdd, $contactAssociations);\n }\n\n private function getCurrentContactCrmIds(Opportunity $opportunity): array\n {\n return $opportunity->contacts()\n ->pluck('contacts.crm_provider_id')\n ->toArray();\n }\n\n private function logContactAssociationChanges(\n Opportunity $opportunity,\n array $currentContactCrmIds,\n array $contactAssociations,\n array $contactsToAdd,\n array $contactsToRemove\n ): void {\n $this->logger->info('[' . $this->getDisplayName() . '] Contact association changes', [\n 'opportunity_id' => $opportunity->getId(),\n 'current_contacts' => $currentContactCrmIds,\n 'new_contacts' => $contactAssociations,\n 'contacts_to_add' => $contactsToAdd,\n 'contacts_to_remove' => $contactsToRemove,\n ]);\n }\n\n private function removeContactAssociations(Opportunity $opportunity, array $contactsToRemove): void\n {\n if (empty($contactsToRemove)) {\n return;\n }\n\n $contactsToDetach = $opportunity->contacts()\n ->whereIn('contacts.crm_provider_id', $contactsToRemove)\n ->pluck('contacts.id')\n ->toArray();\n\n if (! empty($contactsToDetach)) {\n $opportunity->contacts()->detach($contactsToDetach);\n\n $this->logger->info('[' . $this->getDisplayName() . '] Removed contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'removed_contact_crm_ids' => $contactsToRemove,\n 'removed_contact_count' => count($contactsToDetach),\n ]);\n }\n }\n\n private function addContactAssociations(Opportunity $opportunity, array $contactsToAdd, array $contactAssociations): void\n {\n if (empty($contactsToAdd)) {\n return;\n }\n\n $contactsAdded = [];\n foreach ($contactsToAdd as $crmId) {\n $id = $contactAssociations[$crmId];\n\n if ($this->attachSingleContact($opportunity, (string) $crmId, $id)) {\n $contactsAdded[] = $crmId;\n }\n }\n\n $this->logAddedContacts($opportunity, $contactsAdded);\n }\n\n private function attachSingleContact(Opportunity $opportunity, string $crmId, int $id): bool\n {\n try {\n $contact = $this->crmEntityRepository->findContactByConfigurationAndId($this->config, $id);\n\n if (! $contact) {\n return false;\n }\n\n return $this->performContactAttachment($opportunity, $contact, $crmId);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to add contact association', [\n 'opportunity_id' => $opportunity->getId(),\n 'contact_crm_id' => $crmId,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n private function performContactAttachment(Opportunity $opportunity, Contact $contact, string $crmId): bool\n {\n try {\n $opportunity->contacts()->attach($contact->getId(), [\n 'crm_provider_id' => $crmId,\n ]);\n\n return true;\n } catch (\\Illuminate\\Database\\QueryException $e) {\n if (str_contains($e->getMessage(), 'Duplicate entry')) {\n $this->logger->info('[' . $this->getDisplayName() . '] Contact association already exists', [\n 'contact_id' => $contact->getId(),\n 'contact_crm_id' => $crmId,\n 'opportunity_id' => $opportunity->getId(),\n ]);\n\n return false;\n }\n\n throw $e;\n }\n }\n\n private function logAddedContacts(Opportunity $opportunity, array $contactsAdded): void\n {\n if (! empty($contactsAdded)) {\n $this->logger->info('[' . $this->getDisplayName() . '] Added contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'contacts_to_add_count' => count($contactsAdded),\n 'added_contact_crm_ids' => $contactsAdded,\n 'added_contacts_count' => count($contactsAdded),\n ]);\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,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Explain Plan","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Browse Query History","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"View Parameters","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open Query Execution Settings…","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"In-Editor Results","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
7208507781505271922
|
-8178087410993360602
|
visual_change
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
"podcast_audio_url"
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
0 results
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Code changed:
Hide
Sync Changes
Hide This Notification
32
2
19
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\ServiceTraits;
use Carbon\Carbon;
use HubSpot\Client\Crm\Deals\Model\CollectionResponseAssociatedId;
use Jiminny\Exceptions\InvalidArgumentException;
use Jiminny\Models\Account;
use Exception;
use Jiminny\Component\DealInsights\Forecast\Forecast;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Exceptions\CrmException;
use Jiminny\Models\Opportunity;
use Illuminate\Support\Collection;
use Jiminny\Models\Stage;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Services\Crm\Hubspot\DealFieldsService;
use Jiminny\Services\Crm\Hubspot\OpportunitySyncStrategy\HubspotSingleSyncStrategy;
use Jiminny\Services\Crm\Hubspot\WebhookSyncBatchProcessor;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
/**
* Optimized sync methods for better performance
* These methods can be integrated into SyncCrmEntitiesTrait for significant performance gains
*/
trait OpportunitySyncTrait
{
private const int BATCH_SIZE = 100;
private const int BATCH_PROCESS_SIZE = 800;
protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
protected CrmEntityRepository $crmEntityRepository;
protected DealFieldsService $dealFieldsService;
private ?array $cachedClosedDealStages = null;
private array $cachedBusinessProcesses = [];
private array $cachedStages = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' .
$strategyName
);
$total = 0;
$lastId = null;
$buffer = [];
// HubspotWebhookBatchSyncStrategy returns empty generator, this is for other strategies
foreach ($syncStrategy->fetchOpportunities($parameters, $total, $lastId) as $hsOpportunity) {
$buffer[] = $hsOpportunity;
// process every 800 rows (fits < 1 000 association limit)
if (\count($buffer) >= self::BATCH_PROCESS_SIZE) {
$syncCount += $this->processOpportunityBatch($buffer);
$buffer = [];
}
}
// leftovers
if ($buffer) {
$syncCount += $this->processOpportunityBatch($buffer);
}
$reportedTotal += $total;
$lastSyncedId = $lastId;
}
} catch (\HubSpot\Client\Crm\Deals\ApiException | CrmException $e) {
$this->handleSyncException($e, $parameters);
}
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
]
);
return $reportedTotal;
}
private function handleSyncException(\Throwable $e, array $parameters): void
{
if (($parameters['since'] ?? null) instanceof Carbon) {
$parameters['since'] = $parameters['since']->toDateTimeString();
}
$parameters['config'] = $this->config->getId();
$this->logger->warning('[' . $this->getDisplayName() . '] Sync opportunities failed', [
'teamId' => $this->team->getUuid(),
'parameters' => $parameters,
'reason' => $e->getMessage(),
]);
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,
);
$parameters = [
'config' => $this->config,
'crm_id' => $crmId,
];
try {
if (! $strategy instanceof HubspotSingleSyncStrategy) {
throw new InvalidArgumentException('Strategy must by HubspotSingleSyncStrategy');
}
$hsOpportunity = $strategy->fetchOpportunity($parameters);
} catch (\HubSpot\Client\Crm\Deals\ApiException $e) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [
'teamId' => $this->team->getUuid(),
'crmId' => $crmId,
'reason' => $e->getMessage(),
]);
return null;
}
$hsOpportunity['associations'] = $this->convertDealAssociations($hsOpportunity['associations'] ?? []);
return $this->importOrUpdateOpportunity($hsOpportunity);
}
/**
* Process webhook-collected opportunity batches.
*
* Drains Redis sets containing company CRM IDs collected from webhook events
* and dispatches ImportOpportunityBatch jobs for batch processing.
*
* @return int Number of opportunity IDs dispatched to jobs
*/
public function batchSyncOpportunities(): int
{
$configId = $this->team->getCrmConfiguration()->getId();
return $this->batchProcessor->processBatchesForObjectType(
WebhookSyncBatchProcessor::OBJECT_TYPE_DEAL,
$configId
);
}
/**
* Import a batch of opportunities by their CRM IDs.
* Fetches opportunity data from HubSpot API and delegates to importOpportunityBatch().
*
* @param array<string> $crmIds HubSpot deal CRM IDs
*
* @return array{success: array, failed_ids: array, errors?: array<string, string>}
*/
public function importOpportunityBatchByIds(array $crmIds): array
{
$fields = $this->dealFieldsService->getFieldsForConfiguration($this->config);
$allDeals = [];
foreach (array_chunk($crmIds, self::BATCH_SIZE) as $chunk) {
$deals = $this->client->getOpportunitiesByIds($chunk, $fields);
foreach ($deals as $deal) {
$allDeals[] = $deal;
}
}
// IDs not returned by HubSpot are likely deleted or inaccessible deals.
// These are not failures — retrying won't bring them back.
$fetchedIds = array_map('strval', array_column($allDeals, 'id'));
$notFoundIds = array_values(array_diff(array_map('strval', $crmIds), $fetchedIds));
if (! empty($notFoundIds)) {
$this->logger->info('[' . $this->getDisplayName() . '] CRM IDs not found in HubSpot (likely deleted)', [
'teamId' => $this->team->getId(),
'notFoundCount' => \count($notFoundIds),
'notFoundIds' => $notFoundIds,
'requestedCount' => \count($crmIds),
'fetchedCount' => \count($allDeals),
]);
}
if (empty($allDeals)) {
return ['success' => [], 'failed_ids' => []];
}
return $this->importOpportunityBatch($allDeals);
}
private function getClosedDealStages(): array
{
if ($this->cachedClosedDealStages !== null) {
return $this->cachedClosedDealStages;
}
$stages = $this->crmEntityRepository->getOpportunityClosedStages($this->config);
$data = [
'lost' => [],
'won' => [],
];
foreach ($stages as $stage) {
if ($stage->probability == 0.00) {
$data['lost'][] = $stage->crm_provider_id;
}
if ($stage->probability == 100.00) {
$data['won'][] = $stage->crm_provider_id;
}
}
$this->cachedClosedDealStages = $data;
return $data;
}
/**
* Import deals into the database with pre-fetched associations.
*
* API calls here (getAssociationsData, getExistingOpportunityCrmIds) are NOT
* caught — if they throw, the exception propagates to ImportOpportunityBatch::handle()
* where Laravel retries the whole job with backoff. After all retries exhausted,
* failed() requeues all IDs to Redis.
*
* The per-deal loop catches exceptions individually. A deal can end up in three states:
* - success: imported/updated successfully
* - failed_ids: exception thrown (DB constraint violation, corrupt data, etc.)
* These are permanent issues — retrying won't fix them.
* - skipped (null): missing dependencies (no account, unknown pipeline/stage).
* This is acceptable — the deal cannot be imported until those exist.
*/
private function importOpportunityBatch(array $deals): array
{
$syncedOpportunities = [
'success' => [],
'failed_ids' => [],
];
$dealIds = array_column($deals, 'id');
// Shared association/existing-ID preparation is batch-level state. If it fails, rethrow so the
// queue job retries the whole batch and eventually requeues all deal IDs back to Redis.
try {
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$associationsData = $this->prepareAssociatedEntities($companyAssociations, $contactAssociations);
$existingCrmIds = $this->crmEntityRepository->getExistingOpportunityCrmIds(
$this->config,
array_map('strval', $dealIds)
);
$existingCrmIdSet = array_flip($existingCrmIds);
} catch (\Throwable $e) {
$this->logger->error('[' . $this->getDisplayName() . '] Failed to fetch associations or existing IDs', [
'teamId' => $this->team->getId(),
'dealCount' => count($dealIds),
'error' => $e->getMessage(),
]);
throw $e;
}
foreach ($deals as $deal) {
try {
$deal['associations'] = $this->prepareAssociationsForOpportunity(
$deal['id'],
$companyAssociations,
$contactAssociations,
$associationsData
);
$syncedOpportunity = $this->importOrUpdateOpportunity(
$deal,
isset($existingCrmIdSet[(string) $deal['id']])
);
if ($syncedOpportunity) {
$syncedOpportunities['success'][] = $syncedOpportunity;
}
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to import opportunity', [
'teamId' => $this->team->getId(),
'crmId' => $deal['id'],
'error' => $e->getMessage(),
]);
$syncedOpportunities['failed_ids'][] = $deal['id'];
$syncedOpportunities['errors'][$deal['id']] = $e->getMessage();
}
}
return $syncedOpportunities;
}
/**
* Prepare associated entities for opportunities with optimized batch processing
* Returns structured data with CRM ID to DB ID mappings for each opportunity
*/
private function prepareAssociatedEntities(array $companyAssociations, array $contactAssociations): array
{
// Step 1: Collect all unique company and contact IDs from associations
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
// Step 2: Batch sync missing entities and get CRM ID to DB ID mappings
$companyIdMappings = [];
$contactIdMappings = [];
if (! empty($allCompanyIds)) {
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
}
if (! empty($allContactIds)) {
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
}
return [
'company_id_mappings' => $companyIdMappings,
'contact_id_mappings' => $contactIdMappings,
];
}
/**
* Flatten association data to get unique IDs
*/
private function flattenAssociationIds(array $associations): array
{
$ids = [];
foreach ($associations as $dealAssociations) {
if (is_array($dealAssociations)) {
foreach ($dealAssociations as $id) {
$ids[$id] = true;
}
}
}
return array_keys($ids);
}
/**
* Batch sync missing accounts
*/
private function prepareAssociatedAccounts(array $companyIds): array
{
// Find which accounts already exist
$existingAccounts = $this->crmEntityRepository
->findAccountsByExternalIds($this->config, $companyIds);
$existingCompanyIds = $existingAccounts->pluck('crm_provider_id')->toArray();
$existingAccountsData = $existingAccounts->mapWithKeys(function ($account) {
return [$account->getCrmProviderId() => $account->getId()];
})->toArray();
$missingCompanyIds = array_diff($companyIds, $existingCompanyIds);
if (empty($missingCompanyIds)) {
return $existingAccountsData;
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing accounts', [
'teamId' => $this->team->getUuid(),
'total_companies' => count($companyIds),
'existing_companies' => count($existingCompanyIds),
'missing_companies' => count($missingCompanyIds),
]);
// we already have limit on opportunity ids count
// Initialize variable before try block
$syncedAccountsData = [];
try {
$syncedAccountsData = $this->batchSyncCrmObjects('companies', $missingCompanyIds);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing accounts', [
'size' => count($missingCompanyIds),
'error' => $e->getMessage(),
]);
$syncedAccountsData = [];
}
return $existingAccountsData + $syncedAccountsData;
}
/**
* Prepare associated contacts - find existing and sync missing ones
* Returns mapping of CRM ID to DB ID
*/
private function prepareAssociatedContacts(array $contactIds): array
{
// Find which contacts already exist
$existingContacts = $this->crmEntityRepository
->findContactsByExternalIds($this->config, $contactIds);
$existingContactIds = $existingContacts->pluck('crm_provider_id')->toArray();
// Create mapping for existing contacts
$existingContactsData = $existingContacts->mapWithKeys(function ($contact) {
return [$contact->getCrmProviderId() => $contact->getId()];
})->toArray();
$missingContactIds = array_diff($contactIds, $existingContactIds);
if (empty($missingContactIds)) {
return $existingContactsData;
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing contacts', [
'teamId' => $this->team->getUuid(),
'total_contacts' => count($contactIds),
'existing_contacts' => count($existingContactIds),
'missing_contacts' => count($missingContactIds),
]);
// Sync missing contacts using batch API
try {
$syncedContactsData = $this->batchSyncCrmObjects('contacts', $missingContactIds);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing contacts', [
'size' => count($missingContactIds),
'error' => $e->getMessage(),
]);
$syncedContactsData = [];
}
return $existingContactsData + $syncedContactsData;
}
private function batchSyncCrmObjects(string $objectType, array $crmIds): array
{
$syncObjects = [];
$crmObjectIds = array_values($crmIds);
foreach (array_chunk($crmObjectIds, self::BATCH_SIZE) as $chunk) {
try {
$objects = $objectType === 'companies' ?
$this->client->getCompaniesByIds($chunk, $this->getCompanyFields()) :
$this->client->getContactsByIds($chunk, $this->getContactFields());
foreach ($objects as $objectId => $objectData) {
$this->importCrmObject($objectType, (string) $objectId, $objectData, $syncObjects);
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch synced ' . $objectType, [
'requested_count' => count($chunk),
'synced_count' => count($objects),
]);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Batch ' . $objectType . ' sync failed', [
'ids' => $chunk,
'error' => $e->getMessage(),
]);
}
}
return $syncObjects;
}
private function importCrmObject(string $objectType, string $objectId, mixed $objectData, array &$syncObjects): void
{
try {
$object = $objectType === 'companies' ?
$this->importAccount($objectData) :
$this->importContact($objectData);
if ($object) {
$syncObjects[$object->getCrmProviderId()] = $object->getId();
}
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to import batch ' . $objectType, [
'id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
/**
* Prepare associations for a single opportunity
*
* The return value is an array with the following structure:
* [
* 'companies' => [
* $companyCrmId => $companyId,
* ...
* ],
* 'contacts' => [
* $contactCrmId => $contactId,
* ...
* ],
* 'account_id' => $accountId,
* ]
*/
private function prepareAssociationsForOpportunity(
string $oppCrmId,
array $companyAssociations,
array $contactAssociations,
array $associationsData
): array {
$associations = [
'companies' => [],
'contacts' => [],
'account_id' => null, // Primary account for opportunity
];
$oppCompanyIds = $companyAssociations[$oppCrmId] ?? [];
foreach ($oppCompanyIds as $companyCrmId) {
if (isset($associationsData['company_id_mappings'][$companyCrmId])) {
$associations['companies'][$companyCrmId] = $associationsData['company_id_mappings'][$companyCrmId];
// Set primary account (first company becomes primary account)
if ($associations['account_id'] === null) {
$associations['account_id'] = $associationsData['company_id_mappings'][$companyCrmId];
}
}
}
$oppContactIds = $contactAssociations[$oppCrmId] ?? [];
foreach ($oppContactIds as $contactCrmId) {
if (isset($associationsData['contact_id_mappings'][$contactCrmId])) {
$associations['contacts'][$contactCrmId] = $associationsData['contact_id_mappings'][$contactCrmId];
}
}
return $associations;
}
/**
* Update only associations for an opportunity
*/
private function updateOpportunityAssociations(Opportunity $opportunity, array $associations): void
{
// Update contact associations
$this->importOpportunityContacts($opportunity, $associations['contacts']);
// Update company (account) associations
$this->updateOpportunityAccount($opportunity, $associations['account_id']);
}
/**
* Remove all contact associations from an opportunity
*/
private function removeAllOpportunityContacts(Opportunity $opportunity): void
{
$currentCount = (int) $opportunity->contacts()->count();
if ($currentCount > 0) {
$opportunity->contacts()->detach();
$this->logger->info('[' . $this->getDisplayName() . '] Removed all contact associations', [
'opportunity_id' => $opportunity->getId(),
'removed_count' => $currentCount,
]);
}
}
private function updateOpportunityAccount(Opportunity $opportunity, ?int $accountId): void
{
if ($accountId === null) {
// No account ID provided - keep current account
return;
}
$currentAccountId = $opportunity->getAccountId();
// Only update if account has changed
if ($currentAccountId !== $accountId) {
$opportunity->account_id = $accountId;
$opportunity->save();
$this->logger->info('[' . $this->getDisplayName() . '] Updated opportunity account association', [
'opportunity_id' => $opportunity->getId(),
'old_account_id' => $currentAccountId,
'new_account_id' => $accountId,
]);
}
}
/**
* Find existing opportunities by external IDs (OPTIMIZED VERSION)
* Uses batch query for better performance
*/
private function findExistingOpportunities(array $crmIds): Collection
{
return $this->crmEntityRepository
->findOpportunitiesByExternalIds($this->config, $crmIds);
}
private function processOpportunityBatch(array $opportunities): int
{
$syncedOpportunities = $this->importOpportunityBatch($opportunities);
return count($syncedOpportunities['success'] ?? []);
}
/**
* Convert single deal associations from HubSpot format to internal format
* Handles both HubSpot SDK objects and array formats
*
* @param array $opportunityAssociations Raw associations from HubSpot API or pre-processed
*
* @return array Processed associations with DB IDs
*/
private function convertDealAssociations(array $opportunityAssociations): array
{
$associations = $this->initializeAssociationsStructure();
if (empty($opportunityAssociations)) {
return $associations;
}
$associationIds = $this->extractAssociationIds($opportunityAssociations);
$this->processCompanyAssociations($associationIds, $associations);
$this->processContactAssociations($associationIds, $associations);
return $associations;
}
private function initializeAssociationsStructure(): array
{
return [
'companies' => [],
'contacts' => [],
'account_id' => null, // Primary account for opportunity
];
}
private function extractAssociationIds(array $opportunityAssociations): array
{
$associationIds = [];
foreach ($opportunityAssociations as $type => $associationData) {
if (! empty($associationData)) {
$associationIds[$type] = $this->convertSingleDealAssociations($associationData);
}
}
return $associationIds;
}
private function processCompanyAssociations(array $associationIds, array &$associations): void
{
if (empty($associationIds['companies'])) {
return;
}
$companyId = $associationIds['companies'][0];
$account = $this->findOrSyncAccount($companyId);
if ($account instanceof Account) {
$associations['companies'][$companyId] = $account->getId();
$associations['account_id'] = $account->getId();
}
}
private function processContactAssociations(array $associationIds, array &$associations): void
{
if (empty($associationIds['contacts'])) {
return;
}
foreach ($associationIds['contacts'] as $contactId) {
$contact = $this->findOrSyncContact($contactId);
if ($contact instanceof Contact) {
$associations['contacts'][$contactId] = $contact->getId();
}
}
}
private function findOrSyncAccount(string $companyId): ?Account
{
$account = $this->crmEntityRepository->findAccountByExternalId($this->config, $companyId);
if (! $account instanceof Account) {
$account = $this->syncAccount($companyId);
}
return $account;
}
private function findOrSyncContact(string $contactId): ?Contact
{
$contact = $this->crmEntityRepository->findContactByExternalId($this->config, $contactId);
if (! $contact instanceof Contact) {
$contact = $this->syncContact($contactId);
}
return $contact;
}
private function convertSingleDealAssociations($opportunityAssociations = null): array
{
$associationData = [];
if ($opportunityAssociations === null) {
return $associationData;
}
// Handle array input (from extractAssociationIds)
if (is_array($opportunityAssociations)) {
return $opportunityAssociations;
}
// Handle CollectionResponseAssociatedId object
if ($opportunityAssociations instanceof CollectionResponseAssociatedId) {
foreach ($opportunityAssociations->getResults() as $association) {
$associationData[] = $association->getId();
}
}
return $associationData;
}
private function importOrUpdateOpportunity($crmData, ?bool $exists = null): ?Opportunity
{
if (empty($crmData['properties'])) {
return null;
}
$crmId = (string) $crmData['id'];
$properties = $crmData['properties'];
$associations = $crmData['associations'] ?? [];
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity($crmId, $properties, $associations);
} else {
return $this->createOpportunity($crmId, $properties, $associations);
}
}
/**
* Create new opportunity
*/
private function createOpportunity(string $crmId, array $properties, array $associations): ?Opportunity
{
$accountId = $this->resolveAccountId($associations);
if (! $accountId) {
return null;
}
$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);
if (! $businessProcess) {
return null;
}
$stage = $this->resolveStage($businessProcess, $properties['dealstage'] ?? null);
if (! $stage) {
return null;
}
$data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);
$attributes = [
'crm_configuration_id' => $this->config->getId(),
'crm_provider_id' => $crmId,
];
$values = array_merge($attributes, $data);
$opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);
$this->importExternalFieldData($properties, $opportunity->getId());
$this->importOpportunityContacts($opportunity, $associations['contacts']);
if ($opportunity->wasRecentlyCreated) {
MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());
}
return $opportunity;
}
/**
* Update existing opportunity
*/
private function updateOpportunity(string $crmId, array $properties, array $associations): Opportunity
{
$accountId = $this->resolveAccountId($associations);
$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);
$stage = $businessProcess ? $this->resolveStage($businessProcess, $properties['dealstage'] ?? null) : null;
$data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);
$attributes = [
'crm_configuration_id' => $this->config->getId(),
'crm_provider_id' => $crmId,
];
$values = array_merge($attributes, $data);
$opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);
$this->importExternalFieldData($properties, $opportunity->getId());
$this->updateOpportunityAssociations($opportunity, $associations);
return $opportunity;
}
private function resolveAccountId(array $associations): ?int
{
if (! empty($associations['accountId'])) {
return $associations['accountId'];
}
if (empty($associations)) {
return null;
}
// we can't resolve multiple account ids (currently SDK returns one company)
foreach ($associations['companies'] as $accountId) {
return $accountId;
}
return null;
}
private function buildOpportunityData(
array $properties,
?int $accountId,
?BusinessProcess $businessProcess,
?Stage $stage
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, (string) $ownerId);
}
$name = 'Unknown';
if (isset($properties['dealname'])) {
$name = mb_strimwidth($properties['dealname'], 0, 128);
}
$amount = $this->resolveAmount($properties);
$currency = $properties['deal_currency_code'] ?? null;
$closeDate = null;
if (! empty($properties['closedate'])) {
$closeDate = Carbon::parse($properties['closedate'])->format('Y-m-d');
}
$remotelyCreatedAt = null;
if (! empty($properties['createdate']) && strtotime($properties['createdate'])) {
$date = $this->parseCleanDatetime($properties['createdate']);
$remotelyCreatedAt = $date?->format('Y-m-d H:i:s');
}
$closedStages = $this->getClosedDealStages();
$isWon = in_array($properties['dealstage'], $closedStages['won']);
$isLost = in_array($properties['dealstage'], $closedStages['lost']);
$data = [
'team_id' => $this->team->getId(),
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => $name,
'value' => ! empty($amount) ? $amount : null,
'currency_code' => CurrencyFormatter::formatCode($currency),
'close_date' => $closeDate,
'is_closed' => $isWon || $isLost,
'is_won' => $isWon,
'remotely_created_at' => $remotelyCreatedAt,
'probability' => $this->resolveDealProbability($properties['hs_deal_stage_probability']),
'forecast_category' => $this->resolveForecastCategory($properties['hs_manual_forecast_category']),
];
if ($accountId) {
$data['account_id'] = $accountId;
}
if ($stage) {
$data['stage_id'] = $stage->id;
}
if ($businessProcess) {
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
if (isset($this->cachedBusinessProcesses[$pipelineId])) {
return $this->cachedBusinessProcesses[$pipelineId];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$pipelineId] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $businessProcess->getId() . ':' . $stageId;
if (isset($this->cachedStages[$cacheKey])) {
return $this->cachedStages[$cacheKey];
}
$stage = $this->crmEntityRepository->getPipelineStageByConditions(
$businessProcess,
[
'crm_provider_id' => $stageId,
'type' => Stage::TYPE_OPPORTUNITY,
]
);
if ($stage === null) {
$this->importStages(null, $stageId);
}
if ($stage === null) {
$this->logger->info('[HubSpot] Stage does not exist => ' . $stageId);
}
$this->cachedStages[$cacheKey] = $stage;
return $stage;
}
private function resolveAmount(array $properties): ?string
{
$amount = null;
if (! empty($properties['amount'])) {
$amount = str_replace(',', '', $properties['amount']);
}
if ($this->config->hasDefaultCurrencyFieldSet()) {
$valueFieldName = $this->config->getDefaultCurrencyField()->getCrmProviderId();
$amount = $properties[$valueFieldName] ?? $amount;
}
return $amount;
}
private function parseCleanDatetime(string $datetime): ?Carbon
{
// Treat pre-1980 values as invalid
$minValidDate = Carbon::parse('1980-01-01 00:00:00');
try {
$date = Carbon::parse($datetime);
if ($minValidDate->gt($date)) {
return null;
}
return $date;
} catch (Exception) {
return null; // On parse error, treat as null
}
}
private function resolveDealProbability(?string $stageProbability): int
{
if ($stageProbability === null) {
return 0;
}
$probability = (float) $stageProbability;
return $probability > 1 ? 0 : (int) ($probability * 100);
}
private function resolveForecastCategory(?string $forecastCategory): string
{
if (! $forecastCategory) {
return Forecast::FORECAST_CATEGORY_UNCATEGORIZED;
}
$forecastCategory = str_replace('_', ' ', $forecastCategory);
return ucwords(strtolower($forecastCategory));
}
private function importExternalFieldData(array $properties, int $opportunityId): void
{
$crmFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData($properties, $crmFields, $opportunityId);
}
private function importOpportunityContacts(Opportunity $opportunity, array $associations): void
{
// Handle empty or missing contact associations
if (empty($associations)) {
// Remove all existing contact associations if none provided
$this->removeAllOpportunityContacts($opportunity);
return;
}
// Use differential sync approach for better performance and accuracy
$this->syncOpportunityContactsDifferential($opportunity, $associations);
}
/**
* Sync opportunity contacts using differential approach
* This compares current vs new associations and only makes necessary changes
*/
private function syncOpportunityContactsDifferential(Opportunity $opportunity, array $contactAssociations): void
{
$currentContactCrmIds = $this->getCurrentContactCrmIds($opportunity);
$contactAssociationIds = array_keys($contactAssociations);
$contactsToAdd = array_diff($contactAssociationIds, $currentContactCrmIds);
$contactsToRemove = array_diff($currentContactCrmIds, $contactAssociationIds);
if (empty($contactsToAdd) && empty($contactsToRemove)) {
return;
}
$this->logContactAssociationChanges($opportunity, $currentContactCrmIds, $contactAssociations, $contactsToAdd, $contactsToRemove);
$this->removeContactAssociations($opportunity, $contactsToRemove);
$this->addContactAssociations($opportunity, $contactsToAdd, $contactAssociations);
}
private function getCurrentContactCrmIds(Opportunity $opportunity): array
{
return $opportunity->contacts()
->pluck('contacts.crm_provider_id')
->toArray();
}
private function logContactAssociationChanges(
Opportunity $opportunity,
array $currentContactCrmIds,
array $contactAssociations,
array $contactsToAdd,
array $contactsToRemove
): void {
$this->logger->info('[' . $this->getDisplayName() . '] Contact association changes', [
'opportunity_id' => $opportunity->getId(),
'current_contacts' => $currentContactCrmIds,
'new_contacts' => $contactAssociations,
'contacts_to_add' => $contactsToAdd,
'contacts_to_remove' => $contactsToRemove,
]);
}
private function removeContactAssociations(Opportunity $opportunity, array $contactsToRemove): void
{
if (empty($contactsToRemove)) {
return;
}
$contactsToDetach = $opportunity->contacts()
->whereIn('contacts.crm_provider_id', $contactsToRemove)
->pluck('contacts.id')
->toArray();
if (! empty($contactsToDetach)) {
$opportunity->contacts()->detach($contactsToDetach);
$this->logger->info('[' . $this->getDisplayName() . '] Removed contact associations', [
'opportunity_id' => $opportunity->getId(),
'removed_contact_crm_ids' => $contactsToRemove,
'removed_contact_count' => count($contactsToDetach),
]);
}
}
private function addContactAssociations(Opportunity $opportunity, array $contactsToAdd, array $contactAssociations): void
{
if (empty($contactsToAdd)) {
return;
}
$contactsAdded = [];
foreach ($contactsToAdd as $crmId) {
$id = $contactAssociations[$crmId];
if ($this->attachSingleContact($opportunity, (string) $crmId, $id)) {
$contactsAdded[] = $crmId;
}
}
$this->logAddedContacts($opportunity, $contactsAdded);
}
private function attachSingleContact(Opportunity $opportunity, string $crmId, int $id): bool
{
try {
$contact = $this->crmEntityRepository->findContactByConfigurationAndId($this->config, $id);
if (! $contact) {
return false;
}
return $this->performContactAttachment($opportunity, $contact, $crmId);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to add contact association', [
'opportunity_id' => $opportunity->getId(),
'contact_crm_id' => $crmId,
'error' => $e->getMessage(),
]);
return false;
}
}
private function performContactAttachment(Opportunity $opportunity, Contact $contact, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contact->getId(), [
'crm_provider_id' => $crmId,
]);
return true;
} catch (\Illuminate\Database\QueryException $e) {
if (str_contains($e->getMessage(), 'Duplicate entry')) {
$this->logger->info('[' . $this->getDisplayName() . '] Contact association already exists', [
'contact_id' => $contact->getId(),
'contact_crm_id' => $crmId,
'opportunity_id' => $opportunity->getId(),
]);
return false;
}
throw $e;
}
}
private function logAddedContacts(Opportunity $opportunity, array $contactsAdded): void
{
if (! empty($contactsAdded)) {
$this->logger->info('[' . $this->getDisplayName() . '] Added contact associations', [
'opportunity_id' => $opportunity->getId(),
'contacts_to_add_count' => count($contactsAdded),
'added_contact_crm_ids' => $contactsAdded,
'added_contacts_count' => count($contactsAdded),
]);
}
}
}
Execute
Explain Plan
Browse Query History
View Parameters
Open Query Execution Settings…
In-Editor Results...
|
NULL
|
|
44534
|
941
|
0
|
2026-04-17T08:51:33.982892+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776415893982_m1.jpg...
|
PhpStorm
|
faVsco.js – console [EU]
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
"podcast_audio_url"
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
0 results
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Code changed:
Hide
Sync Changes
Hide This Notification
32
2
19
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\ServiceTraits;
use Carbon\Carbon;
use HubSpot\Client\Crm\Deals\Model\CollectionResponseAssociatedId;
use Jiminny\Exceptions\InvalidArgumentException;
use Jiminny\Models\Account;
use Exception;
use Jiminny\Component\DealInsights\Forecast\Forecast;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Exceptions\CrmException;
use Jiminny\Models\Opportunity;
use Illuminate\Support\Collection;
use Jiminny\Models\Stage;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Services\Crm\Hubspot\DealFieldsService;
use Jiminny\Services\Crm\Hubspot\OpportunitySyncStrategy\HubspotSingleSyncStrategy;
use Jiminny\Services\Crm\Hubspot\WebhookSyncBatchProcessor;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
/**
* Optimized sync methods for better performance
* These methods can be integrated into SyncCrmEntitiesTrait for significant performance gains
*/
trait OpportunitySyncTrait
{
private const int BATCH_SIZE = 100;
private const int BATCH_PROCESS_SIZE = 800;
protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
protected CrmEntityRepository $crmEntityRepository;
protected DealFieldsService $dealFieldsService;
private ?array $cachedClosedDealStages = null;
private array $cachedBusinessProcesses = [];
private array $cachedStages = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' .
$strategyName
);
$total = 0;
$lastId = null;
$buffer = [];
// HubspotWebhookBatchSyncStrategy returns empty generator, this is for other strategies
foreach ($syncStrategy->fetchOpportunities($parameters, $total, $lastId) as $hsOpportunity) {
$buffer[] = $hsOpportunity;
// process every 800 rows (fits < 1 000 association limit)
if (\count($buffer) >= self::BATCH_PROCESS_SIZE) {
$syncCount += $this->processOpportunityBatch($buffer);
$buffer = [];
}
}
// leftovers
if ($buffer) {
$syncCount += $this->processOpportunityBatch($buffer);
}
$reportedTotal += $total;
$lastSyncedId = $lastId;
}
} catch (\HubSpot\Client\Crm\Deals\ApiException | CrmException $e) {
$this->handleSyncException($e, $parameters);
}
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
]
);
return $reportedTotal;
}
private function handleSyncException(\Throwable $e, array $parameters): void
{
if (($parameters['since'] ?? null) instanceof Carbon) {
$parameters['since'] = $parameters['since']->toDateTimeString();
}
$parameters['config'] = $this->config->getId();
$this->logger->warning('[' . $this->getDisplayName() . '] Sync opportunities failed', [
'teamId' => $this->team->getUuid(),
'parameters' => $parameters,
'reason' => $e->getMessage(),
]);
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,
);
$parameters = [
'config' => $this->config,
'crm_id' => $crmId,
];
try {
if (! $strategy instanceof HubspotSingleSyncStrategy) {
throw new InvalidArgumentException('Strategy must by HubspotSingleSyncStrategy');
}
$hsOpportunity = $strategy->fetchOpportunity($parameters);
} catch (\HubSpot\Client\Crm\Deals\ApiException $e) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [
'teamId' => $this->team->getUuid(),
'crmId' => $crmId,
'reason' => $e->getMessage(),
]);
return null;
}
$hsOpportunity['associations'] = $this->convertDealAssociations($hsOpportunity['associations'] ?? []);
return $this->importOrUpdateOpportunity($hsOpportunity);
}
/**
* Process webhook-collected opportunity batches.
*
* Drains Redis sets containing company CRM IDs collected from webhook events
* and dispatches ImportOpportunityBatch jobs for batch processing.
*
* @return int Number of opportunity IDs dispatched to jobs
*/
public function batchSyncOpportunities(): int
{
$configId = $this->team->getCrmConfiguration()->getId();
return $this->batchProcessor->processBatchesForObjectType(
WebhookSyncBatchProcessor::OBJECT_TYPE_DEAL,
$configId
);
}
/**
* Import a batch of opportunities by their CRM IDs.
* Fetches opportunity data from HubSpot API and delegates to importOpportunityBatch().
*
* @param array<string> $crmIds HubSpot deal CRM IDs
*
* @return array{success: array, failed_ids: array, errors?: array<string, string>}
*/
public function importOpportunityBatchByIds(array $crmIds): array
{
$fields = $this->dealFieldsService->getFieldsForConfiguration($this->config);
$allDeals = [];
foreach (array_chunk($crmIds, self::BATCH_SIZE) as $chunk) {
$deals = $this->client->getOpportunitiesByIds($chunk, $fields);
foreach ($deals as $deal) {
$allDeals[] = $deal;
}
}
// IDs not returned by HubSpot are likely deleted or inaccessible deals.
// These are not failures — retrying won't bring them back.
$fetchedIds = array_map('strval', array_column($allDeals, 'id'));
$notFoundIds = array_values(array_diff(array_map('strval', $crmIds), $fetchedIds));
if (! empty($notFoundIds)) {
$this->logger->info('[' . $this->getDisplayName() . '] CRM IDs not found in HubSpot (likely deleted)', [
'teamId' => $this->team->getId(),
'notFoundCount' => \count($notFoundIds),
'notFoundIds' => $notFoundIds,
'requestedCount' => \count($crmIds),
'fetchedCount' => \count($allDeals),
]);
}
if (empty($allDeals)) {
return ['success' => [], 'failed_ids' => []];
}
return $this->importOpportunityBatch($allDeals);
}
private function getClosedDealStages(): array
{
if ($this->cachedClosedDealStages !== null) {
return $this->cachedClosedDealStages;
}
$stages = $this->crmEntityRepository->getOpportunityClosedStages($this->config);
$data = [
'lost' => [],
'won' => [],
];
foreach ($stages as $stage) {
if ($stage->probability == 0.00) {
$data['lost'][] = $stage->crm_provider_id;
}
if ($stage->probability == 100.00) {
$data['won'][] = $stage->crm_provider_id;
}
}
$this->cachedClosedDealStages = $data;
return $data;
}
/**
* Import deals into the database with pre-fetched associations.
*
* API calls here (getAssociationsData, getExistingOpportunityCrmIds) are NOT
* caught — if they throw, the exception propagates to ImportOpportunityBatch::handle()
* where Laravel retries the whole job with backoff. After all retries exhausted,
* failed() requeues all IDs to Redis.
*
* The per-deal loop catches exceptions individually. A deal can end up in three states:
* - success: imported/updated successfully
* - failed_ids: exception thrown (DB constraint violation, corrupt data, etc.)
* These are permanent issues — retrying won't fix them.
* - skipped (null): missing dependencies (no account, unknown pipeline/stage).
* This is acceptable — the deal cannot be imported until those exist.
*/
private function importOpportunityBatch(array $deals): array
{
$syncedOpportunities = [
'success' => [],
'failed_ids' => [],
];
$dealIds = array_column($deals, 'id');
// Shared association/existing-ID preparation is batch-level state. If it fails, rethrow so the
// queue job retries the whole batch and eventually requeues all deal IDs back to Redis.
try {
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$associationsData = $this->prepareAssociatedEntities($companyAssociations, $contactAssociations);
$existingCrmIds = $this->crmEntityRepository->getExistingOpportunityCrmIds(
$this->config,
array_map('strval', $dealIds)
);
$existingCrmIdSet = array_flip($existingCrmIds);
} catch (\Throwable $e) {
$this->logger->error('[' . $this->getDisplayName() . '] Failed to fetch associations or existing IDs', [
'teamId' => $this->team->getId(),
'dealCount' => count($dealIds),
'error' => $e->getMessage(),
]);
throw $e;
}
foreach ($deals as $deal) {
try {
$deal['associations'] = $this->prepareAssociationsForOpportunity(
$deal['id'],
$companyAssociations,
$contactAssociations,
$associationsData
);
$syncedOpportunity = $this->importOrUpdateOpportunity(
$deal,
isset($existingCrmIdSet[(string) $deal['id']])
);
if ($syncedOpportunity) {
$syncedOpportunities['success'][] = $syncedOpportunity;
}
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to import opportunity', [
'teamId' => $this->team->getId(),
'crmId' => $deal['id'],
'error' => $e->getMessage(),
]);
$syncedOpportunities['failed_ids'][] = $deal['id'];
$syncedOpportunities['errors'][$deal['id']] = $e->getMessage();
}
}
return $syncedOpportunities;
}
/**
* Prepare associated entities for opportunities with optimized batch processing
* Returns structured data with CRM ID to DB ID mappings for each opportunity
*/
private function prepareAssociatedEntities(array $companyAssociations, array $contactAssociations): array
{
// Step 1: Collect all unique company and contact IDs from associations
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
// Step 2: Batch sync missing entities and get CRM ID to DB ID mappings
$companyIdMappings = [];
$contactIdMappings = [];
if (! empty($allCompanyIds)) {
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
}
if (! empty($allContactIds)) {
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
}
return [
'company_id_mappings' => $companyIdMappings,
'contact_id_mappings' => $contactIdMappings,
];
}
/**
* Flatten association data to get unique IDs
*/
private function flattenAssociationIds(array $associations): array
{
$ids = [];
foreach ($associations as $dealAssociations) {
if (is_array($dealAssociations)) {
foreach ($dealAssociations as $id) {
$ids[$id] = true;
}
}
}
return array_keys($ids);
}
/**
* Batch sync missing accounts
*/
private function prepareAssociatedAccounts(array $companyIds): array
{
// Find which accounts already exist
$existingAccounts = $this->crmEntityRepository
->findAccountsByExternalIds($this->config, $companyIds);
$existingCompanyIds = $existingAccounts->pluck('crm_provider_id')->toArray();
$existingAccountsData = $existingAccounts->mapWithKeys(function ($account) {
return [$account->getCrmProviderId() => $account->getId()];
})->toArray();
$missingCompanyIds = array_diff($companyIds, $existingCompanyIds);
if (empty($missingCompanyIds)) {
return $existingAccountsData;
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing accounts', [
'teamId' => $this->team->getUuid(),
'total_companies' => count($companyIds),
'existing_companies' => count($existingCompanyIds),
'missing_companies' => count($missingCompanyIds),
]);
// we already have limit on opportunity ids count
// Initialize variable before try block
$syncedAccountsData = [];
try {
$syncedAccountsData = $this->batchSyncCrmObjects('companies', $missingCompanyIds);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing accounts', [
'size' => count($missingCompanyIds),
'error' => $e->getMessage(),
]);
$syncedAccountsData = [];
}
return $existingAccountsData + $syncedAccountsData;
}
/**
* Prepare associated contacts - find existing and sync missing ones
* Returns mapping of CRM ID to DB ID
*/
private function prepareAssociatedContacts(array $contactIds): array
{
// Find which contacts already exist
$existingContacts = $this->crmEntityRepository
->findContactsByExternalIds($this->config, $contactIds);
$existingContactIds = $existingContacts->pluck('crm_provider_id')->toArray();
// Create mapping for existing contacts
$existingContactsData = $existingContacts->mapWithKeys(function ($contact) {
return [$contact->getCrmProviderId() => $contact->getId()];
})->toArray();
$missingContactIds = array_diff($contactIds, $existingContactIds);
if (empty($missingContactIds)) {
return $existingContactsData;
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing contacts', [
'teamId' => $this->team->getUuid(),
'total_contacts' => count($contactIds),
'existing_contacts' => count($existingContactIds),
'missing_contacts' => count($missingContactIds),
]);
// Sync missing contacts using batch API
try {
$syncedContactsData = $this->batchSyncCrmObjects('contacts', $missingContactIds);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing contacts', [
'size' => count($missingContactIds),
'error' => $e->getMessage(),
]);
$syncedContactsData = [];
}
return $existingContactsData + $syncedContactsData;
}
private function batchSyncCrmObjects(string $objectType, array $crmIds): array
{
$syncObjects = [];
$crmObjectIds = array_values($crmIds);
foreach (array_chunk($crmObjectIds, self::BATCH_SIZE) as $chunk) {
try {
$objects = $objectType === 'companies' ?
$this->client->getCompaniesByIds($chunk, $this->getCompanyFields()) :
$this->client->getContactsByIds($chunk, $this->getContactFields());
foreach ($objects as $objectId => $objectData) {
$this->importCrmObject($objectType, (string) $objectId, $objectData, $syncObjects);
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch synced ' . $objectType, [
'requested_count' => count($chunk),
'synced_count' => count($objects),
]);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Batch ' . $objectType . ' sync failed', [
'ids' => $chunk,
'error' => $e->getMessage(),
]);
}
}
return $syncObjects;
}
private function importCrmObject(string $objectType, string $objectId, mixed $objectData, array &$syncObjects): void
{
try {
$object = $objectType === 'companies' ?
$this->importAccount($objectData) :
$this->importContact($objectData);
if ($object) {
$syncObjects[$object->getCrmProviderId()] = $object->getId();
}
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to import batch ' . $objectType, [
'id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
/**
* Prepare associations for a single opportunity
*
* The return value is an array with the following structure:
* [
* 'companies' => [
* $companyCrmId => $companyId,
* ...
* ],
* 'contacts' => [
* $contactCrmId => $contactId,
* ...
* ],
* 'account_id' => $accountId,
* ]
*/
private function prepareAssociationsForOpportunity(
string $oppCrmId,
array $companyAssociations,
array $contactAssociations,
array $associationsData
): array {
$associations = [
'companies' => [],
'contacts' => [],
'account_id' => null, // Primary account for opportunity
];
$oppCompanyIds = $companyAssociations[$oppCrmId] ?? [];
foreach ($oppCompanyIds as $companyCrmId) {
if (isset($associationsData['company_id_mappings'][$companyCrmId])) {
$associations['companies'][$companyCrmId] = $associationsData['company_id_mappings'][$companyCrmId];
// Set primary account (first company becomes primary account)
if ($associations['account_id'] === null) {
$associations['account_id'] = $associationsData['company_id_mappings'][$companyCrmId];
}
}
}
$oppContactIds = $contactAssociations[$oppCrmId] ?? [];
foreach ($oppContactIds as $contactCrmId) {
if (isset($associationsData['contact_id_mappings'][$contactCrmId])) {
$associations['contacts'][$contactCrmId] = $associationsData['contact_id_mappings'][$contactCrmId];
}
}
return $associations;
}
/**
* Update only associations for an opportunity
*/
private function updateOpportunityAssociations(Opportunity $opportunity, array $associations): void
{
// Update contact associations
$this->importOpportunityContacts($opportunity, $associations['contacts']);
// Update company (account) associations
$this->updateOpportunityAccount($opportunity, $associations['account_id']);
}
/**
* Remove all contact associations from an opportunity
*/
private function removeAllOpportunityContacts(Opportunity $opportunity): void
{
$currentCount = (int) $opportunity->contacts()->count();
if ($currentCount > 0) {
$opportunity->contacts()->detach();
$this->logger->info('[' . $this->getDisplayName() . '] Removed all contact associations', [
'opportunity_id' => $opportunity->getId(),
'removed_count' => $currentCount,
]);
}
}
private function updateOpportunityAccount(Opportunity $opportunity, ?int $accountId): void
{
if ($accountId === null) {
// No account ID provided - keep current account
return;
}
$currentAccountId = $opportunity->getAccountId();
// Only update if account has changed
if ($currentAccountId !== $accountId) {
$opportunity->account_id = $accountId;
$opportunity->save();
$this->logger->info('[' . $this->getDisplayName() . '] Updated opportunity account association', [
'opportunity_id' => $opportunity->getId(),
'old_account_id' => $currentAccountId,
'new_account_id' => $accountId,
]);
}
}
/**
* Find existing opportunities by external IDs (OPTIMIZED VERSION)
* Uses batch query for better performance
*/
private function findExistingOpportunities(array $crmIds): Collection
{
return $this->crmEntityRepository
->findOpportunitiesByExternalIds($this->config, $crmIds);
}
private function processOpportunityBatch(array $opportunities): int
{
$syncedOpportunities = $this->importOpportunityBatch($opportunities);
return count($syncedOpportunities['success'] ?? []);
}
/**
* Convert single deal associations from HubSpot format to internal format
* Handles both HubSpot SDK objects and array formats
*
* @param array $opportunityAssociations Raw associations from HubSpot API or pre-processed
*
* @return array Processed associations with DB IDs
*/
private function convertDealAssociations(array $opportunityAssociations): array
{
$associations = $this->initializeAssociationsStructure();
if (empty($opportunityAssociations)) {
return $associations;
}
$associationIds = $this->extractAssociationIds($opportunityAssociations);
$this->processCompanyAssociations($associationIds, $associations);
$this->processContactAssociations($associationIds, $associations);
return $associations;
}
private function initializeAssociationsStructure(): array
{
return [
'companies' => [],
'contacts' => [],
'account_id' => null, // Primary account for opportunity
];
}
private function extractAssociationIds(array $opportunityAssociations): array
{
$associationIds = [];
foreach ($opportunityAssociations as $type => $associationData) {
if (! empty($associationData)) {
$associationIds[$type] = $this->convertSingleDealAssociations($associationData);
}
}
return $associationIds;
}
private function processCompanyAssociations(array $associationIds, array &$associations): void
{
if (empty($associationIds['companies'])) {
return;
}
$companyId = $associationIds['companies'][0];
$account = $this->findOrSyncAccount($companyId);
if ($account instanceof Account) {
$associations['companies'][$companyId] = $account->getId();
$associations['account_id'] = $account->getId();
}
}
private function processContactAssociations(array $associationIds, array &$associations): void
{
if (empty($associationIds['contacts'])) {
return;
}
foreach ($associationIds['contacts'] as $contactId) {
$contact = $this->findOrSyncContact($contactId);
if ($contact instanceof Contact) {
$associations['contacts'][$contactId] = $contact->getId();
}
}
}
private function findOrSyncAccount(string $companyId): ?Account
{
$account = $this->crmEntityRepository->findAccountByExternalId($this->config, $companyId);
if (! $account instanceof Account) {
$account = $this->syncAccount($companyId);
}
return $account;
}
private function findOrSyncContact(string $contactId): ?Contact
{
$contact = $this->crmEntityRepository->findContactByExternalId($this->config, $contactId);
if (! $contact instanceof Contact) {
$contact = $this->syncContact($contactId);
}
return $contact;
}
private function convertSingleDealAssociations($opportunityAssociations = null): array
{
$associationData = [];
if ($opportunityAssociations === null) {
return $associationData;
}
// Handle array input (from extractAssociationIds)
if (is_array($opportunityAssociations)) {
return $opportunityAssociations;
}
// Handle CollectionResponseAssociatedId object
if ($opportunityAssociations instanceof CollectionResponseAssociatedId) {
foreach ($opportunityAssociations->getResults() as $association) {
$associationData[] = $association->getId();
}
}
return $associationData;
}
private function importOrUpdateOpportunity($crmData, ?bool $exists = null): ?Opportunity
{
if (empty($crmData['properties'])) {
return null;
}
$crmId = (string) $crmData['id'];
$properties = $crmData['properties'];
$associations = $crmData['associations'] ?? [];
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity($crmId, $properties, $associations);
} else {
return $this->createOpportunity($crmId, $properties, $associations);
}
}
/**
* Create new opportunity
*/
private function createOpportunity(string $crmId, array $properties, array $associations): ?Opportunity
{
$accountId = $this->resolveAccountId($associations);
if (! $accountId) {
return null;
}
$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);
if (! $businessProcess) {
return null;
}
$stage = $this->resolveStage($businessProcess, $properties['dealstage'] ?? null);
if (! $stage) {
return null;
}
$data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);
$attributes = [
'crm_configuration_id' => $this->config->getId(),
'crm_provider_id' => $crmId,
];
$values = array_merge($attributes, $data);
$opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);
$this->importExternalFieldData($properties, $opportunity->getId());
$this->importOpportunityContacts($opportunity, $associations['contacts']);
if ($opportunity->wasRecentlyCreated) {
MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());
}
return $opportunity;
}
/**
* Update existing opportunity
*/
private function updateOpportunity(string $crmId, array $properties, array $associations): Opportunity
{
$accountId = $this->resolveAccountId($associations);
$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);
$stage = $businessProcess ? $this->resolveStage($businessProcess, $properties['dealstage'] ?? null) : null;
$data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);
$attributes = [
'crm_configuration_id' => $this->config->getId(),
'crm_provider_id' => $crmId,
];
$values = array_merge($attributes, $data);
$opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);
$this->importExternalFieldData($properties, $opportunity->getId());
$this->updateOpportunityAssociations($opportunity, $associations);
return $opportunity;
}
private function resolveAccountId(array $associations): ?int
{
if (! empty($associations['accountId'])) {
return $associations['accountId'];
}
if (empty($associations)) {
return null;
}
// we can't resolve multiple account ids (currently SDK returns one company)
foreach ($associations['companies'] as $accountId) {
return $accountId;
}
return null;
}
private function buildOpportunityData(
array $properties,
?int $accountId,
?BusinessProcess $businessProcess,
?Stage $stage
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, (string) $ownerId);
}
$name = 'Unknown';
if (isset($properties['dealname'])) {
$name = mb_strimwidth($properties['dealname'], 0, 128);
}
$amount = $this->resolveAmount($properties);
$currency = $properties['deal_currency_code'] ?? null;
$closeDate = null;
if (! empty($properties['closedate'])) {
$closeDate = Carbon::parse($properties['closedate'])->format('Y-m-d');
}
$remotelyCreatedAt = null;
if (! empty($properties['createdate']) && strtotime($properties['createdate'])) {
$date = $this->parseCleanDatetime($properties['createdate']);
$remotelyCreatedAt = $date?->format('Y-m-d H:i:s');
}
$closedStages = $this->getClosedDealStages();
$isWon = in_array($properties['dealstage'], $closedStages['won']);
$isLost = in_array($properties['dealstage'], $closedStages['lost']);
$data = [
'team_id' => $this->team->getId(),
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => $name,
'value' => ! empty($amount) ? $amount : null,
'currency_code' => CurrencyFormatter::formatCode($currency),
'close_date' => $closeDate,
'is_closed' => $isWon || $isLost,
'is_won' => $isWon,
'remotely_created_at' => $remotelyCreatedAt,
'probability' => $this->resolveDealProbability($properties['hs_deal_stage_probability']),
'forecast_category' => $this->resolveForecastCategory($properties['hs_manual_forecast_category']),
];
if ($accountId) {
$data['account_id'] = $accountId;
}
if ($stage) {
$data['stage_id'] = $stage->id;
}
if ($businessProcess) {
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
if (isset($this->cachedBusinessProcesses[$pipelineId])) {
return $this->cachedBusinessProcesses[$pipelineId];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$pipelineId] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $businessProcess->getId() . ':' . $stageId;
if (isset($this->cachedStages[$cacheKey])) {
return $this->cachedStages[$cacheKey];
}
$stage = $this->crmEntityRepository->getPipelineStageByConditions(
$businessProcess,
[
'crm_provider_id' => $stageId,
'type' => Stage::TYPE_OPPORTUNITY,
]
);
if ($stage === null) {
$this->importStages(null, $stageId);
}
if ($stage === null) {
$this->logger->info('[HubSpot] Stage does not exist => ' . $stageId);
}
$this->cachedStages[$cacheKey] = $stage;
return $stage;
}
private function resolveAmount(array $properties): ?string
{
$amount = null;
if (! empty($properties['amount'])) {
$amount = str_replace(',', '', $properties['amount']);
}
if ($this->config->hasDefaultCurrencyFieldSet()) {
$valueFieldName = $this->config->getDefaultCurrencyField()->getCrmProviderId();
$amount = $properties[$valueFieldName] ?? $amount;
}
return $amount;
}
private function parseCleanDatetime(string $datetime): ?Carbon
{
// Treat pre-1980 values as invalid
$minValidDate = Carbon::parse('1980-01-01 00:00:00');
try {
$date = Carbon::parse($datetime);
if ($minValidDate->gt($date)) {
return null;
}
return $date;
} catch (Exception) {
return null; // On parse error, treat as null
}
}
private function resolveDealProbability(?string $stageProbability): int
{
if ($stageProbability === null) {
return 0;
}
$probability = (float) $stageProbability;
return $probability > 1 ? 0 : (int) ($probability * 100);
}
private function resolveForecastCategory(?string $forecastCategory): string
{
if (! $forecastCategory) {
return Forecast::FORECAST_CATEGORY_UNCATEGORIZED;
}
$forecastCategory = str_replace('_', ' ', $forecastCategory);
return ucwords(strtolower($forecastCategory));
}
private function importExternalFieldData(array $properties, int $opportunityId): void
{
$crmFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData($properties, $crmFields, $opportunityId);
}
private function importOpportunityContacts(Opportunity $opportunity, array $associations): void
{
// Handle empty or missing contact associations
if (empty($associations)) {
// Remove all existing contact associations if none provided
$this->removeAllOpportunityContacts($opportunity);
return;
}
// Use differential sync approach for better performance and accuracy
$this->syncOpportunityContactsDifferential($opportunity, $associations);
}
/**
* Sync opportunity contacts using differential approach
* This compares current vs new associations and only makes necessary changes
*/
private function syncOpportunityContactsDifferential(Opportunity $opportunity, array $contactAssociations): void
{
$currentContactCrmIds = $this->getCurrentContactCrmIds($opportunity);
$contactAssociationIds = array_keys($contactAssociations);
$contactsToAdd = array_diff($contactAssociationIds, $currentContactCrmIds);
$contactsToRemove = array_diff($currentContactCrmIds, $contactAssociationIds);
if (empty($contactsToAdd) && empty($contactsToRemove)) {
return;
}
$this->logContactAssociationChanges($opportunity, $currentContactCrmIds, $contactAssociations, $contactsToAdd, $contactsToRemove);
$this->removeContactAssociations($opportunity, $contactsToRemove);
$this->addContactAssociations($opportunity, $contactsToAdd, $contactAssociations);
}
private function getCurrentContactCrmIds(Opportunity $opportunity): array
{
return $opportunity->contacts()
->pluck('contacts.crm_provider_id')
->toArray();
}
private function logContactAssociationChanges(
Opportunity $opportunity,
array $currentContactCrmIds,
array $contactAssociations,
array $contactsToAdd,
array $contactsToRemove
): void {
$this->logger->info('[' . $this->getDisplayName() . '] Contact association changes', [
'opportunity_id' => $opportunity->getId(),
'current_contacts' => $currentContactCrmIds,
'new_contacts' => $contactAssociations,
'contacts_to_add' => $contactsToAdd,
'contacts_to_remove' => $contactsToRemove,
]);
}
private function removeContactAssociations(Opportunity $opportunity, array $contactsToRemove): void
{
if (empty($contactsToRemove)) {
return;
}
$contactsToDetach = $opportunity->contacts()
->whereIn('contacts.crm_provider_id', $contactsToRemove)
->pluck('contacts.id')
->toArray();
if (! empty($contactsToDetach)) {
$opportunity->contacts()->detach($contactsToDetach);
$this->logger->info('[' . $this->getDisplayName() . '] Removed contact associations', [
'opportunity_id' => $opportunity->getId(),
'removed_contact_crm_ids' => $contactsToRemove,
'removed_contact_count' => count($contactsToDetach),
]);
}
}
private function addContactAssociations(Opportunity $opportunity, array $contactsToAdd, array $contactAssociations): void
{
if (empty($contactsToAdd)) {
return;
}
$contactsAdded = [];
foreach ($contactsToAdd as $crmId) {
$id = $contactAssociations[$crmId];
if ($this->attachSingleContact($opportunity, (string) $crmId, $id)) {
$contactsAdded[] = $crmId;
}
}
$this->logAddedContacts($opportunity, $contactsAdded);
}
private function attachSingleContact(Opportunity $opportunity, string $crmId, int $id): bool
{
try {
$contact = $this->crmEntityRepository->findContactByConfigurationAndId($this->config, $id);
if (! $contact) {
return false;
}
return $this->performContactAttachment($opportunity, $contact, $crmId);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to add contact association', [
'opportunity_id' => $opportunity->getId(),
'contact_crm_id' => $crmId,
'error' => $e->getMessage(),
]);
return false;
}
}
private function performContactAttachment(Opportunity $opportunity, Contact $contact, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contact->getId(), [
'crm_provider_id' => $crmId,
]);
return true;
} catch (\Illuminate\Database\QueryException $e) {
if (str_contains($e->getMessage(), 'Duplicate entry')) {
$this->logger->info('[' . $this->getDisplayName() . '] Contact association already exists', [
'contact_id' => $contact->getId(),
'contact_crm_id' => $crmId,
'opportunity_id' => $opportunity->getId(),
]);
return false;
}
throw $e;
}
}
private function logAddedContacts(Opportunity $opportunity, array $contactsAdded): void
{
if (! empty($contactsAdded)) {
$this->logger->info('[' . $this->getDisplayName() . '] Added contact associations', [
'opportunity_id' => $opportunity->getId(),
'contacts_to_add_count' => count($contactsAdded),
'added_contact_crm_ids' => $contactsAdded,
'added_contacts_count' => count($contactsAdded),
]);
}
}
}
Execute...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#11894 on JY-18909-automated-reports-ask-jiminny, menu","depth":5,"help_text":"Pull request #11894 exists for current branch JY-18909-automated-reports-ask-jiminny, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AutomatedReportsCommandTest","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AutomatedReportsCommandTest'","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AutomatedReportsCommandTest'","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Show Replace Field","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Search History","depth":3,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"\"podcast_audio_url\"","depth":4,"value":"\"podcast_audio_url\"","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"New Line","depth":3,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Match Case","depth":3,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Words","depth":3,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Regex","depth":3,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Replace History","depth":3,"bounds":{"left":0.0,"top":0.0,"width":0.015277778,"height":0.024444444},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextField","text":"Replace","depth":4,"role_description":"text field","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"New Line","depth":3,"bounds":{"left":0.0,"top":0.0,"width":0.015277778,"height":0.024444444},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Preserve case","depth":3,"bounds":{"left":0.0,"top":0.0,"width":0.015277778,"height":0.024444444},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"0 results","depth":4,"role_description":"text"},{"role":"AXButton","text":"Previous Occurrence","depth":4,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Occurrence","depth":4,"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Filter Search Results","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open in Window, Multiple Cursors","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXLink","text":"Click to highlight","depth":4,"role_description":"link","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Close","depth":4,"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.0,"top":0.0,"width":0.088194445,"height":0.027777778},"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},"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},"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},"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"32","depth":4,"role_description":"text"},{"role":"AXStaticText","text":"2","depth":4,"role_description":"text"},{"role":"AXStaticText","text":"19","depth":4,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"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\\ServiceTraits;\n\nuse Carbon\\Carbon;\nuse HubSpot\\Client\\Crm\\Deals\\Model\\CollectionResponseAssociatedId;\nuse Jiminny\\Exceptions\\InvalidArgumentException;\nuse Jiminny\\Models\\Account;\nuse Exception;\nuse Jiminny\\Component\\DealInsights\\Forecast\\Forecast;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Models\\Opportunity;\nuse Illuminate\\Support\\Collection;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Services\\Crm\\Hubspot\\DealFieldsService;\nuse Jiminny\\Services\\Crm\\Hubspot\\OpportunitySyncStrategy\\HubspotSingleSyncStrategy;\nuse Jiminny\\Services\\Crm\\Hubspot\\WebhookSyncBatchProcessor;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\n\n/**\n * Optimized sync methods for better performance\n * These methods can be integrated into SyncCrmEntitiesTrait for significant performance gains\n */\ntrait OpportunitySyncTrait\n{\n private const int BATCH_SIZE = 100;\n private const int BATCH_PROCESS_SIZE = 800;\n\n protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n protected CrmEntityRepository $crmEntityRepository;\n protected DealFieldsService $dealFieldsService;\n\n private ?array $cachedClosedDealStages = null;\n private array $cachedBusinessProcesses = [];\n private array $cachedStages = [];\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n $parameters['config'] = $this->config;\n $syncCount = 0;\n $reportedTotal = 0;\n $lastSyncedId = [];\n\n try {\n foreach ($strategies as $strategyName => $syncStrategy) {\n $this->logger->info(\n '[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' .\n $strategyName\n );\n\n $total = 0;\n $lastId = null;\n $buffer = [];\n\n // HubspotWebhookBatchSyncStrategy returns empty generator, this is for other strategies\n foreach ($syncStrategy->fetchOpportunities($parameters, $total, $lastId) as $hsOpportunity) {\n $buffer[] = $hsOpportunity;\n\n // process every 800 rows (fits < 1 000 association limit)\n if (\\count($buffer) >= self::BATCH_PROCESS_SIZE) {\n $syncCount += $this->processOpportunityBatch($buffer);\n $buffer = [];\n }\n }\n\n // leftovers\n if ($buffer) {\n $syncCount += $this->processOpportunityBatch($buffer);\n }\n\n $reportedTotal += $total;\n $lastSyncedId = $lastId;\n }\n } catch (\\HubSpot\\Client\\Crm\\Deals\\ApiException | CrmException $e) {\n $this->handleSyncException($e, $parameters);\n }\n\n $this->logger->info(\n '[HubSpot] Synced opportunities',\n [\n 'team' => $this->team->getId(),\n 'sync_count' => $syncCount,\n 'total' => $reportedTotal,\n 'last_synced_id' => $lastSyncedId,\n ]\n );\n\n return $reportedTotal;\n }\n\n private function handleSyncException(\\Throwable $e, array $parameters): void\n {\n if (($parameters['since'] ?? null) instanceof Carbon) {\n $parameters['since'] = $parameters['since']->toDateTimeString();\n }\n $parameters['config'] = $this->config->getId();\n\n $this->logger->warning('[' . $this->getDisplayName() . '] Sync opportunities failed', [\n 'teamId' => $this->team->getUuid(),\n 'parameters' => $parameters,\n 'reason' => $e->getMessage(),\n ]);\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,\n );\n\n $parameters = [\n 'config' => $this->config,\n 'crm_id' => $crmId,\n ];\n\n try {\n if (! $strategy instanceof HubspotSingleSyncStrategy) {\n throw new InvalidArgumentException('Strategy must by HubspotSingleSyncStrategy');\n }\n\n $hsOpportunity = $strategy->fetchOpportunity($parameters);\n } catch (\\HubSpot\\Client\\Crm\\Deals\\ApiException $e) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [\n 'teamId' => $this->team->getUuid(),\n 'crmId' => $crmId,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n $hsOpportunity['associations'] = $this->convertDealAssociations($hsOpportunity['associations'] ?? []);\n\n return $this->importOrUpdateOpportunity($hsOpportunity);\n }\n\n /**\n * Process webhook-collected opportunity batches.\n *\n * Drains Redis sets containing company CRM IDs collected from webhook events\n * and dispatches ImportOpportunityBatch jobs for batch processing.\n *\n * @return int Number of opportunity IDs dispatched to jobs\n */\n public function batchSyncOpportunities(): int\n {\n $configId = $this->team->getCrmConfiguration()->getId();\n\n return $this->batchProcessor->processBatchesForObjectType(\n WebhookSyncBatchProcessor::OBJECT_TYPE_DEAL,\n $configId\n );\n }\n\n /**\n * Import a batch of opportunities by their CRM IDs.\n * Fetches opportunity data from HubSpot API and delegates to importOpportunityBatch().\n *\n * @param array<string> $crmIds HubSpot deal CRM IDs\n *\n * @return array{success: array, failed_ids: array, errors?: array<string, string>}\n */\n public function importOpportunityBatchByIds(array $crmIds): array\n {\n $fields = $this->dealFieldsService->getFieldsForConfiguration($this->config);\n\n $allDeals = [];\n foreach (array_chunk($crmIds, self::BATCH_SIZE) as $chunk) {\n $deals = $this->client->getOpportunitiesByIds($chunk, $fields);\n foreach ($deals as $deal) {\n $allDeals[] = $deal;\n }\n }\n\n // IDs not returned by HubSpot are likely deleted or inaccessible deals.\n // These are not failures — retrying won't bring them back.\n $fetchedIds = array_map('strval', array_column($allDeals, 'id'));\n $notFoundIds = array_values(array_diff(array_map('strval', $crmIds), $fetchedIds));\n\n if (! empty($notFoundIds)) {\n $this->logger->info('[' . $this->getDisplayName() . '] CRM IDs not found in HubSpot (likely deleted)', [\n 'teamId' => $this->team->getId(),\n 'notFoundCount' => \\count($notFoundIds),\n 'notFoundIds' => $notFoundIds,\n 'requestedCount' => \\count($crmIds),\n 'fetchedCount' => \\count($allDeals),\n ]);\n }\n\n if (empty($allDeals)) {\n return ['success' => [], 'failed_ids' => []];\n }\n\n return $this->importOpportunityBatch($allDeals);\n }\n\n private function getClosedDealStages(): array\n {\n if ($this->cachedClosedDealStages !== null) {\n return $this->cachedClosedDealStages;\n }\n\n $stages = $this->crmEntityRepository->getOpportunityClosedStages($this->config);\n $data = [\n 'lost' => [],\n 'won' => [],\n ];\n\n foreach ($stages as $stage) {\n if ($stage->probability == 0.00) {\n $data['lost'][] = $stage->crm_provider_id;\n }\n if ($stage->probability == 100.00) {\n $data['won'][] = $stage->crm_provider_id;\n }\n }\n\n $this->cachedClosedDealStages = $data;\n\n return $data;\n }\n\n /**\n * Import deals into the database with pre-fetched associations.\n *\n * API calls here (getAssociationsData, getExistingOpportunityCrmIds) are NOT\n * caught — if they throw, the exception propagates to ImportOpportunityBatch::handle()\n * where Laravel retries the whole job with backoff. After all retries exhausted,\n * failed() requeues all IDs to Redis.\n *\n * The per-deal loop catches exceptions individually. A deal can end up in three states:\n * - success: imported/updated successfully\n * - failed_ids: exception thrown (DB constraint violation, corrupt data, etc.)\n * These are permanent issues — retrying won't fix them.\n * - skipped (null): missing dependencies (no account, unknown pipeline/stage).\n * This is acceptable — the deal cannot be imported until those exist.\n */\n private function importOpportunityBatch(array $deals): array\n {\n $syncedOpportunities = [\n 'success' => [],\n 'failed_ids' => [],\n ];\n $dealIds = array_column($deals, 'id');\n\n // Shared association/existing-ID preparation is batch-level state. If it fails, rethrow so the\n // queue job retries the whole batch and eventually requeues all deal IDs back to Redis.\n try {\n $companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');\n $contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');\n\n $associationsData = $this->prepareAssociatedEntities($companyAssociations, $contactAssociations);\n\n $existingCrmIds = $this->crmEntityRepository->getExistingOpportunityCrmIds(\n $this->config,\n array_map('strval', $dealIds)\n );\n $existingCrmIdSet = array_flip($existingCrmIds);\n } catch (\\Throwable $e) {\n $this->logger->error('[' . $this->getDisplayName() . '] Failed to fetch associations or existing IDs', [\n 'teamId' => $this->team->getId(),\n 'dealCount' => count($dealIds),\n 'error' => $e->getMessage(),\n ]);\n\n throw $e;\n }\n\n foreach ($deals as $deal) {\n try {\n $deal['associations'] = $this->prepareAssociationsForOpportunity(\n $deal['id'],\n $companyAssociations,\n $contactAssociations,\n $associationsData\n );\n\n $syncedOpportunity = $this->importOrUpdateOpportunity(\n $deal,\n isset($existingCrmIdSet[(string) $deal['id']])\n );\n if ($syncedOpportunity) {\n $syncedOpportunities['success'][] = $syncedOpportunity;\n }\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to import opportunity', [\n 'teamId' => $this->team->getId(),\n 'crmId' => $deal['id'],\n 'error' => $e->getMessage(),\n ]);\n $syncedOpportunities['failed_ids'][] = $deal['id'];\n $syncedOpportunities['errors'][$deal['id']] = $e->getMessage();\n }\n }\n\n return $syncedOpportunities;\n }\n\n /**\n * Prepare associated entities for opportunities with optimized batch processing\n * Returns structured data with CRM ID to DB ID mappings for each opportunity\n */\n private function prepareAssociatedEntities(array $companyAssociations, array $contactAssociations): array\n {\n // Step 1: Collect all unique company and contact IDs from associations\n $allCompanyIds = $this->flattenAssociationIds($companyAssociations);\n $allContactIds = $this->flattenAssociationIds($contactAssociations);\n\n // Step 2: Batch sync missing entities and get CRM ID to DB ID mappings\n $companyIdMappings = [];\n $contactIdMappings = [];\n\n if (! empty($allCompanyIds)) {\n $companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);\n }\n\n if (! empty($allContactIds)) {\n $contactIdMappings = $this->prepareAssociatedContacts($allContactIds);\n }\n\n return [\n 'company_id_mappings' => $companyIdMappings,\n 'contact_id_mappings' => $contactIdMappings,\n ];\n }\n\n /**\n * Flatten association data to get unique IDs\n */\n private function flattenAssociationIds(array $associations): array\n {\n $ids = [];\n foreach ($associations as $dealAssociations) {\n if (is_array($dealAssociations)) {\n foreach ($dealAssociations as $id) {\n $ids[$id] = true;\n }\n }\n }\n\n return array_keys($ids);\n }\n\n /**\n * Batch sync missing accounts\n */\n private function prepareAssociatedAccounts(array $companyIds): array\n {\n // Find which accounts already exist\n $existingAccounts = $this->crmEntityRepository\n ->findAccountsByExternalIds($this->config, $companyIds);\n\n $existingCompanyIds = $existingAccounts->pluck('crm_provider_id')->toArray();\n\n $existingAccountsData = $existingAccounts->mapWithKeys(function ($account) {\n return [$account->getCrmProviderId() => $account->getId()];\n })->toArray();\n\n $missingCompanyIds = array_diff($companyIds, $existingCompanyIds);\n\n if (empty($missingCompanyIds)) {\n return $existingAccountsData;\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing accounts', [\n 'teamId' => $this->team->getUuid(),\n 'total_companies' => count($companyIds),\n 'existing_companies' => count($existingCompanyIds),\n 'missing_companies' => count($missingCompanyIds),\n ]);\n\n // we already have limit on opportunity ids count\n // Initialize variable before try block\n $syncedAccountsData = [];\n\n try {\n $syncedAccountsData = $this->batchSyncCrmObjects('companies', $missingCompanyIds);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing accounts', [\n 'size' => count($missingCompanyIds),\n 'error' => $e->getMessage(),\n ]);\n $syncedAccountsData = [];\n }\n\n return $existingAccountsData + $syncedAccountsData;\n }\n\n /**\n * Prepare associated contacts - find existing and sync missing ones\n * Returns mapping of CRM ID to DB ID\n */\n private function prepareAssociatedContacts(array $contactIds): array\n {\n // Find which contacts already exist\n $existingContacts = $this->crmEntityRepository\n ->findContactsByExternalIds($this->config, $contactIds);\n\n $existingContactIds = $existingContacts->pluck('crm_provider_id')->toArray();\n\n // Create mapping for existing contacts\n $existingContactsData = $existingContacts->mapWithKeys(function ($contact) {\n return [$contact->getCrmProviderId() => $contact->getId()];\n })->toArray();\n\n $missingContactIds = array_diff($contactIds, $existingContactIds);\n\n if (empty($missingContactIds)) {\n return $existingContactsData;\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing contacts', [\n 'teamId' => $this->team->getUuid(),\n 'total_contacts' => count($contactIds),\n 'existing_contacts' => count($existingContactIds),\n 'missing_contacts' => count($missingContactIds),\n ]);\n\n // Sync missing contacts using batch API\n try {\n $syncedContactsData = $this->batchSyncCrmObjects('contacts', $missingContactIds);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing contacts', [\n 'size' => count($missingContactIds),\n 'error' => $e->getMessage(),\n ]);\n $syncedContactsData = [];\n }\n\n return $existingContactsData + $syncedContactsData;\n }\n\n private function batchSyncCrmObjects(string $objectType, array $crmIds): array\n {\n $syncObjects = [];\n $crmObjectIds = array_values($crmIds);\n\n foreach (array_chunk($crmObjectIds, self::BATCH_SIZE) as $chunk) {\n try {\n $objects = $objectType === 'companies' ?\n $this->client->getCompaniesByIds($chunk, $this->getCompanyFields()) :\n $this->client->getContactsByIds($chunk, $this->getContactFields());\n\n foreach ($objects as $objectId => $objectData) {\n $this->importCrmObject($objectType, (string) $objectId, $objectData, $syncObjects);\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch synced ' . $objectType, [\n 'requested_count' => count($chunk),\n 'synced_count' => count($objects),\n ]);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Batch ' . $objectType . ' sync failed', [\n 'ids' => $chunk,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n return $syncObjects;\n }\n\n private function importCrmObject(string $objectType, string $objectId, mixed $objectData, array &$syncObjects): void\n {\n try {\n $object = $objectType === 'companies' ?\n $this->importAccount($objectData) :\n $this->importContact($objectData);\n\n if ($object) {\n $syncObjects[$object->getCrmProviderId()] = $object->getId();\n }\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to import batch ' . $objectType, [\n 'id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n /**\n * Prepare associations for a single opportunity\n *\n * The return value is an array with the following structure:\n * [\n * 'companies' => [\n * $companyCrmId => $companyId,\n * ...\n * ],\n * 'contacts' => [\n * $contactCrmId => $contactId,\n * ...\n * ],\n * 'account_id' => $accountId,\n * ]\n */\n private function prepareAssociationsForOpportunity(\n string $oppCrmId,\n array $companyAssociations,\n array $contactAssociations,\n array $associationsData\n ): array {\n $associations = [\n 'companies' => [],\n 'contacts' => [],\n 'account_id' => null, // Primary account for opportunity\n ];\n\n $oppCompanyIds = $companyAssociations[$oppCrmId] ?? [];\n foreach ($oppCompanyIds as $companyCrmId) {\n if (isset($associationsData['company_id_mappings'][$companyCrmId])) {\n $associations['companies'][$companyCrmId] = $associationsData['company_id_mappings'][$companyCrmId];\n\n // Set primary account (first company becomes primary account)\n if ($associations['account_id'] === null) {\n $associations['account_id'] = $associationsData['company_id_mappings'][$companyCrmId];\n }\n }\n }\n\n $oppContactIds = $contactAssociations[$oppCrmId] ?? [];\n foreach ($oppContactIds as $contactCrmId) {\n if (isset($associationsData['contact_id_mappings'][$contactCrmId])) {\n $associations['contacts'][$contactCrmId] = $associationsData['contact_id_mappings'][$contactCrmId];\n }\n }\n\n return $associations;\n }\n\n /**\n * Update only associations for an opportunity\n */\n private function updateOpportunityAssociations(Opportunity $opportunity, array $associations): void\n {\n // Update contact associations\n $this->importOpportunityContacts($opportunity, $associations['contacts']);\n\n // Update company (account) associations\n $this->updateOpportunityAccount($opportunity, $associations['account_id']);\n }\n\n /**\n * Remove all contact associations from an opportunity\n */\n private function removeAllOpportunityContacts(Opportunity $opportunity): void\n {\n $currentCount = (int) $opportunity->contacts()->count();\n\n if ($currentCount > 0) {\n $opportunity->contacts()->detach();\n\n $this->logger->info('[' . $this->getDisplayName() . '] Removed all contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'removed_count' => $currentCount,\n ]);\n }\n }\n\n private function updateOpportunityAccount(Opportunity $opportunity, ?int $accountId): void\n {\n if ($accountId === null) {\n // No account ID provided - keep current account\n return;\n }\n\n $currentAccountId = $opportunity->getAccountId();\n\n // Only update if account has changed\n if ($currentAccountId !== $accountId) {\n $opportunity->account_id = $accountId;\n $opportunity->save();\n\n $this->logger->info('[' . $this->getDisplayName() . '] Updated opportunity account association', [\n 'opportunity_id' => $opportunity->getId(),\n 'old_account_id' => $currentAccountId,\n 'new_account_id' => $accountId,\n ]);\n }\n }\n\n /**\n * Find existing opportunities by external IDs (OPTIMIZED VERSION)\n * Uses batch query for better performance\n */\n private function findExistingOpportunities(array $crmIds): Collection\n {\n return $this->crmEntityRepository\n ->findOpportunitiesByExternalIds($this->config, $crmIds);\n }\n\n private function processOpportunityBatch(array $opportunities): int\n {\n $syncedOpportunities = $this->importOpportunityBatch($opportunities);\n\n return count($syncedOpportunities['success'] ?? []);\n }\n\n /**\n * Convert single deal associations from HubSpot format to internal format\n * Handles both HubSpot SDK objects and array formats\n *\n * @param array $opportunityAssociations Raw associations from HubSpot API or pre-processed\n *\n * @return array Processed associations with DB IDs\n */\n private function convertDealAssociations(array $opportunityAssociations): array\n {\n $associations = $this->initializeAssociationsStructure();\n\n if (empty($opportunityAssociations)) {\n return $associations;\n }\n\n $associationIds = $this->extractAssociationIds($opportunityAssociations);\n\n $this->processCompanyAssociations($associationIds, $associations);\n $this->processContactAssociations($associationIds, $associations);\n\n return $associations;\n }\n\n private function initializeAssociationsStructure(): array\n {\n return [\n 'companies' => [],\n 'contacts' => [],\n 'account_id' => null, // Primary account for opportunity\n ];\n }\n\n private function extractAssociationIds(array $opportunityAssociations): array\n {\n $associationIds = [];\n\n foreach ($opportunityAssociations as $type => $associationData) {\n if (! empty($associationData)) {\n $associationIds[$type] = $this->convertSingleDealAssociations($associationData);\n }\n }\n\n return $associationIds;\n }\n\n private function processCompanyAssociations(array $associationIds, array &$associations): void\n {\n if (empty($associationIds['companies'])) {\n return;\n }\n\n $companyId = $associationIds['companies'][0];\n $account = $this->findOrSyncAccount($companyId);\n\n if ($account instanceof Account) {\n $associations['companies'][$companyId] = $account->getId();\n $associations['account_id'] = $account->getId();\n }\n }\n\n private function processContactAssociations(array $associationIds, array &$associations): void\n {\n if (empty($associationIds['contacts'])) {\n return;\n }\n\n foreach ($associationIds['contacts'] as $contactId) {\n $contact = $this->findOrSyncContact($contactId);\n\n if ($contact instanceof Contact) {\n $associations['contacts'][$contactId] = $contact->getId();\n }\n }\n }\n\n private function findOrSyncAccount(string $companyId): ?Account\n {\n $account = $this->crmEntityRepository->findAccountByExternalId($this->config, $companyId);\n\n if (! $account instanceof Account) {\n $account = $this->syncAccount($companyId);\n }\n\n return $account;\n }\n\n private function findOrSyncContact(string $contactId): ?Contact\n {\n $contact = $this->crmEntityRepository->findContactByExternalId($this->config, $contactId);\n\n if (! $contact instanceof Contact) {\n $contact = $this->syncContact($contactId);\n }\n\n return $contact;\n }\n\n private function convertSingleDealAssociations($opportunityAssociations = null): array\n {\n $associationData = [];\n\n if ($opportunityAssociations === null) {\n return $associationData;\n }\n\n // Handle array input (from extractAssociationIds)\n if (is_array($opportunityAssociations)) {\n return $opportunityAssociations;\n }\n\n // Handle CollectionResponseAssociatedId object\n if ($opportunityAssociations instanceof CollectionResponseAssociatedId) {\n foreach ($opportunityAssociations->getResults() as $association) {\n $associationData[] = $association->getId();\n }\n }\n\n return $associationData;\n }\n\n private function importOrUpdateOpportunity($crmData, ?bool $exists = null): ?Opportunity\n {\n if (empty($crmData['properties'])) {\n return null;\n }\n\n $crmId = (string) $crmData['id'];\n $properties = $crmData['properties'];\n $associations = $crmData['associations'] ?? [];\n\n $opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(\n $this->config,\n $crmId\n );\n\n if ($opportunityExists) {\n return $this->updateOpportunity($crmId, $properties, $associations);\n } else {\n return $this->createOpportunity($crmId, $properties, $associations);\n }\n }\n\n /**\n * Create new opportunity\n */\n private function createOpportunity(string $crmId, array $properties, array $associations): ?Opportunity\n {\n $accountId = $this->resolveAccountId($associations);\n if (! $accountId) {\n return null;\n }\n\n $businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);\n if (! $businessProcess) {\n return null;\n }\n\n $stage = $this->resolveStage($businessProcess, $properties['dealstage'] ?? null);\n if (! $stage) {\n return null;\n }\n\n $data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);\n\n $attributes = [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmId,\n ];\n\n $values = array_merge($attributes, $data);\n\n $opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);\n\n $this->importExternalFieldData($properties, $opportunity->getId());\n $this->importOpportunityContacts($opportunity, $associations['contacts']);\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n }\n\n /**\n * Update existing opportunity\n */\n private function updateOpportunity(string $crmId, array $properties, array $associations): Opportunity\n {\n $accountId = $this->resolveAccountId($associations);\n $businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);\n $stage = $businessProcess ? $this->resolveStage($businessProcess, $properties['dealstage'] ?? null) : null;\n\n $data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);\n\n $attributes = [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmId,\n ];\n\n $values = array_merge($attributes, $data);\n $opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);\n\n $this->importExternalFieldData($properties, $opportunity->getId());\n $this->updateOpportunityAssociations($opportunity, $associations);\n\n return $opportunity;\n }\n\n private function resolveAccountId(array $associations): ?int\n {\n if (! empty($associations['accountId'])) {\n return $associations['accountId'];\n }\n\n if (empty($associations)) {\n return null;\n }\n\n // we can't resolve multiple account ids (currently SDK returns one company)\n foreach ($associations['companies'] as $accountId) {\n return $accountId;\n }\n\n return null;\n }\n\n private function buildOpportunityData(\n array $properties,\n ?int $accountId,\n ?BusinessProcess $businessProcess,\n ?Stage $stage\n ): array {\n $ownerId = null;\n $profile = null;\n if (! empty($properties['hubspot_owner_id'])) {\n $ownerId = $properties['hubspot_owner_id'];\n $profile = $this->crmEntityRepository->findProfileByExternalId($this->config, (string) $ownerId);\n }\n\n $name = 'Unknown';\n if (isset($properties['dealname'])) {\n $name = mb_strimwidth($properties['dealname'], 0, 128);\n }\n\n $amount = $this->resolveAmount($properties);\n $currency = $properties['deal_currency_code'] ?? null;\n\n $closeDate = null;\n if (! empty($properties['closedate'])) {\n $closeDate = Carbon::parse($properties['closedate'])->format('Y-m-d');\n }\n\n $remotelyCreatedAt = null;\n if (! empty($properties['createdate']) && strtotime($properties['createdate'])) {\n $date = $this->parseCleanDatetime($properties['createdate']);\n $remotelyCreatedAt = $date?->format('Y-m-d H:i:s');\n }\n\n $closedStages = $this->getClosedDealStages();\n $isWon = in_array($properties['dealstage'], $closedStages['won']);\n $isLost = in_array($properties['dealstage'], $closedStages['lost']);\n\n $data = [\n 'team_id' => $this->team->getId(),\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => $name,\n 'value' => ! empty($amount) ? $amount : null,\n 'currency_code' => CurrencyFormatter::formatCode($currency),\n 'close_date' => $closeDate,\n 'is_closed' => $isWon || $isLost,\n 'is_won' => $isWon,\n 'remotely_created_at' => $remotelyCreatedAt,\n 'probability' => $this->resolveDealProbability($properties['hs_deal_stage_probability']),\n 'forecast_category' => $this->resolveForecastCategory($properties['hs_manual_forecast_category']),\n ];\n\n if ($accountId) {\n $data['account_id'] = $accountId;\n }\n\n if ($stage) {\n $data['stage_id'] = $stage->id;\n }\n\n if ($businessProcess) {\n $recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);\n if ($recordType) {\n $data['record_type_id'] = $recordType->id;\n }\n }\n\n return $data;\n }\n\n private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess\n {\n if ($pipelineId === null) {\n return null;\n }\n\n if (isset($this->cachedBusinessProcesses[$pipelineId])) {\n return $this->cachedBusinessProcesses[$pipelineId];\n }\n\n $businessProcess = $this->getBusinessProcess($pipelineId);\n\n if (! $businessProcess instanceof BusinessProcess) {\n $this->importStages();\n $businessProcess = $this->getBusinessProcess($pipelineId);\n }\n\n if (! $businessProcess instanceof BusinessProcess) {\n $this->logger->info(\n '[HubSpot] Deal is not attached to a pipeline',\n [\n 'pipeline' => $pipelineId]\n );\n }\n\n $this->cachedBusinessProcesses[$pipelineId] = $businessProcess;\n\n return $businessProcess;\n }\n\n private function getBusinessProcess(string $pipelineId): ?BusinessProcess\n {\n return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);\n }\n\n private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage\n {\n if (empty($stageId)) {\n return null;\n }\n\n $cacheKey = $businessProcess->getId() . ':' . $stageId;\n if (isset($this->cachedStages[$cacheKey])) {\n return $this->cachedStages[$cacheKey];\n }\n\n $stage = $this->crmEntityRepository->getPipelineStageByConditions(\n $businessProcess,\n [\n 'crm_provider_id' => $stageId,\n 'type' => Stage::TYPE_OPPORTUNITY,\n ]\n );\n\n if ($stage === null) {\n $this->importStages(null, $stageId);\n }\n\n if ($stage === null) {\n $this->logger->info('[HubSpot] Stage does not exist => ' . $stageId);\n }\n\n $this->cachedStages[$cacheKey] = $stage;\n\n return $stage;\n }\n\n private function resolveAmount(array $properties): ?string\n {\n $amount = null;\n if (! empty($properties['amount'])) {\n $amount = str_replace(',', '', $properties['amount']);\n }\n\n if ($this->config->hasDefaultCurrencyFieldSet()) {\n $valueFieldName = $this->config->getDefaultCurrencyField()->getCrmProviderId();\n $amount = $properties[$valueFieldName] ?? $amount;\n }\n\n return $amount;\n }\n\n private function parseCleanDatetime(string $datetime): ?Carbon\n {\n // Treat pre-1980 values as invalid\n $minValidDate = Carbon::parse('1980-01-01 00:00:00');\n\n try {\n $date = Carbon::parse($datetime);\n\n if ($minValidDate->gt($date)) {\n return null;\n }\n\n return $date;\n } catch (Exception) {\n return null; // On parse error, treat as null\n }\n }\n\n private function resolveDealProbability(?string $stageProbability): int\n {\n if ($stageProbability === null) {\n return 0;\n }\n\n $probability = (float) $stageProbability;\n\n return $probability > 1 ? 0 : (int) ($probability * 100);\n }\n\n private function resolveForecastCategory(?string $forecastCategory): string\n {\n if (! $forecastCategory) {\n return Forecast::FORECAST_CATEGORY_UNCATEGORIZED;\n }\n\n $forecastCategory = str_replace('_', ' ', $forecastCategory);\n\n return ucwords(strtolower($forecastCategory));\n }\n\n private function importExternalFieldData(array $properties, int $opportunityId): void\n {\n $crmFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData($properties, $crmFields, $opportunityId);\n }\n\n private function importOpportunityContacts(Opportunity $opportunity, array $associations): void\n {\n // Handle empty or missing contact associations\n if (empty($associations)) {\n // Remove all existing contact associations if none provided\n $this->removeAllOpportunityContacts($opportunity);\n\n return;\n }\n\n // Use differential sync approach for better performance and accuracy\n $this->syncOpportunityContactsDifferential($opportunity, $associations);\n }\n\n /**\n * Sync opportunity contacts using differential approach\n * This compares current vs new associations and only makes necessary changes\n */\n private function syncOpportunityContactsDifferential(Opportunity $opportunity, array $contactAssociations): void\n {\n $currentContactCrmIds = $this->getCurrentContactCrmIds($opportunity);\n $contactAssociationIds = array_keys($contactAssociations);\n\n $contactsToAdd = array_diff($contactAssociationIds, $currentContactCrmIds);\n $contactsToRemove = array_diff($currentContactCrmIds, $contactAssociationIds);\n\n if (empty($contactsToAdd) && empty($contactsToRemove)) {\n return;\n }\n\n $this->logContactAssociationChanges($opportunity, $currentContactCrmIds, $contactAssociations, $contactsToAdd, $contactsToRemove);\n\n $this->removeContactAssociations($opportunity, $contactsToRemove);\n $this->addContactAssociations($opportunity, $contactsToAdd, $contactAssociations);\n }\n\n private function getCurrentContactCrmIds(Opportunity $opportunity): array\n {\n return $opportunity->contacts()\n ->pluck('contacts.crm_provider_id')\n ->toArray();\n }\n\n private function logContactAssociationChanges(\n Opportunity $opportunity,\n array $currentContactCrmIds,\n array $contactAssociations,\n array $contactsToAdd,\n array $contactsToRemove\n ): void {\n $this->logger->info('[' . $this->getDisplayName() . '] Contact association changes', [\n 'opportunity_id' => $opportunity->getId(),\n 'current_contacts' => $currentContactCrmIds,\n 'new_contacts' => $contactAssociations,\n 'contacts_to_add' => $contactsToAdd,\n 'contacts_to_remove' => $contactsToRemove,\n ]);\n }\n\n private function removeContactAssociations(Opportunity $opportunity, array $contactsToRemove): void\n {\n if (empty($contactsToRemove)) {\n return;\n }\n\n $contactsToDetach = $opportunity->contacts()\n ->whereIn('contacts.crm_provider_id', $contactsToRemove)\n ->pluck('contacts.id')\n ->toArray();\n\n if (! empty($contactsToDetach)) {\n $opportunity->contacts()->detach($contactsToDetach);\n\n $this->logger->info('[' . $this->getDisplayName() . '] Removed contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'removed_contact_crm_ids' => $contactsToRemove,\n 'removed_contact_count' => count($contactsToDetach),\n ]);\n }\n }\n\n private function addContactAssociations(Opportunity $opportunity, array $contactsToAdd, array $contactAssociations): void\n {\n if (empty($contactsToAdd)) {\n return;\n }\n\n $contactsAdded = [];\n foreach ($contactsToAdd as $crmId) {\n $id = $contactAssociations[$crmId];\n\n if ($this->attachSingleContact($opportunity, (string) $crmId, $id)) {\n $contactsAdded[] = $crmId;\n }\n }\n\n $this->logAddedContacts($opportunity, $contactsAdded);\n }\n\n private function attachSingleContact(Opportunity $opportunity, string $crmId, int $id): bool\n {\n try {\n $contact = $this->crmEntityRepository->findContactByConfigurationAndId($this->config, $id);\n\n if (! $contact) {\n return false;\n }\n\n return $this->performContactAttachment($opportunity, $contact, $crmId);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to add contact association', [\n 'opportunity_id' => $opportunity->getId(),\n 'contact_crm_id' => $crmId,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n private function performContactAttachment(Opportunity $opportunity, Contact $contact, string $crmId): bool\n {\n try {\n $opportunity->contacts()->attach($contact->getId(), [\n 'crm_provider_id' => $crmId,\n ]);\n\n return true;\n } catch (\\Illuminate\\Database\\QueryException $e) {\n if (str_contains($e->getMessage(), 'Duplicate entry')) {\n $this->logger->info('[' . $this->getDisplayName() . '] Contact association already exists', [\n 'contact_id' => $contact->getId(),\n 'contact_crm_id' => $crmId,\n 'opportunity_id' => $opportunity->getId(),\n ]);\n\n return false;\n }\n\n throw $e;\n }\n }\n\n private function logAddedContacts(Opportunity $opportunity, array $contactsAdded): void\n {\n if (! empty($contactsAdded)) {\n $this->logger->info('[' . $this->getDisplayName() . '] Added contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'contacts_to_add_count' => count($contactsAdded),\n 'added_contact_crm_ids' => $contactsAdded,\n 'added_contacts_count' => count($contactsAdded),\n ]);\n }\n }\n}","depth":4,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\ServiceTraits;\n\nuse Carbon\\Carbon;\nuse HubSpot\\Client\\Crm\\Deals\\Model\\CollectionResponseAssociatedId;\nuse Jiminny\\Exceptions\\InvalidArgumentException;\nuse Jiminny\\Models\\Account;\nuse Exception;\nuse Jiminny\\Component\\DealInsights\\Forecast\\Forecast;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Models\\Opportunity;\nuse Illuminate\\Support\\Collection;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Services\\Crm\\Hubspot\\DealFieldsService;\nuse Jiminny\\Services\\Crm\\Hubspot\\OpportunitySyncStrategy\\HubspotSingleSyncStrategy;\nuse Jiminny\\Services\\Crm\\Hubspot\\WebhookSyncBatchProcessor;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\n\n/**\n * Optimized sync methods for better performance\n * These methods can be integrated into SyncCrmEntitiesTrait for significant performance gains\n */\ntrait OpportunitySyncTrait\n{\n private const int BATCH_SIZE = 100;\n private const int BATCH_PROCESS_SIZE = 800;\n\n protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n protected CrmEntityRepository $crmEntityRepository;\n protected DealFieldsService $dealFieldsService;\n\n private ?array $cachedClosedDealStages = null;\n private array $cachedBusinessProcesses = [];\n private array $cachedStages = [];\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n $parameters['config'] = $this->config;\n $syncCount = 0;\n $reportedTotal = 0;\n $lastSyncedId = [];\n\n try {\n foreach ($strategies as $strategyName => $syncStrategy) {\n $this->logger->info(\n '[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' .\n $strategyName\n );\n\n $total = 0;\n $lastId = null;\n $buffer = [];\n\n // HubspotWebhookBatchSyncStrategy returns empty generator, this is for other strategies\n foreach ($syncStrategy->fetchOpportunities($parameters, $total, $lastId) as $hsOpportunity) {\n $buffer[] = $hsOpportunity;\n\n // process every 800 rows (fits < 1 000 association limit)\n if (\\count($buffer) >= self::BATCH_PROCESS_SIZE) {\n $syncCount += $this->processOpportunityBatch($buffer);\n $buffer = [];\n }\n }\n\n // leftovers\n if ($buffer) {\n $syncCount += $this->processOpportunityBatch($buffer);\n }\n\n $reportedTotal += $total;\n $lastSyncedId = $lastId;\n }\n } catch (\\HubSpot\\Client\\Crm\\Deals\\ApiException | CrmException $e) {\n $this->handleSyncException($e, $parameters);\n }\n\n $this->logger->info(\n '[HubSpot] Synced opportunities',\n [\n 'team' => $this->team->getId(),\n 'sync_count' => $syncCount,\n 'total' => $reportedTotal,\n 'last_synced_id' => $lastSyncedId,\n ]\n );\n\n return $reportedTotal;\n }\n\n private function handleSyncException(\\Throwable $e, array $parameters): void\n {\n if (($parameters['since'] ?? null) instanceof Carbon) {\n $parameters['since'] = $parameters['since']->toDateTimeString();\n }\n $parameters['config'] = $this->config->getId();\n\n $this->logger->warning('[' . $this->getDisplayName() . '] Sync opportunities failed', [\n 'teamId' => $this->team->getUuid(),\n 'parameters' => $parameters,\n 'reason' => $e->getMessage(),\n ]);\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,\n );\n\n $parameters = [\n 'config' => $this->config,\n 'crm_id' => $crmId,\n ];\n\n try {\n if (! $strategy instanceof HubspotSingleSyncStrategy) {\n throw new InvalidArgumentException('Strategy must by HubspotSingleSyncStrategy');\n }\n\n $hsOpportunity = $strategy->fetchOpportunity($parameters);\n } catch (\\HubSpot\\Client\\Crm\\Deals\\ApiException $e) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [\n 'teamId' => $this->team->getUuid(),\n 'crmId' => $crmId,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n $hsOpportunity['associations'] = $this->convertDealAssociations($hsOpportunity['associations'] ?? []);\n\n return $this->importOrUpdateOpportunity($hsOpportunity);\n }\n\n /**\n * Process webhook-collected opportunity batches.\n *\n * Drains Redis sets containing company CRM IDs collected from webhook events\n * and dispatches ImportOpportunityBatch jobs for batch processing.\n *\n * @return int Number of opportunity IDs dispatched to jobs\n */\n public function batchSyncOpportunities(): int\n {\n $configId = $this->team->getCrmConfiguration()->getId();\n\n return $this->batchProcessor->processBatchesForObjectType(\n WebhookSyncBatchProcessor::OBJECT_TYPE_DEAL,\n $configId\n );\n }\n\n /**\n * Import a batch of opportunities by their CRM IDs.\n * Fetches opportunity data from HubSpot API and delegates to importOpportunityBatch().\n *\n * @param array<string> $crmIds HubSpot deal CRM IDs\n *\n * @return array{success: array, failed_ids: array, errors?: array<string, string>}\n */\n public function importOpportunityBatchByIds(array $crmIds): array\n {\n $fields = $this->dealFieldsService->getFieldsForConfiguration($this->config);\n\n $allDeals = [];\n foreach (array_chunk($crmIds, self::BATCH_SIZE) as $chunk) {\n $deals = $this->client->getOpportunitiesByIds($chunk, $fields);\n foreach ($deals as $deal) {\n $allDeals[] = $deal;\n }\n }\n\n // IDs not returned by HubSpot are likely deleted or inaccessible deals.\n // These are not failures — retrying won't bring them back.\n $fetchedIds = array_map('strval', array_column($allDeals, 'id'));\n $notFoundIds = array_values(array_diff(array_map('strval', $crmIds), $fetchedIds));\n\n if (! empty($notFoundIds)) {\n $this->logger->info('[' . $this->getDisplayName() . '] CRM IDs not found in HubSpot (likely deleted)', [\n 'teamId' => $this->team->getId(),\n 'notFoundCount' => \\count($notFoundIds),\n 'notFoundIds' => $notFoundIds,\n 'requestedCount' => \\count($crmIds),\n 'fetchedCount' => \\count($allDeals),\n ]);\n }\n\n if (empty($allDeals)) {\n return ['success' => [], 'failed_ids' => []];\n }\n\n return $this->importOpportunityBatch($allDeals);\n }\n\n private function getClosedDealStages(): array\n {\n if ($this->cachedClosedDealStages !== null) {\n return $this->cachedClosedDealStages;\n }\n\n $stages = $this->crmEntityRepository->getOpportunityClosedStages($this->config);\n $data = [\n 'lost' => [],\n 'won' => [],\n ];\n\n foreach ($stages as $stage) {\n if ($stage->probability == 0.00) {\n $data['lost'][] = $stage->crm_provider_id;\n }\n if ($stage->probability == 100.00) {\n $data['won'][] = $stage->crm_provider_id;\n }\n }\n\n $this->cachedClosedDealStages = $data;\n\n return $data;\n }\n\n /**\n * Import deals into the database with pre-fetched associations.\n *\n * API calls here (getAssociationsData, getExistingOpportunityCrmIds) are NOT\n * caught — if they throw, the exception propagates to ImportOpportunityBatch::handle()\n * where Laravel retries the whole job with backoff. After all retries exhausted,\n * failed() requeues all IDs to Redis.\n *\n * The per-deal loop catches exceptions individually. A deal can end up in three states:\n * - success: imported/updated successfully\n * - failed_ids: exception thrown (DB constraint violation, corrupt data, etc.)\n * These are permanent issues — retrying won't fix them.\n * - skipped (null): missing dependencies (no account, unknown pipeline/stage).\n * This is acceptable — the deal cannot be imported until those exist.\n */\n private function importOpportunityBatch(array $deals): array\n {\n $syncedOpportunities = [\n 'success' => [],\n 'failed_ids' => [],\n ];\n $dealIds = array_column($deals, 'id');\n\n // Shared association/existing-ID preparation is batch-level state. If it fails, rethrow so the\n // queue job retries the whole batch and eventually requeues all deal IDs back to Redis.\n try {\n $companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');\n $contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');\n\n $associationsData = $this->prepareAssociatedEntities($companyAssociations, $contactAssociations);\n\n $existingCrmIds = $this->crmEntityRepository->getExistingOpportunityCrmIds(\n $this->config,\n array_map('strval', $dealIds)\n );\n $existingCrmIdSet = array_flip($existingCrmIds);\n } catch (\\Throwable $e) {\n $this->logger->error('[' . $this->getDisplayName() . '] Failed to fetch associations or existing IDs', [\n 'teamId' => $this->team->getId(),\n 'dealCount' => count($dealIds),\n 'error' => $e->getMessage(),\n ]);\n\n throw $e;\n }\n\n foreach ($deals as $deal) {\n try {\n $deal['associations'] = $this->prepareAssociationsForOpportunity(\n $deal['id'],\n $companyAssociations,\n $contactAssociations,\n $associationsData\n );\n\n $syncedOpportunity = $this->importOrUpdateOpportunity(\n $deal,\n isset($existingCrmIdSet[(string) $deal['id']])\n );\n if ($syncedOpportunity) {\n $syncedOpportunities['success'][] = $syncedOpportunity;\n }\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to import opportunity', [\n 'teamId' => $this->team->getId(),\n 'crmId' => $deal['id'],\n 'error' => $e->getMessage(),\n ]);\n $syncedOpportunities['failed_ids'][] = $deal['id'];\n $syncedOpportunities['errors'][$deal['id']] = $e->getMessage();\n }\n }\n\n return $syncedOpportunities;\n }\n\n /**\n * Prepare associated entities for opportunities with optimized batch processing\n * Returns structured data with CRM ID to DB ID mappings for each opportunity\n */\n private function prepareAssociatedEntities(array $companyAssociations, array $contactAssociations): array\n {\n // Step 1: Collect all unique company and contact IDs from associations\n $allCompanyIds = $this->flattenAssociationIds($companyAssociations);\n $allContactIds = $this->flattenAssociationIds($contactAssociations);\n\n // Step 2: Batch sync missing entities and get CRM ID to DB ID mappings\n $companyIdMappings = [];\n $contactIdMappings = [];\n\n if (! empty($allCompanyIds)) {\n $companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);\n }\n\n if (! empty($allContactIds)) {\n $contactIdMappings = $this->prepareAssociatedContacts($allContactIds);\n }\n\n return [\n 'company_id_mappings' => $companyIdMappings,\n 'contact_id_mappings' => $contactIdMappings,\n ];\n }\n\n /**\n * Flatten association data to get unique IDs\n */\n private function flattenAssociationIds(array $associations): array\n {\n $ids = [];\n foreach ($associations as $dealAssociations) {\n if (is_array($dealAssociations)) {\n foreach ($dealAssociations as $id) {\n $ids[$id] = true;\n }\n }\n }\n\n return array_keys($ids);\n }\n\n /**\n * Batch sync missing accounts\n */\n private function prepareAssociatedAccounts(array $companyIds): array\n {\n // Find which accounts already exist\n $existingAccounts = $this->crmEntityRepository\n ->findAccountsByExternalIds($this->config, $companyIds);\n\n $existingCompanyIds = $existingAccounts->pluck('crm_provider_id')->toArray();\n\n $existingAccountsData = $existingAccounts->mapWithKeys(function ($account) {\n return [$account->getCrmProviderId() => $account->getId()];\n })->toArray();\n\n $missingCompanyIds = array_diff($companyIds, $existingCompanyIds);\n\n if (empty($missingCompanyIds)) {\n return $existingAccountsData;\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing accounts', [\n 'teamId' => $this->team->getUuid(),\n 'total_companies' => count($companyIds),\n 'existing_companies' => count($existingCompanyIds),\n 'missing_companies' => count($missingCompanyIds),\n ]);\n\n // we already have limit on opportunity ids count\n // Initialize variable before try block\n $syncedAccountsData = [];\n\n try {\n $syncedAccountsData = $this->batchSyncCrmObjects('companies', $missingCompanyIds);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing accounts', [\n 'size' => count($missingCompanyIds),\n 'error' => $e->getMessage(),\n ]);\n $syncedAccountsData = [];\n }\n\n return $existingAccountsData + $syncedAccountsData;\n }\n\n /**\n * Prepare associated contacts - find existing and sync missing ones\n * Returns mapping of CRM ID to DB ID\n */\n private function prepareAssociatedContacts(array $contactIds): array\n {\n // Find which contacts already exist\n $existingContacts = $this->crmEntityRepository\n ->findContactsByExternalIds($this->config, $contactIds);\n\n $existingContactIds = $existingContacts->pluck('crm_provider_id')->toArray();\n\n // Create mapping for existing contacts\n $existingContactsData = $existingContacts->mapWithKeys(function ($contact) {\n return [$contact->getCrmProviderId() => $contact->getId()];\n })->toArray();\n\n $missingContactIds = array_diff($contactIds, $existingContactIds);\n\n if (empty($missingContactIds)) {\n return $existingContactsData;\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing contacts', [\n 'teamId' => $this->team->getUuid(),\n 'total_contacts' => count($contactIds),\n 'existing_contacts' => count($existingContactIds),\n 'missing_contacts' => count($missingContactIds),\n ]);\n\n // Sync missing contacts using batch API\n try {\n $syncedContactsData = $this->batchSyncCrmObjects('contacts', $missingContactIds);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing contacts', [\n 'size' => count($missingContactIds),\n 'error' => $e->getMessage(),\n ]);\n $syncedContactsData = [];\n }\n\n return $existingContactsData + $syncedContactsData;\n }\n\n private function batchSyncCrmObjects(string $objectType, array $crmIds): array\n {\n $syncObjects = [];\n $crmObjectIds = array_values($crmIds);\n\n foreach (array_chunk($crmObjectIds, self::BATCH_SIZE) as $chunk) {\n try {\n $objects = $objectType === 'companies' ?\n $this->client->getCompaniesByIds($chunk, $this->getCompanyFields()) :\n $this->client->getContactsByIds($chunk, $this->getContactFields());\n\n foreach ($objects as $objectId => $objectData) {\n $this->importCrmObject($objectType, (string) $objectId, $objectData, $syncObjects);\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch synced ' . $objectType, [\n 'requested_count' => count($chunk),\n 'synced_count' => count($objects),\n ]);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Batch ' . $objectType . ' sync failed', [\n 'ids' => $chunk,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n return $syncObjects;\n }\n\n private function importCrmObject(string $objectType, string $objectId, mixed $objectData, array &$syncObjects): void\n {\n try {\n $object = $objectType === 'companies' ?\n $this->importAccount($objectData) :\n $this->importContact($objectData);\n\n if ($object) {\n $syncObjects[$object->getCrmProviderId()] = $object->getId();\n }\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to import batch ' . $objectType, [\n 'id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n /**\n * Prepare associations for a single opportunity\n *\n * The return value is an array with the following structure:\n * [\n * 'companies' => [\n * $companyCrmId => $companyId,\n * ...\n * ],\n * 'contacts' => [\n * $contactCrmId => $contactId,\n * ...\n * ],\n * 'account_id' => $accountId,\n * ]\n */\n private function prepareAssociationsForOpportunity(\n string $oppCrmId,\n array $companyAssociations,\n array $contactAssociations,\n array $associationsData\n ): array {\n $associations = [\n 'companies' => [],\n 'contacts' => [],\n 'account_id' => null, // Primary account for opportunity\n ];\n\n $oppCompanyIds = $companyAssociations[$oppCrmId] ?? [];\n foreach ($oppCompanyIds as $companyCrmId) {\n if (isset($associationsData['company_id_mappings'][$companyCrmId])) {\n $associations['companies'][$companyCrmId] = $associationsData['company_id_mappings'][$companyCrmId];\n\n // Set primary account (first company becomes primary account)\n if ($associations['account_id'] === null) {\n $associations['account_id'] = $associationsData['company_id_mappings'][$companyCrmId];\n }\n }\n }\n\n $oppContactIds = $contactAssociations[$oppCrmId] ?? [];\n foreach ($oppContactIds as $contactCrmId) {\n if (isset($associationsData['contact_id_mappings'][$contactCrmId])) {\n $associations['contacts'][$contactCrmId] = $associationsData['contact_id_mappings'][$contactCrmId];\n }\n }\n\n return $associations;\n }\n\n /**\n * Update only associations for an opportunity\n */\n private function updateOpportunityAssociations(Opportunity $opportunity, array $associations): void\n {\n // Update contact associations\n $this->importOpportunityContacts($opportunity, $associations['contacts']);\n\n // Update company (account) associations\n $this->updateOpportunityAccount($opportunity, $associations['account_id']);\n }\n\n /**\n * Remove all contact associations from an opportunity\n */\n private function removeAllOpportunityContacts(Opportunity $opportunity): void\n {\n $currentCount = (int) $opportunity->contacts()->count();\n\n if ($currentCount > 0) {\n $opportunity->contacts()->detach();\n\n $this->logger->info('[' . $this->getDisplayName() . '] Removed all contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'removed_count' => $currentCount,\n ]);\n }\n }\n\n private function updateOpportunityAccount(Opportunity $opportunity, ?int $accountId): void\n {\n if ($accountId === null) {\n // No account ID provided - keep current account\n return;\n }\n\n $currentAccountId = $opportunity->getAccountId();\n\n // Only update if account has changed\n if ($currentAccountId !== $accountId) {\n $opportunity->account_id = $accountId;\n $opportunity->save();\n\n $this->logger->info('[' . $this->getDisplayName() . '] Updated opportunity account association', [\n 'opportunity_id' => $opportunity->getId(),\n 'old_account_id' => $currentAccountId,\n 'new_account_id' => $accountId,\n ]);\n }\n }\n\n /**\n * Find existing opportunities by external IDs (OPTIMIZED VERSION)\n * Uses batch query for better performance\n */\n private function findExistingOpportunities(array $crmIds): Collection\n {\n return $this->crmEntityRepository\n ->findOpportunitiesByExternalIds($this->config, $crmIds);\n }\n\n private function processOpportunityBatch(array $opportunities): int\n {\n $syncedOpportunities = $this->importOpportunityBatch($opportunities);\n\n return count($syncedOpportunities['success'] ?? []);\n }\n\n /**\n * Convert single deal associations from HubSpot format to internal format\n * Handles both HubSpot SDK objects and array formats\n *\n * @param array $opportunityAssociations Raw associations from HubSpot API or pre-processed\n *\n * @return array Processed associations with DB IDs\n */\n private function convertDealAssociations(array $opportunityAssociations): array\n {\n $associations = $this->initializeAssociationsStructure();\n\n if (empty($opportunityAssociations)) {\n return $associations;\n }\n\n $associationIds = $this->extractAssociationIds($opportunityAssociations);\n\n $this->processCompanyAssociations($associationIds, $associations);\n $this->processContactAssociations($associationIds, $associations);\n\n return $associations;\n }\n\n private function initializeAssociationsStructure(): array\n {\n return [\n 'companies' => [],\n 'contacts' => [],\n 'account_id' => null, // Primary account for opportunity\n ];\n }\n\n private function extractAssociationIds(array $opportunityAssociations): array\n {\n $associationIds = [];\n\n foreach ($opportunityAssociations as $type => $associationData) {\n if (! empty($associationData)) {\n $associationIds[$type] = $this->convertSingleDealAssociations($associationData);\n }\n }\n\n return $associationIds;\n }\n\n private function processCompanyAssociations(array $associationIds, array &$associations): void\n {\n if (empty($associationIds['companies'])) {\n return;\n }\n\n $companyId = $associationIds['companies'][0];\n $account = $this->findOrSyncAccount($companyId);\n\n if ($account instanceof Account) {\n $associations['companies'][$companyId] = $account->getId();\n $associations['account_id'] = $account->getId();\n }\n }\n\n private function processContactAssociations(array $associationIds, array &$associations): void\n {\n if (empty($associationIds['contacts'])) {\n return;\n }\n\n foreach ($associationIds['contacts'] as $contactId) {\n $contact = $this->findOrSyncContact($contactId);\n\n if ($contact instanceof Contact) {\n $associations['contacts'][$contactId] = $contact->getId();\n }\n }\n }\n\n private function findOrSyncAccount(string $companyId): ?Account\n {\n $account = $this->crmEntityRepository->findAccountByExternalId($this->config, $companyId);\n\n if (! $account instanceof Account) {\n $account = $this->syncAccount($companyId);\n }\n\n return $account;\n }\n\n private function findOrSyncContact(string $contactId): ?Contact\n {\n $contact = $this->crmEntityRepository->findContactByExternalId($this->config, $contactId);\n\n if (! $contact instanceof Contact) {\n $contact = $this->syncContact($contactId);\n }\n\n return $contact;\n }\n\n private function convertSingleDealAssociations($opportunityAssociations = null): array\n {\n $associationData = [];\n\n if ($opportunityAssociations === null) {\n return $associationData;\n }\n\n // Handle array input (from extractAssociationIds)\n if (is_array($opportunityAssociations)) {\n return $opportunityAssociations;\n }\n\n // Handle CollectionResponseAssociatedId object\n if ($opportunityAssociations instanceof CollectionResponseAssociatedId) {\n foreach ($opportunityAssociations->getResults() as $association) {\n $associationData[] = $association->getId();\n }\n }\n\n return $associationData;\n }\n\n private function importOrUpdateOpportunity($crmData, ?bool $exists = null): ?Opportunity\n {\n if (empty($crmData['properties'])) {\n return null;\n }\n\n $crmId = (string) $crmData['id'];\n $properties = $crmData['properties'];\n $associations = $crmData['associations'] ?? [];\n\n $opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(\n $this->config,\n $crmId\n );\n\n if ($opportunityExists) {\n return $this->updateOpportunity($crmId, $properties, $associations);\n } else {\n return $this->createOpportunity($crmId, $properties, $associations);\n }\n }\n\n /**\n * Create new opportunity\n */\n private function createOpportunity(string $crmId, array $properties, array $associations): ?Opportunity\n {\n $accountId = $this->resolveAccountId($associations);\n if (! $accountId) {\n return null;\n }\n\n $businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);\n if (! $businessProcess) {\n return null;\n }\n\n $stage = $this->resolveStage($businessProcess, $properties['dealstage'] ?? null);\n if (! $stage) {\n return null;\n }\n\n $data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);\n\n $attributes = [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmId,\n ];\n\n $values = array_merge($attributes, $data);\n\n $opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);\n\n $this->importExternalFieldData($properties, $opportunity->getId());\n $this->importOpportunityContacts($opportunity, $associations['contacts']);\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n }\n\n /**\n * Update existing opportunity\n */\n private function updateOpportunity(string $crmId, array $properties, array $associations): Opportunity\n {\n $accountId = $this->resolveAccountId($associations);\n $businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);\n $stage = $businessProcess ? $this->resolveStage($businessProcess, $properties['dealstage'] ?? null) : null;\n\n $data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);\n\n $attributes = [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmId,\n ];\n\n $values = array_merge($attributes, $data);\n $opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);\n\n $this->importExternalFieldData($properties, $opportunity->getId());\n $this->updateOpportunityAssociations($opportunity, $associations);\n\n return $opportunity;\n }\n\n private function resolveAccountId(array $associations): ?int\n {\n if (! empty($associations['accountId'])) {\n return $associations['accountId'];\n }\n\n if (empty($associations)) {\n return null;\n }\n\n // we can't resolve multiple account ids (currently SDK returns one company)\n foreach ($associations['companies'] as $accountId) {\n return $accountId;\n }\n\n return null;\n }\n\n private function buildOpportunityData(\n array $properties,\n ?int $accountId,\n ?BusinessProcess $businessProcess,\n ?Stage $stage\n ): array {\n $ownerId = null;\n $profile = null;\n if (! empty($properties['hubspot_owner_id'])) {\n $ownerId = $properties['hubspot_owner_id'];\n $profile = $this->crmEntityRepository->findProfileByExternalId($this->config, (string) $ownerId);\n }\n\n $name = 'Unknown';\n if (isset($properties['dealname'])) {\n $name = mb_strimwidth($properties['dealname'], 0, 128);\n }\n\n $amount = $this->resolveAmount($properties);\n $currency = $properties['deal_currency_code'] ?? null;\n\n $closeDate = null;\n if (! empty($properties['closedate'])) {\n $closeDate = Carbon::parse($properties['closedate'])->format('Y-m-d');\n }\n\n $remotelyCreatedAt = null;\n if (! empty($properties['createdate']) && strtotime($properties['createdate'])) {\n $date = $this->parseCleanDatetime($properties['createdate']);\n $remotelyCreatedAt = $date?->format('Y-m-d H:i:s');\n }\n\n $closedStages = $this->getClosedDealStages();\n $isWon = in_array($properties['dealstage'], $closedStages['won']);\n $isLost = in_array($properties['dealstage'], $closedStages['lost']);\n\n $data = [\n 'team_id' => $this->team->getId(),\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => $name,\n 'value' => ! empty($amount) ? $amount : null,\n 'currency_code' => CurrencyFormatter::formatCode($currency),\n 'close_date' => $closeDate,\n 'is_closed' => $isWon || $isLost,\n 'is_won' => $isWon,\n 'remotely_created_at' => $remotelyCreatedAt,\n 'probability' => $this->resolveDealProbability($properties['hs_deal_stage_probability']),\n 'forecast_category' => $this->resolveForecastCategory($properties['hs_manual_forecast_category']),\n ];\n\n if ($accountId) {\n $data['account_id'] = $accountId;\n }\n\n if ($stage) {\n $data['stage_id'] = $stage->id;\n }\n\n if ($businessProcess) {\n $recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);\n if ($recordType) {\n $data['record_type_id'] = $recordType->id;\n }\n }\n\n return $data;\n }\n\n private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess\n {\n if ($pipelineId === null) {\n return null;\n }\n\n if (isset($this->cachedBusinessProcesses[$pipelineId])) {\n return $this->cachedBusinessProcesses[$pipelineId];\n }\n\n $businessProcess = $this->getBusinessProcess($pipelineId);\n\n if (! $businessProcess instanceof BusinessProcess) {\n $this->importStages();\n $businessProcess = $this->getBusinessProcess($pipelineId);\n }\n\n if (! $businessProcess instanceof BusinessProcess) {\n $this->logger->info(\n '[HubSpot] Deal is not attached to a pipeline',\n [\n 'pipeline' => $pipelineId]\n );\n }\n\n $this->cachedBusinessProcesses[$pipelineId] = $businessProcess;\n\n return $businessProcess;\n }\n\n private function getBusinessProcess(string $pipelineId): ?BusinessProcess\n {\n return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);\n }\n\n private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage\n {\n if (empty($stageId)) {\n return null;\n }\n\n $cacheKey = $businessProcess->getId() . ':' . $stageId;\n if (isset($this->cachedStages[$cacheKey])) {\n return $this->cachedStages[$cacheKey];\n }\n\n $stage = $this->crmEntityRepository->getPipelineStageByConditions(\n $businessProcess,\n [\n 'crm_provider_id' => $stageId,\n 'type' => Stage::TYPE_OPPORTUNITY,\n ]\n );\n\n if ($stage === null) {\n $this->importStages(null, $stageId);\n }\n\n if ($stage === null) {\n $this->logger->info('[HubSpot] Stage does not exist => ' . $stageId);\n }\n\n $this->cachedStages[$cacheKey] = $stage;\n\n return $stage;\n }\n\n private function resolveAmount(array $properties): ?string\n {\n $amount = null;\n if (! empty($properties['amount'])) {\n $amount = str_replace(',', '', $properties['amount']);\n }\n\n if ($this->config->hasDefaultCurrencyFieldSet()) {\n $valueFieldName = $this->config->getDefaultCurrencyField()->getCrmProviderId();\n $amount = $properties[$valueFieldName] ?? $amount;\n }\n\n return $amount;\n }\n\n private function parseCleanDatetime(string $datetime): ?Carbon\n {\n // Treat pre-1980 values as invalid\n $minValidDate = Carbon::parse('1980-01-01 00:00:00');\n\n try {\n $date = Carbon::parse($datetime);\n\n if ($minValidDate->gt($date)) {\n return null;\n }\n\n return $date;\n } catch (Exception) {\n return null; // On parse error, treat as null\n }\n }\n\n private function resolveDealProbability(?string $stageProbability): int\n {\n if ($stageProbability === null) {\n return 0;\n }\n\n $probability = (float) $stageProbability;\n\n return $probability > 1 ? 0 : (int) ($probability * 100);\n }\n\n private function resolveForecastCategory(?string $forecastCategory): string\n {\n if (! $forecastCategory) {\n return Forecast::FORECAST_CATEGORY_UNCATEGORIZED;\n }\n\n $forecastCategory = str_replace('_', ' ', $forecastCategory);\n\n return ucwords(strtolower($forecastCategory));\n }\n\n private function importExternalFieldData(array $properties, int $opportunityId): void\n {\n $crmFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData($properties, $crmFields, $opportunityId);\n }\n\n private function importOpportunityContacts(Opportunity $opportunity, array $associations): void\n {\n // Handle empty or missing contact associations\n if (empty($associations)) {\n // Remove all existing contact associations if none provided\n $this->removeAllOpportunityContacts($opportunity);\n\n return;\n }\n\n // Use differential sync approach for better performance and accuracy\n $this->syncOpportunityContactsDifferential($opportunity, $associations);\n }\n\n /**\n * Sync opportunity contacts using differential approach\n * This compares current vs new associations and only makes necessary changes\n */\n private function syncOpportunityContactsDifferential(Opportunity $opportunity, array $contactAssociations): void\n {\n $currentContactCrmIds = $this->getCurrentContactCrmIds($opportunity);\n $contactAssociationIds = array_keys($contactAssociations);\n\n $contactsToAdd = array_diff($contactAssociationIds, $currentContactCrmIds);\n $contactsToRemove = array_diff($currentContactCrmIds, $contactAssociationIds);\n\n if (empty($contactsToAdd) && empty($contactsToRemove)) {\n return;\n }\n\n $this->logContactAssociationChanges($opportunity, $currentContactCrmIds, $contactAssociations, $contactsToAdd, $contactsToRemove);\n\n $this->removeContactAssociations($opportunity, $contactsToRemove);\n $this->addContactAssociations($opportunity, $contactsToAdd, $contactAssociations);\n }\n\n private function getCurrentContactCrmIds(Opportunity $opportunity): array\n {\n return $opportunity->contacts()\n ->pluck('contacts.crm_provider_id')\n ->toArray();\n }\n\n private function logContactAssociationChanges(\n Opportunity $opportunity,\n array $currentContactCrmIds,\n array $contactAssociations,\n array $contactsToAdd,\n array $contactsToRemove\n ): void {\n $this->logger->info('[' . $this->getDisplayName() . '] Contact association changes', [\n 'opportunity_id' => $opportunity->getId(),\n 'current_contacts' => $currentContactCrmIds,\n 'new_contacts' => $contactAssociations,\n 'contacts_to_add' => $contactsToAdd,\n 'contacts_to_remove' => $contactsToRemove,\n ]);\n }\n\n private function removeContactAssociations(Opportunity $opportunity, array $contactsToRemove): void\n {\n if (empty($contactsToRemove)) {\n return;\n }\n\n $contactsToDetach = $opportunity->contacts()\n ->whereIn('contacts.crm_provider_id', $contactsToRemove)\n ->pluck('contacts.id')\n ->toArray();\n\n if (! empty($contactsToDetach)) {\n $opportunity->contacts()->detach($contactsToDetach);\n\n $this->logger->info('[' . $this->getDisplayName() . '] Removed contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'removed_contact_crm_ids' => $contactsToRemove,\n 'removed_contact_count' => count($contactsToDetach),\n ]);\n }\n }\n\n private function addContactAssociations(Opportunity $opportunity, array $contactsToAdd, array $contactAssociations): void\n {\n if (empty($contactsToAdd)) {\n return;\n }\n\n $contactsAdded = [];\n foreach ($contactsToAdd as $crmId) {\n $id = $contactAssociations[$crmId];\n\n if ($this->attachSingleContact($opportunity, (string) $crmId, $id)) {\n $contactsAdded[] = $crmId;\n }\n }\n\n $this->logAddedContacts($opportunity, $contactsAdded);\n }\n\n private function attachSingleContact(Opportunity $opportunity, string $crmId, int $id): bool\n {\n try {\n $contact = $this->crmEntityRepository->findContactByConfigurationAndId($this->config, $id);\n\n if (! $contact) {\n return false;\n }\n\n return $this->performContactAttachment($opportunity, $contact, $crmId);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to add contact association', [\n 'opportunity_id' => $opportunity->getId(),\n 'contact_crm_id' => $crmId,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n private function performContactAttachment(Opportunity $opportunity, Contact $contact, string $crmId): bool\n {\n try {\n $opportunity->contacts()->attach($contact->getId(), [\n 'crm_provider_id' => $crmId,\n ]);\n\n return true;\n } catch (\\Illuminate\\Database\\QueryException $e) {\n if (str_contains($e->getMessage(), 'Duplicate entry')) {\n $this->logger->info('[' . $this->getDisplayName() . '] Contact association already exists', [\n 'contact_id' => $contact->getId(),\n 'contact_crm_id' => $crmId,\n 'opportunity_id' => $opportunity->getId(),\n ]);\n\n return false;\n }\n\n throw $e;\n }\n }\n\n private function logAddedContacts(Opportunity $opportunity, array $contactsAdded): void\n {\n if (! empty($contactsAdded)) {\n $this->logger->info('[' . $this->getDisplayName() . '] Added contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'contacts_to_add_count' => count($contactsAdded),\n 'added_contact_crm_ids' => $contactsAdded,\n 'added_contacts_count' => count($contactsAdded),\n ]);\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,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-3768613051053981807
|
-8178087410993426138
|
visual_change
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
"podcast_audio_url"
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
0 results
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Code changed:
Hide
Sync Changes
Hide This Notification
32
2
19
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\ServiceTraits;
use Carbon\Carbon;
use HubSpot\Client\Crm\Deals\Model\CollectionResponseAssociatedId;
use Jiminny\Exceptions\InvalidArgumentException;
use Jiminny\Models\Account;
use Exception;
use Jiminny\Component\DealInsights\Forecast\Forecast;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Exceptions\CrmException;
use Jiminny\Models\Opportunity;
use Illuminate\Support\Collection;
use Jiminny\Models\Stage;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Services\Crm\Hubspot\DealFieldsService;
use Jiminny\Services\Crm\Hubspot\OpportunitySyncStrategy\HubspotSingleSyncStrategy;
use Jiminny\Services\Crm\Hubspot\WebhookSyncBatchProcessor;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
/**
* Optimized sync methods for better performance
* These methods can be integrated into SyncCrmEntitiesTrait for significant performance gains
*/
trait OpportunitySyncTrait
{
private const int BATCH_SIZE = 100;
private const int BATCH_PROCESS_SIZE = 800;
protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
protected CrmEntityRepository $crmEntityRepository;
protected DealFieldsService $dealFieldsService;
private ?array $cachedClosedDealStages = null;
private array $cachedBusinessProcesses = [];
private array $cachedStages = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' .
$strategyName
);
$total = 0;
$lastId = null;
$buffer = [];
// HubspotWebhookBatchSyncStrategy returns empty generator, this is for other strategies
foreach ($syncStrategy->fetchOpportunities($parameters, $total, $lastId) as $hsOpportunity) {
$buffer[] = $hsOpportunity;
// process every 800 rows (fits < 1 000 association limit)
if (\count($buffer) >= self::BATCH_PROCESS_SIZE) {
$syncCount += $this->processOpportunityBatch($buffer);
$buffer = [];
}
}
// leftovers
if ($buffer) {
$syncCount += $this->processOpportunityBatch($buffer);
}
$reportedTotal += $total;
$lastSyncedId = $lastId;
}
} catch (\HubSpot\Client\Crm\Deals\ApiException | CrmException $e) {
$this->handleSyncException($e, $parameters);
}
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
]
);
return $reportedTotal;
}
private function handleSyncException(\Throwable $e, array $parameters): void
{
if (($parameters['since'] ?? null) instanceof Carbon) {
$parameters['since'] = $parameters['since']->toDateTimeString();
}
$parameters['config'] = $this->config->getId();
$this->logger->warning('[' . $this->getDisplayName() . '] Sync opportunities failed', [
'teamId' => $this->team->getUuid(),
'parameters' => $parameters,
'reason' => $e->getMessage(),
]);
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,
);
$parameters = [
'config' => $this->config,
'crm_id' => $crmId,
];
try {
if (! $strategy instanceof HubspotSingleSyncStrategy) {
throw new InvalidArgumentException('Strategy must by HubspotSingleSyncStrategy');
}
$hsOpportunity = $strategy->fetchOpportunity($parameters);
} catch (\HubSpot\Client\Crm\Deals\ApiException $e) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [
'teamId' => $this->team->getUuid(),
'crmId' => $crmId,
'reason' => $e->getMessage(),
]);
return null;
}
$hsOpportunity['associations'] = $this->convertDealAssociations($hsOpportunity['associations'] ?? []);
return $this->importOrUpdateOpportunity($hsOpportunity);
}
/**
* Process webhook-collected opportunity batches.
*
* Drains Redis sets containing company CRM IDs collected from webhook events
* and dispatches ImportOpportunityBatch jobs for batch processing.
*
* @return int Number of opportunity IDs dispatched to jobs
*/
public function batchSyncOpportunities(): int
{
$configId = $this->team->getCrmConfiguration()->getId();
return $this->batchProcessor->processBatchesForObjectType(
WebhookSyncBatchProcessor::OBJECT_TYPE_DEAL,
$configId
);
}
/**
* Import a batch of opportunities by their CRM IDs.
* Fetches opportunity data from HubSpot API and delegates to importOpportunityBatch().
*
* @param array<string> $crmIds HubSpot deal CRM IDs
*
* @return array{success: array, failed_ids: array, errors?: array<string, string>}
*/
public function importOpportunityBatchByIds(array $crmIds): array
{
$fields = $this->dealFieldsService->getFieldsForConfiguration($this->config);
$allDeals = [];
foreach (array_chunk($crmIds, self::BATCH_SIZE) as $chunk) {
$deals = $this->client->getOpportunitiesByIds($chunk, $fields);
foreach ($deals as $deal) {
$allDeals[] = $deal;
}
}
// IDs not returned by HubSpot are likely deleted or inaccessible deals.
// These are not failures — retrying won't bring them back.
$fetchedIds = array_map('strval', array_column($allDeals, 'id'));
$notFoundIds = array_values(array_diff(array_map('strval', $crmIds), $fetchedIds));
if (! empty($notFoundIds)) {
$this->logger->info('[' . $this->getDisplayName() . '] CRM IDs not found in HubSpot (likely deleted)', [
'teamId' => $this->team->getId(),
'notFoundCount' => \count($notFoundIds),
'notFoundIds' => $notFoundIds,
'requestedCount' => \count($crmIds),
'fetchedCount' => \count($allDeals),
]);
}
if (empty($allDeals)) {
return ['success' => [], 'failed_ids' => []];
}
return $this->importOpportunityBatch($allDeals);
}
private function getClosedDealStages(): array
{
if ($this->cachedClosedDealStages !== null) {
return $this->cachedClosedDealStages;
}
$stages = $this->crmEntityRepository->getOpportunityClosedStages($this->config);
$data = [
'lost' => [],
'won' => [],
];
foreach ($stages as $stage) {
if ($stage->probability == 0.00) {
$data['lost'][] = $stage->crm_provider_id;
}
if ($stage->probability == 100.00) {
$data['won'][] = $stage->crm_provider_id;
}
}
$this->cachedClosedDealStages = $data;
return $data;
}
/**
* Import deals into the database with pre-fetched associations.
*
* API calls here (getAssociationsData, getExistingOpportunityCrmIds) are NOT
* caught — if they throw, the exception propagates to ImportOpportunityBatch::handle()
* where Laravel retries the whole job with backoff. After all retries exhausted,
* failed() requeues all IDs to Redis.
*
* The per-deal loop catches exceptions individually. A deal can end up in three states:
* - success: imported/updated successfully
* - failed_ids: exception thrown (DB constraint violation, corrupt data, etc.)
* These are permanent issues — retrying won't fix them.
* - skipped (null): missing dependencies (no account, unknown pipeline/stage).
* This is acceptable — the deal cannot be imported until those exist.
*/
private function importOpportunityBatch(array $deals): array
{
$syncedOpportunities = [
'success' => [],
'failed_ids' => [],
];
$dealIds = array_column($deals, 'id');
// Shared association/existing-ID preparation is batch-level state. If it fails, rethrow so the
// queue job retries the whole batch and eventually requeues all deal IDs back to Redis.
try {
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$associationsData = $this->prepareAssociatedEntities($companyAssociations, $contactAssociations);
$existingCrmIds = $this->crmEntityRepository->getExistingOpportunityCrmIds(
$this->config,
array_map('strval', $dealIds)
);
$existingCrmIdSet = array_flip($existingCrmIds);
} catch (\Throwable $e) {
$this->logger->error('[' . $this->getDisplayName() . '] Failed to fetch associations or existing IDs', [
'teamId' => $this->team->getId(),
'dealCount' => count($dealIds),
'error' => $e->getMessage(),
]);
throw $e;
}
foreach ($deals as $deal) {
try {
$deal['associations'] = $this->prepareAssociationsForOpportunity(
$deal['id'],
$companyAssociations,
$contactAssociations,
$associationsData
);
$syncedOpportunity = $this->importOrUpdateOpportunity(
$deal,
isset($existingCrmIdSet[(string) $deal['id']])
);
if ($syncedOpportunity) {
$syncedOpportunities['success'][] = $syncedOpportunity;
}
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to import opportunity', [
'teamId' => $this->team->getId(),
'crmId' => $deal['id'],
'error' => $e->getMessage(),
]);
$syncedOpportunities['failed_ids'][] = $deal['id'];
$syncedOpportunities['errors'][$deal['id']] = $e->getMessage();
}
}
return $syncedOpportunities;
}
/**
* Prepare associated entities for opportunities with optimized batch processing
* Returns structured data with CRM ID to DB ID mappings for each opportunity
*/
private function prepareAssociatedEntities(array $companyAssociations, array $contactAssociations): array
{
// Step 1: Collect all unique company and contact IDs from associations
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
// Step 2: Batch sync missing entities and get CRM ID to DB ID mappings
$companyIdMappings = [];
$contactIdMappings = [];
if (! empty($allCompanyIds)) {
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
}
if (! empty($allContactIds)) {
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
}
return [
'company_id_mappings' => $companyIdMappings,
'contact_id_mappings' => $contactIdMappings,
];
}
/**
* Flatten association data to get unique IDs
*/
private function flattenAssociationIds(array $associations): array
{
$ids = [];
foreach ($associations as $dealAssociations) {
if (is_array($dealAssociations)) {
foreach ($dealAssociations as $id) {
$ids[$id] = true;
}
}
}
return array_keys($ids);
}
/**
* Batch sync missing accounts
*/
private function prepareAssociatedAccounts(array $companyIds): array
{
// Find which accounts already exist
$existingAccounts = $this->crmEntityRepository
->findAccountsByExternalIds($this->config, $companyIds);
$existingCompanyIds = $existingAccounts->pluck('crm_provider_id')->toArray();
$existingAccountsData = $existingAccounts->mapWithKeys(function ($account) {
return [$account->getCrmProviderId() => $account->getId()];
})->toArray();
$missingCompanyIds = array_diff($companyIds, $existingCompanyIds);
if (empty($missingCompanyIds)) {
return $existingAccountsData;
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing accounts', [
'teamId' => $this->team->getUuid(),
'total_companies' => count($companyIds),
'existing_companies' => count($existingCompanyIds),
'missing_companies' => count($missingCompanyIds),
]);
// we already have limit on opportunity ids count
// Initialize variable before try block
$syncedAccountsData = [];
try {
$syncedAccountsData = $this->batchSyncCrmObjects('companies', $missingCompanyIds);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing accounts', [
'size' => count($missingCompanyIds),
'error' => $e->getMessage(),
]);
$syncedAccountsData = [];
}
return $existingAccountsData + $syncedAccountsData;
}
/**
* Prepare associated contacts - find existing and sync missing ones
* Returns mapping of CRM ID to DB ID
*/
private function prepareAssociatedContacts(array $contactIds): array
{
// Find which contacts already exist
$existingContacts = $this->crmEntityRepository
->findContactsByExternalIds($this->config, $contactIds);
$existingContactIds = $existingContacts->pluck('crm_provider_id')->toArray();
// Create mapping for existing contacts
$existingContactsData = $existingContacts->mapWithKeys(function ($contact) {
return [$contact->getCrmProviderId() => $contact->getId()];
})->toArray();
$missingContactIds = array_diff($contactIds, $existingContactIds);
if (empty($missingContactIds)) {
return $existingContactsData;
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing contacts', [
'teamId' => $this->team->getUuid(),
'total_contacts' => count($contactIds),
'existing_contacts' => count($existingContactIds),
'missing_contacts' => count($missingContactIds),
]);
// Sync missing contacts using batch API
try {
$syncedContactsData = $this->batchSyncCrmObjects('contacts', $missingContactIds);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing contacts', [
'size' => count($missingContactIds),
'error' => $e->getMessage(),
]);
$syncedContactsData = [];
}
return $existingContactsData + $syncedContactsData;
}
private function batchSyncCrmObjects(string $objectType, array $crmIds): array
{
$syncObjects = [];
$crmObjectIds = array_values($crmIds);
foreach (array_chunk($crmObjectIds, self::BATCH_SIZE) as $chunk) {
try {
$objects = $objectType === 'companies' ?
$this->client->getCompaniesByIds($chunk, $this->getCompanyFields()) :
$this->client->getContactsByIds($chunk, $this->getContactFields());
foreach ($objects as $objectId => $objectData) {
$this->importCrmObject($objectType, (string) $objectId, $objectData, $syncObjects);
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch synced ' . $objectType, [
'requested_count' => count($chunk),
'synced_count' => count($objects),
]);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Batch ' . $objectType . ' sync failed', [
'ids' => $chunk,
'error' => $e->getMessage(),
]);
}
}
return $syncObjects;
}
private function importCrmObject(string $objectType, string $objectId, mixed $objectData, array &$syncObjects): void
{
try {
$object = $objectType === 'companies' ?
$this->importAccount($objectData) :
$this->importContact($objectData);
if ($object) {
$syncObjects[$object->getCrmProviderId()] = $object->getId();
}
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to import batch ' . $objectType, [
'id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
/**
* Prepare associations for a single opportunity
*
* The return value is an array with the following structure:
* [
* 'companies' => [
* $companyCrmId => $companyId,
* ...
* ],
* 'contacts' => [
* $contactCrmId => $contactId,
* ...
* ],
* 'account_id' => $accountId,
* ]
*/
private function prepareAssociationsForOpportunity(
string $oppCrmId,
array $companyAssociations,
array $contactAssociations,
array $associationsData
): array {
$associations = [
'companies' => [],
'contacts' => [],
'account_id' => null, // Primary account for opportunity
];
$oppCompanyIds = $companyAssociations[$oppCrmId] ?? [];
foreach ($oppCompanyIds as $companyCrmId) {
if (isset($associationsData['company_id_mappings'][$companyCrmId])) {
$associations['companies'][$companyCrmId] = $associationsData['company_id_mappings'][$companyCrmId];
// Set primary account (first company becomes primary account)
if ($associations['account_id'] === null) {
$associations['account_id'] = $associationsData['company_id_mappings'][$companyCrmId];
}
}
}
$oppContactIds = $contactAssociations[$oppCrmId] ?? [];
foreach ($oppContactIds as $contactCrmId) {
if (isset($associationsData['contact_id_mappings'][$contactCrmId])) {
$associations['contacts'][$contactCrmId] = $associationsData['contact_id_mappings'][$contactCrmId];
}
}
return $associations;
}
/**
* Update only associations for an opportunity
*/
private function updateOpportunityAssociations(Opportunity $opportunity, array $associations): void
{
// Update contact associations
$this->importOpportunityContacts($opportunity, $associations['contacts']);
// Update company (account) associations
$this->updateOpportunityAccount($opportunity, $associations['account_id']);
}
/**
* Remove all contact associations from an opportunity
*/
private function removeAllOpportunityContacts(Opportunity $opportunity): void
{
$currentCount = (int) $opportunity->contacts()->count();
if ($currentCount > 0) {
$opportunity->contacts()->detach();
$this->logger->info('[' . $this->getDisplayName() . '] Removed all contact associations', [
'opportunity_id' => $opportunity->getId(),
'removed_count' => $currentCount,
]);
}
}
private function updateOpportunityAccount(Opportunity $opportunity, ?int $accountId): void
{
if ($accountId === null) {
// No account ID provided - keep current account
return;
}
$currentAccountId = $opportunity->getAccountId();
// Only update if account has changed
if ($currentAccountId !== $accountId) {
$opportunity->account_id = $accountId;
$opportunity->save();
$this->logger->info('[' . $this->getDisplayName() . '] Updated opportunity account association', [
'opportunity_id' => $opportunity->getId(),
'old_account_id' => $currentAccountId,
'new_account_id' => $accountId,
]);
}
}
/**
* Find existing opportunities by external IDs (OPTIMIZED VERSION)
* Uses batch query for better performance
*/
private function findExistingOpportunities(array $crmIds): Collection
{
return $this->crmEntityRepository
->findOpportunitiesByExternalIds($this->config, $crmIds);
}
private function processOpportunityBatch(array $opportunities): int
{
$syncedOpportunities = $this->importOpportunityBatch($opportunities);
return count($syncedOpportunities['success'] ?? []);
}
/**
* Convert single deal associations from HubSpot format to internal format
* Handles both HubSpot SDK objects and array formats
*
* @param array $opportunityAssociations Raw associations from HubSpot API or pre-processed
*
* @return array Processed associations with DB IDs
*/
private function convertDealAssociations(array $opportunityAssociations): array
{
$associations = $this->initializeAssociationsStructure();
if (empty($opportunityAssociations)) {
return $associations;
}
$associationIds = $this->extractAssociationIds($opportunityAssociations);
$this->processCompanyAssociations($associationIds, $associations);
$this->processContactAssociations($associationIds, $associations);
return $associations;
}
private function initializeAssociationsStructure(): array
{
return [
'companies' => [],
'contacts' => [],
'account_id' => null, // Primary account for opportunity
];
}
private function extractAssociationIds(array $opportunityAssociations): array
{
$associationIds = [];
foreach ($opportunityAssociations as $type => $associationData) {
if (! empty($associationData)) {
$associationIds[$type] = $this->convertSingleDealAssociations($associationData);
}
}
return $associationIds;
}
private function processCompanyAssociations(array $associationIds, array &$associations): void
{
if (empty($associationIds['companies'])) {
return;
}
$companyId = $associationIds['companies'][0];
$account = $this->findOrSyncAccount($companyId);
if ($account instanceof Account) {
$associations['companies'][$companyId] = $account->getId();
$associations['account_id'] = $account->getId();
}
}
private function processContactAssociations(array $associationIds, array &$associations): void
{
if (empty($associationIds['contacts'])) {
return;
}
foreach ($associationIds['contacts'] as $contactId) {
$contact = $this->findOrSyncContact($contactId);
if ($contact instanceof Contact) {
$associations['contacts'][$contactId] = $contact->getId();
}
}
}
private function findOrSyncAccount(string $companyId): ?Account
{
$account = $this->crmEntityRepository->findAccountByExternalId($this->config, $companyId);
if (! $account instanceof Account) {
$account = $this->syncAccount($companyId);
}
return $account;
}
private function findOrSyncContact(string $contactId): ?Contact
{
$contact = $this->crmEntityRepository->findContactByExternalId($this->config, $contactId);
if (! $contact instanceof Contact) {
$contact = $this->syncContact($contactId);
}
return $contact;
}
private function convertSingleDealAssociations($opportunityAssociations = null): array
{
$associationData = [];
if ($opportunityAssociations === null) {
return $associationData;
}
// Handle array input (from extractAssociationIds)
if (is_array($opportunityAssociations)) {
return $opportunityAssociations;
}
// Handle CollectionResponseAssociatedId object
if ($opportunityAssociations instanceof CollectionResponseAssociatedId) {
foreach ($opportunityAssociations->getResults() as $association) {
$associationData[] = $association->getId();
}
}
return $associationData;
}
private function importOrUpdateOpportunity($crmData, ?bool $exists = null): ?Opportunity
{
if (empty($crmData['properties'])) {
return null;
}
$crmId = (string) $crmData['id'];
$properties = $crmData['properties'];
$associations = $crmData['associations'] ?? [];
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity($crmId, $properties, $associations);
} else {
return $this->createOpportunity($crmId, $properties, $associations);
}
}
/**
* Create new opportunity
*/
private function createOpportunity(string $crmId, array $properties, array $associations): ?Opportunity
{
$accountId = $this->resolveAccountId($associations);
if (! $accountId) {
return null;
}
$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);
if (! $businessProcess) {
return null;
}
$stage = $this->resolveStage($businessProcess, $properties['dealstage'] ?? null);
if (! $stage) {
return null;
}
$data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);
$attributes = [
'crm_configuration_id' => $this->config->getId(),
'crm_provider_id' => $crmId,
];
$values = array_merge($attributes, $data);
$opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);
$this->importExternalFieldData($properties, $opportunity->getId());
$this->importOpportunityContacts($opportunity, $associations['contacts']);
if ($opportunity->wasRecentlyCreated) {
MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());
}
return $opportunity;
}
/**
* Update existing opportunity
*/
private function updateOpportunity(string $crmId, array $properties, array $associations): Opportunity
{
$accountId = $this->resolveAccountId($associations);
$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);
$stage = $businessProcess ? $this->resolveStage($businessProcess, $properties['dealstage'] ?? null) : null;
$data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);
$attributes = [
'crm_configuration_id' => $this->config->getId(),
'crm_provider_id' => $crmId,
];
$values = array_merge($attributes, $data);
$opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);
$this->importExternalFieldData($properties, $opportunity->getId());
$this->updateOpportunityAssociations($opportunity, $associations);
return $opportunity;
}
private function resolveAccountId(array $associations): ?int
{
if (! empty($associations['accountId'])) {
return $associations['accountId'];
}
if (empty($associations)) {
return null;
}
// we can't resolve multiple account ids (currently SDK returns one company)
foreach ($associations['companies'] as $accountId) {
return $accountId;
}
return null;
}
private function buildOpportunityData(
array $properties,
?int $accountId,
?BusinessProcess $businessProcess,
?Stage $stage
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, (string) $ownerId);
}
$name = 'Unknown';
if (isset($properties['dealname'])) {
$name = mb_strimwidth($properties['dealname'], 0, 128);
}
$amount = $this->resolveAmount($properties);
$currency = $properties['deal_currency_code'] ?? null;
$closeDate = null;
if (! empty($properties['closedate'])) {
$closeDate = Carbon::parse($properties['closedate'])->format('Y-m-d');
}
$remotelyCreatedAt = null;
if (! empty($properties['createdate']) && strtotime($properties['createdate'])) {
$date = $this->parseCleanDatetime($properties['createdate']);
$remotelyCreatedAt = $date?->format('Y-m-d H:i:s');
}
$closedStages = $this->getClosedDealStages();
$isWon = in_array($properties['dealstage'], $closedStages['won']);
$isLost = in_array($properties['dealstage'], $closedStages['lost']);
$data = [
'team_id' => $this->team->getId(),
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => $name,
'value' => ! empty($amount) ? $amount : null,
'currency_code' => CurrencyFormatter::formatCode($currency),
'close_date' => $closeDate,
'is_closed' => $isWon || $isLost,
'is_won' => $isWon,
'remotely_created_at' => $remotelyCreatedAt,
'probability' => $this->resolveDealProbability($properties['hs_deal_stage_probability']),
'forecast_category' => $this->resolveForecastCategory($properties['hs_manual_forecast_category']),
];
if ($accountId) {
$data['account_id'] = $accountId;
}
if ($stage) {
$data['stage_id'] = $stage->id;
}
if ($businessProcess) {
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
if (isset($this->cachedBusinessProcesses[$pipelineId])) {
return $this->cachedBusinessProcesses[$pipelineId];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$pipelineId] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $businessProcess->getId() . ':' . $stageId;
if (isset($this->cachedStages[$cacheKey])) {
return $this->cachedStages[$cacheKey];
}
$stage = $this->crmEntityRepository->getPipelineStageByConditions(
$businessProcess,
[
'crm_provider_id' => $stageId,
'type' => Stage::TYPE_OPPORTUNITY,
]
);
if ($stage === null) {
$this->importStages(null, $stageId);
}
if ($stage === null) {
$this->logger->info('[HubSpot] Stage does not exist => ' . $stageId);
}
$this->cachedStages[$cacheKey] = $stage;
return $stage;
}
private function resolveAmount(array $properties): ?string
{
$amount = null;
if (! empty($properties['amount'])) {
$amount = str_replace(',', '', $properties['amount']);
}
if ($this->config->hasDefaultCurrencyFieldSet()) {
$valueFieldName = $this->config->getDefaultCurrencyField()->getCrmProviderId();
$amount = $properties[$valueFieldName] ?? $amount;
}
return $amount;
}
private function parseCleanDatetime(string $datetime): ?Carbon
{
// Treat pre-1980 values as invalid
$minValidDate = Carbon::parse('1980-01-01 00:00:00');
try {
$date = Carbon::parse($datetime);
if ($minValidDate->gt($date)) {
return null;
}
return $date;
} catch (Exception) {
return null; // On parse error, treat as null
}
}
private function resolveDealProbability(?string $stageProbability): int
{
if ($stageProbability === null) {
return 0;
}
$probability = (float) $stageProbability;
return $probability > 1 ? 0 : (int) ($probability * 100);
}
private function resolveForecastCategory(?string $forecastCategory): string
{
if (! $forecastCategory) {
return Forecast::FORECAST_CATEGORY_UNCATEGORIZED;
}
$forecastCategory = str_replace('_', ' ', $forecastCategory);
return ucwords(strtolower($forecastCategory));
}
private function importExternalFieldData(array $properties, int $opportunityId): void
{
$crmFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData($properties, $crmFields, $opportunityId);
}
private function importOpportunityContacts(Opportunity $opportunity, array $associations): void
{
// Handle empty or missing contact associations
if (empty($associations)) {
// Remove all existing contact associations if none provided
$this->removeAllOpportunityContacts($opportunity);
return;
}
// Use differential sync approach for better performance and accuracy
$this->syncOpportunityContactsDifferential($opportunity, $associations);
}
/**
* Sync opportunity contacts using differential approach
* This compares current vs new associations and only makes necessary changes
*/
private function syncOpportunityContactsDifferential(Opportunity $opportunity, array $contactAssociations): void
{
$currentContactCrmIds = $this->getCurrentContactCrmIds($opportunity);
$contactAssociationIds = array_keys($contactAssociations);
$contactsToAdd = array_diff($contactAssociationIds, $currentContactCrmIds);
$contactsToRemove = array_diff($currentContactCrmIds, $contactAssociationIds);
if (empty($contactsToAdd) && empty($contactsToRemove)) {
return;
}
$this->logContactAssociationChanges($opportunity, $currentContactCrmIds, $contactAssociations, $contactsToAdd, $contactsToRemove);
$this->removeContactAssociations($opportunity, $contactsToRemove);
$this->addContactAssociations($opportunity, $contactsToAdd, $contactAssociations);
}
private function getCurrentContactCrmIds(Opportunity $opportunity): array
{
return $opportunity->contacts()
->pluck('contacts.crm_provider_id')
->toArray();
}
private function logContactAssociationChanges(
Opportunity $opportunity,
array $currentContactCrmIds,
array $contactAssociations,
array $contactsToAdd,
array $contactsToRemove
): void {
$this->logger->info('[' . $this->getDisplayName() . '] Contact association changes', [
'opportunity_id' => $opportunity->getId(),
'current_contacts' => $currentContactCrmIds,
'new_contacts' => $contactAssociations,
'contacts_to_add' => $contactsToAdd,
'contacts_to_remove' => $contactsToRemove,
]);
}
private function removeContactAssociations(Opportunity $opportunity, array $contactsToRemove): void
{
if (empty($contactsToRemove)) {
return;
}
$contactsToDetach = $opportunity->contacts()
->whereIn('contacts.crm_provider_id', $contactsToRemove)
->pluck('contacts.id')
->toArray();
if (! empty($contactsToDetach)) {
$opportunity->contacts()->detach($contactsToDetach);
$this->logger->info('[' . $this->getDisplayName() . '] Removed contact associations', [
'opportunity_id' => $opportunity->getId(),
'removed_contact_crm_ids' => $contactsToRemove,
'removed_contact_count' => count($contactsToDetach),
]);
}
}
private function addContactAssociations(Opportunity $opportunity, array $contactsToAdd, array $contactAssociations): void
{
if (empty($contactsToAdd)) {
return;
}
$contactsAdded = [];
foreach ($contactsToAdd as $crmId) {
$id = $contactAssociations[$crmId];
if ($this->attachSingleContact($opportunity, (string) $crmId, $id)) {
$contactsAdded[] = $crmId;
}
}
$this->logAddedContacts($opportunity, $contactsAdded);
}
private function attachSingleContact(Opportunity $opportunity, string $crmId, int $id): bool
{
try {
$contact = $this->crmEntityRepository->findContactByConfigurationAndId($this->config, $id);
if (! $contact) {
return false;
}
return $this->performContactAttachment($opportunity, $contact, $crmId);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to add contact association', [
'opportunity_id' => $opportunity->getId(),
'contact_crm_id' => $crmId,
'error' => $e->getMessage(),
]);
return false;
}
}
private function performContactAttachment(Opportunity $opportunity, Contact $contact, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contact->getId(), [
'crm_provider_id' => $crmId,
]);
return true;
} catch (\Illuminate\Database\QueryException $e) {
if (str_contains($e->getMessage(), 'Duplicate entry')) {
$this->logger->info('[' . $this->getDisplayName() . '] Contact association already exists', [
'contact_id' => $contact->getId(),
'contact_crm_id' => $crmId,
'opportunity_id' => $opportunity->getId(),
]);
return false;
}
throw $e;
}
}
private function logAddedContacts(Opportunity $opportunity, array $contactsAdded): void
{
if (! empty($contactsAdded)) {
$this->logger->info('[' . $this->getDisplayName() . '] Added contact associations', [
'opportunity_id' => $opportunity->getId(),
'contacts_to_add_count' => count($contactsAdded),
'added_contact_crm_ids' => $contactsAdded,
'added_contacts_count' => count($contactsAdded),
]);
}
}
}
Execute...
|
44533
|
|
44537
|
942
|
0
|
2026-04-17T08:51:39.217041+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776415899217_m2.jpg...
|
PhpStorm
|
faVsco.js – console [EU]
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
"podcast_audio_url"
New Line...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.03046875,"top":0.017361112,"width":0.0453125,"height":0.022222223},"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#11894 on JY-18909-automated-reports-ask-jiminny, menu","depth":5,"bounds":{"left":0.07578125,"top":0.017361112,"width":0.14960937,"height":0.022222223},"help_text":"Pull request #11894 exists for current branch JY-18909-automated-reports-ask-jiminny, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.78515625,"top":0.017361112,"width":0.01328125,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AutomatedReportsCommandTest","depth":6,"bounds":{"left":0.803125,"top":0.017361112,"width":0.09765625,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AutomatedReportsCommandTest'","depth":6,"bounds":{"left":0.9007813,"top":0.017361112,"width":0.01328125,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AutomatedReportsCommandTest'","depth":6,"bounds":{"left":0.9140625,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9273437,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.96015626,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9734375,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9867188,"top":0.017361112,"width":0.013281226,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Show Replace Field","depth":4,"bounds":{"left":0.12382813,"top":0.24236111,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Search History","depth":3,"bounds":{"left":0.13867188,"top":0.24166666,"width":0.00859375,"height":0.015277778},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"\"podcast_audio_url\"","depth":4,"bounds":{"left":0.1515625,"top":0.24166666,"width":0.06367187,"height":0.013888889},"value":"\"podcast_audio_url\"","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"New Line","depth":3,"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
-6359289565226403712
|
-8637542560107345084
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
"podcast_audio_url"
New Line
PhpStormFileFditViewNavigateCodelaravelRetactonToolsWindowHelpFV faVsco.s v#11894 on JY-18909-automated-reports-ask-iminny kProject vEids.txt=infection.son.distM+ INSTALL.mdM+ INTERNAL WEBHOOK SETUPiminny_storageM+ licenses.mdIM MakefileU package-lock.json= phpstan.neon.dist= phpstan-baseline.neon<> phounit xml1d raw sal_querv.salM+ KEADME.mO{o sonar-project.properties=test.py<> Untitled Diagram.xmlus vetur.config.jsM+ WEBHOOK_FILTERING_IMPLE›Ib External Librariesv E Scratches and Consolesv M Database ConsolesvA-Uc consoe -u4 DEAL RISKS [EU]A DI [EU]LEU EUv 4 iminny@localhostd console liminny@localfc Di liminny@localhost)c HS_local liminny@locald sr yiminny@localhost)V & PRODd zono_dev yiminny @loca& consoe PrODIA console 1 [PROD1d DI [PRODI> LQAL QAi> L QAI PRODV ACTAGNGd console STAGING¿ console 1 STAGNGIId uranus ISl AGING• MEytensionsv MScratches= phostorm_shortcuts.txt= scratch.txtUr scratch 1.isonUr scratch 2.isonUr scratch 3.isor= scratch_4.txtphp scratch_5.phpph9 scratch_6.phpG scratch_7.json( stage2.jsonE° test<test.htmlphr tmp.ohp(C AutomatedReportsService.phpC) SendReportJob.phpC SendReportMailJob.phpC ReportController.phpTokenBuilder.phpC TeamSetupController.phppnp apl.ono• Filesystem.php© Team.php© CreateHeldActivityEvent.php© TrackProviderInstalledEvent.php© ActivityLogged.phpC AutomatedReportsCallbackService.phpC RequestGenerateAskJiminnyReportJob.phpC RequestGenerateReportJob.phgT OpportunitySyncTrait.php xOpoortunity.onp© OpportunityUpdated.phpc) onnortuntvstadendated.nno© EventServiceProvider.php(C OpportunityPendingAiAnalysisAfterStageChanged.php(C RunOpportunityAiAnalysis.phpC ProcessAiAutomationAnalysisResults.php(C) ImportOpportunityBatch.phpT ImportBatchJobTrait.phpHasattributes.onoC) Service.php© AutomatedReportResult.php© AutomatedReport.php"podcast audio url"CcW0 resultstrait OpportunitySyncTraitBS2M2M19 ^7509319329339349359349411744943944945946947948949956951952953954955956957958959960961967963Y04966967968969976971912private function resolveBusinessProcess@string $pipelineld): ?BusinessProcesssthis->cachedBusinessProcesses Spipelineld = SbusinessProcess:return sbusinessProcess2 usagesprivate function getBusinessProcess(string $pipelineId): ?BusinessProcess{...}2 usagesprivate function resolveStage(BusinessProcess $businessProcess, ?string $stageId)=1578if (empty($stageld))return null:scachekey = sbusinessProcess->getid.':. sstageld;if Gisset(Sthis->cachedStages ScacheKeyJJ zreturn schis->cachedscagesLscachekeyJ;$stage = $this->crmEntityRepository->getPipelineStageByConditions($businessProcess.'crm provider id' => $stageld.'type' => Stage::TYPE_OPPORTUNITY,if ($stage === null) {фuh1s->mpontsrages(null, escagela):if (Sstage === null) {sthis->Logger->info HubSpot Stage does not exist =>. Sstageld):sth1s->cachedstagesLscachekey = sstage:return sstage;1 usageHelper code will nelp lDe lo unstand vour Laravel apo code. Generale Don't snow Anymore loday 8.09= custom.log= laravel.logL SF (iminny@localhostU scratch_1.jsonconnect.vueV onboard.vue< Hs local liminnyalocalnost4 console [EU]c crmenutykeposilory.ono(iii crm configurations [EUl¿console IPROD¿ consoe STAGINGI15561557155811552150015621563156415651566-1568=156915/0115/1= [CREDIT_CARD]— [CREDIT_CARD]— 1584158515841085100015871591159215951594157510Y6-1oY/1oYo15991600IT16011160216051002PlaygroundySELECT * FROM activities WHERE uuid_to_bin('2e6ff4d3-9faa-Oo jiminny v026 49 A22 23 X103 *select * trom crm_proriles where crm_contiguracion_1d = suy and crm_provider_1d = 525/85080select * trom opportunitles where crn_contiguration_1d = 51y and crm_provider_1d = 4101502select * trom accouncs where crm_contiguracion_1d = s1y and crm_provider_1d = 4/150650567,select * from contacts where crm confiquration id = 319 and crm provider id IN (66558744181* Owner 10z0 04/09000# contact 116779180 665587441856 - activity - Alex Howes [EMAIL] created 202# contact 219247563 742723347700 - [EMAIL] 2026-03-24# company 4176133 47150650569# deal 7100953 410150124747CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '• END) AS user_idu.email,sa.*,Towner 1o Frum soctal accounts saJuin users u on u.ld = sa.soclable_1aJuir tealllst 1..n<->1: on t.id = u.team idWheke U.teanl_ld- 400 and sa.provider- nuosporaselect * from features:select * from team features where feature id = 40:select * from teams where 1d = 556; # owner: 18101, crm: 477select * from crm_configurations where 1d = 477*sEuee * rrur users Warkedo siolouDELEEITCONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_idu.emallsarxt.owner id FROM social accounts saJOIN users u on U.id = sa.sociable idJOIN teams t 1..n‹->1: on t.id = u.team idWHERE U.team_id = 556 and sa.provider = 'integration-app':select * from oppirtunities where id = 7594349;select * from business_processes where 1d = 6024;select * +rombusiness_process_suages wnere scage_1d = 16552;select * tron oustness orocess staces where oustness orocess 1o = 00241select * tron stades wereTean 10 = 4571select * from teams where id = 4591SCLCLICONCAT(u.id, CASE WHEN U.id = t.owner_id THEN' (owner)' ELSE'' END) AS user_id,U.emailsa.*,t.owner_1d FROM soc1al_accounts saJOIN users u on u.1d = sa.soclable_10JOIN teams tl..n<->I: on t.ld = U.team_1dWHERE U.team_1d = 45% and sa.provider = 'nupspor :, 0lablSupport Daily • in 3h 9m100% 1Z7• Fri 17 Apr 11:51:38AutomatedRenortsCommandTestCascadeAutomated Report Rete Investigating HubSg+D ..bu1ldupporcunicybata only sets stage 1d lt sstage IS non-null line oss-ogo. But upsercopporcun1ty() always calls $opportunity->update($data) with whatever is in $datain upaareupportunity = sstace canoe nuce wnen soustnessprocess is null line ouz.U php$stage = $businessProcess ? $this->resolveStage(...) : null;When $stage IS null, stage id is absenttrom $data entirely. But update($data) doesn't mean "keepexisting value" for absent keys - it just doesn't touch that column. So stage id is preserved.but nere's the acrual osclllation source — resolvestage caches nuulaOpponunitysynciralt.onpenus→cachedscages Iscacheney. = sstage,1 caches nutl arcer importstagest is calleaThis means,Sync run 1 (new Service instance, empty cache): stage not in DB → importStages() called → $stage= null → stage_id not setin Sdata → updatel) doesn'ttouch stage_id → opportunity keepswhatever stage id was set previously (or null)Sync run 2 (fresh instance, empty cache again): stage IS in DB now (imported in run 1) → resolves tostage 400 → stage_id = 456 Wiitten OpportunityStageUpdated TiresSync run 3: same as run 2... unless importStages() somehow re-runs and overwrites the stagestable witn eltterentibsThe real oscillation: importStages() recreates stages with new DB IDsservice.onp:459-409— importstages uses updateorcreate on stages:• phppsuage = schis→>contig→stages→updareurtreatellcrm provider 1a -> o5.10Jaaaa.HThis is fine — it reuses the same DB id. BUT resolveBusinessProcess() also calls importStages( ) whena pipeline is missina (line 920). If a pipeline gets recreated with a new BusinessProcess DB record, the business_process_id stage relationship could point to a different stage DB IDMost lkely actual cause. Iwo alterent syne oatns are runnine concurrenty orin raple succession". syncudjects scheauled job → processes the deal 7 Writes stage_1d = 4502. SyncOpportunity job (triggered by something else) → resolves via a ditterent businessProcessinstance → writes stage id = 123Inese two jobs run independently with no cooraination, both calling upsertopportunity) on the sameopportunity, alternating between two valid stage IDs that belong to different BusinessProcess recordspointine lo the same Huosoot plpeline —le., auplicate BusinessProcess rows in the Db for the same cm_provader idCommand docke• docker exeoMode1s Crm Contis('team', fn($a) = \$q-rocesses@-suithlirashedtforeach($bps asSDp.oo-hale .""ed',*$bp-;i$bp->created atelere. ath•\$bp->deleted at .PHP_EOL;Run #ieSkiowthe crm has pipeline (business_process) and stage id that exists in DB. However there are thousands of<> Code Claude Sonnet 4.6winasun leams1591.23uir-o...
|
44532
|
|
44657
|
NULL
|
0
|
2026-04-17T08:57:02.609913+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776416222609_m1.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
+FirefoxFileEditViewHistoryBookmarksProfilesToolsW +FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelp→Cmeet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)DBeaverFileSearchSOL•Database Navigator Xee ar scorecarosE crm_configurationsE crm_field_datatcrureerweeenuweE crm_JayoutsE crm.JogsE crm_profilescrm.sync_batchestcntieoromdopportunity_stageststeamua contexth teomarestoresE team_settingscrowencesBa TriggersBt Events> E3 Administer|Du System Info4 Prod VIEW localhost:7832Uataossesro bookтarksSy Dashboardsn DiaorameEl Scripts164M170576M276MS00K96K320K|112K|528K|В•+?E Value•T DOLEE3 Metadata X123 ld" wuid123 crm_confi crm_configuratiAz crm_provi crm_provider_JeCatalog NameO INTEGER UNSIG jiminny1 BINARY3 VARCHAR4 VARCHAR"NADCUAGAt descrioto descnotronAELES123 length|lengthAz default_vi default_valueo Recort123 is_selecta is_selectable123 is_manda is_mandatorytonurerab is titerabie7 INTEGER UNSIG jiminny8 VARCHAR9 VARCHAR11 TINYINT12 TINYINTiminnyTRetrethaSave • [5 CancelProor ditn4 Prod EU VIEW • jminny » crm.fieldsala]Support Daily • in 3 h 3 m100% <478 • Fri 17 Apr 11:57:02Help..•• 40 0 $ 12 @ Q 8• F17Apr 11:57Dwvcroo.ecumtierem•0..9.asai crm-temolasscrmutk osxEE al_crm_templatesE ai_crm_ templatesopportunitiesE aicrm_templatesai_crm_templatesE DataEE SELECT ct.* FROM jiminny.crm_fields AS ef WHERE id in (3Jo01Lo300/08123 crm_configuration._jd366,708366,710366,713366,714366,717.366,719% wuidMeSQyae3 eni gE36760*S Ü-u MI "A [™ 367Hò ABbX* 7 clFB60x367367G 404J,Su "sCE- [1 367ISeieÜ_%/R ànO [16 367Gdmo-oads ve [1.367Az crm_provider_idcompetition.detailsdecision_criteria_detailsdecision_process__detailseconomic_buyer_detailsAZ label|Champion - Detailsidentified Pain - DetallsAz description• Az type |How strong is our champion'y i7 textareaCompetition - How weil do we i textareaDecision Criteria - How well do textarea- How well do textareaEconomic Buyer - How well do ' textareaIdentified Pain - How well do wi textareaMetrics - How weil do we under textarea123lllian KyuchukovNikolay NikolovNVasil Vasilevonemd ontMihail MihaylovTable Namecrm_fieldscrm_fieldsCrmtCmetiecrm_fieldscrm_fieldscrm_fieldscrm. tieldcrm-fieloMax Lenge»255Precision8a&%a8a8Scale JOBC TypeO INTEGERO BINARYO INTEGERO VARCHARo vArcHArO VARCHARO VARCHARO VARCHARo VARCHARO TINYNTO TINYINTOTENTENT7 row(s) fetched - 0.102s (0.03s fetch), on 2026-04-17 at 10-30-251-11.6.56,pngLukas Kovalik11:57 AM | Daily - Processing...
|
NULL
|
-728417500400137462
|
NULL
|
visual_change
|
ocr
|
NULL
|
+FirefoxFileEditViewHistoryBookmarksProfilesToolsW +FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelp→Cmeet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)DBeaverFileSearchSOL•Database Navigator Xee ar scorecarosE crm_configurationsE crm_field_datatcrureerweeenuweE crm_JayoutsE crm.JogsE crm_profilescrm.sync_batchestcntieoromdopportunity_stageststeamua contexth teomarestoresE team_settingscrowencesBa TriggersBt Events> E3 Administer|Du System Info4 Prod VIEW localhost:7832Uataossesro bookтarksSy Dashboardsn DiaorameEl Scripts164M170576M276MS00K96K320K|112K|528K|В•+?E Value•T DOLEE3 Metadata X123 ld" wuid123 crm_confi crm_configuratiAz crm_provi crm_provider_JeCatalog NameO INTEGER UNSIG jiminny1 BINARY3 VARCHAR4 VARCHAR"NADCUAGAt descrioto descnotronAELES123 length|lengthAz default_vi default_valueo Recort123 is_selecta is_selectable123 is_manda is_mandatorytonurerab is titerabie7 INTEGER UNSIG jiminny8 VARCHAR9 VARCHAR11 TINYINT12 TINYINTiminnyTRetrethaSave • [5 CancelProor ditn4 Prod EU VIEW • jminny » crm.fieldsala]Support Daily • in 3 h 3 m100% <478 • Fri 17 Apr 11:57:02Help..•• 40 0 $ 12 @ Q 8• F17Apr 11:57Dwvcroo.ecumtierem•0..9.asai crm-temolasscrmutk osxEE al_crm_templatesE ai_crm_ templatesopportunitiesE aicrm_templatesai_crm_templatesE DataEE SELECT ct.* FROM jiminny.crm_fields AS ef WHERE id in (3Jo01Lo300/08123 crm_configuration._jd366,708366,710366,713366,714366,717.366,719% wuidMeSQyae3 eni gE36760*S Ü-u MI "A [™ 367Hò ABbX* 7 clFB60x367367G 404J,Su "sCE- [1 367ISeieÜ_%/R ànO [16 367Gdmo-oads ve [1.367Az crm_provider_idcompetition.detailsdecision_criteria_detailsdecision_process__detailseconomic_buyer_detailsAZ label|Champion - Detailsidentified Pain - DetallsAz description• Az type |How strong is our champion'y i7 textareaCompetition - How weil do we i textareaDecision Criteria - How well do textarea- How well do textareaEconomic Buyer - How well do ' textareaIdentified Pain - How well do wi textareaMetrics - How weil do we under textarea123lllian KyuchukovNikolay NikolovNVasil Vasilevonemd ontMihail MihaylovTable Namecrm_fieldscrm_fieldsCrmtCmetiecrm_fieldscrm_fieldscrm_fieldscrm. tieldcrm-fieloMax Lenge»255Precision8a&%a8a8Scale JOBC TypeO INTEGERO BINARYO INTEGERO VARCHARo vArcHArO VARCHARO VARCHARO VARCHARo VARCHARO TINYNTO TINYINTOTENTENT7 row(s) fetched - 0.102s (0.03s fetch), on 2026-04-17 at 10-30-251-11.6.56,pngLukas Kovalik11:57 AM | Daily - Processing...
|
NULL
|
|
44658
|
NULL
|
0
|
2026-04-17T08:57:06.208690+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776416226208_m2.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorFV PhpStormFileEditViewNavigateCodeLaravelRefactorFV faVsco.js v#11894 on JY-18909-automated-reports-ask-iminnyProject vToolsWindowHelp> D Redisv D ServiceTraits€ OpportunitySy& SyncCrmEntiti© SyncFieldsTra© WriteCrm Trait.→IUTIS•Weohook© BatchSyncCollect© BatchSyncRedisS(c) Client.php© ClosedDealStage6 DealFieldsService© DecorateActivity.© FieldDefinitions.p© FieldTypeConveri© HubspotClientInte© HubspotTokenMa© PayloadBuilder.pt© RemoteCrmObjec(C) ResponseNormali© Service.php© SyncFieldAction.f© SyncRelatedActiv© WebhookSyncBa1v D IntegrationApp> D Accessors~ D Api© ActionUrl.php• EnumUrllnterfe© FlowUrl.php© PageResult.phe Proxyun.php(c) recuestsuloeLa kequestcxecu• RequestExecuSystemEvents© SystemUrl.phpC TokenBuilder.f• TokenBuilderlr© UrlBuilder.php> D Config> DDTO> MFilters>MJobs› _ ProspectSearchS> D ServiceTraits© DataClient.php© DecorateActivity.© LocalSearch.php© LocalSearchlntert© RemoteSearch.pr© Service.phpustenersM Metadata[ MigrationPipedriveD SalesforceD Traits© AutomatedReportsService.php© ReportController.phplokenbullaer.ono© Team.php© AutomatedReportsCallbackService.phpC RequestGenerateReportJob.phg© SendReportJob.php© SendReportMailJob.phpc leamsetuocontroller.onpphp api.phpTrackProviderInstalledEvent.php• Filesystem.php© ActivityLogged.php= custom.log= laravel.logA SF ljiminny@localhost]C" scratch_1.json< Hs local liminnyalocalnostA console [EU] )c crmenutykeposilory.onoA console [PROD]A console [STAGING]V connect.vueV Onboard.vue(i crm_configurations [EU]keouestoenerateaskJiminnykeportdob.ongT OpportunitySyncTrait.php xOpoortunity.onpOpportunityUpdated.phpEventServiceProvider.php© OpportunityPendingAiAnalysisAfterStageChanged.php© RunOpportunityAiAnalysis.php© ProcessAiAutomationAnalysisResults.php© ImportBatchJobTrait.php• HasAttributes.php© Service.php© AutomatedReportResult.php© AutomatedReport.phpO results155715581559156015041563"poacast aualo unl"X3 Cc W15641565trait OpportunitySyncTraitA32 X2 219 A Y 1566private function createOpportunity(string $crmId, array $properties, array Sassocia 156777277377477577615681569Sdata = Sthis->buidOpportunityData($properties, $accountId, $businessProcess =15701571nartrioures ='crm_configuration_id' => $this->config->getId(),'crm_provider_id' => $crmId,157215737781/7= 1574]:1575101782783784785786787788789790791792793794795796797$values = array_merge($attributes, $data);-15761577— 1578$opportunity = $this->crmEntityRepository->upsert0pportunity($attributes, $val™ 15791580$this->importExternalFieldData($properties, $opportunity->getId());sth1s->1mporcupporcunityconcacus(sopporcunlty, sassoclatlonst concactsJ:1581_1582-1583if ($oppornitv->wasRecentlyCreated &MatchActivitiesToNew0pportunity::dispatch($opportunity->getId());198415851080100/return $opportunity;15881589* Update existing opportunity1 usageprivate tunccion upaateupporcuntcy,scring pcrmta, array epropercles, array passocla 1595800802803804805806807159215931594$accountId = $this->resolveAccountId(Sassociations);1596$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? nul 1598$stage = $businessProcess ? $this->resolveStage($businessProcess, $propertiesl'!15991600$data = $this->buildOpportunityData($properties, $accountId,$businessProcess,160116021604808$attributes = ['crm_configuration_id' => $this->config->getId(),crm_provider_1d = scrmld,8078101:811812$values = array_merge($attributes, $data);$opportunity = $this->crmEntityRepository->upsert0pportunity($attributes, $valur813814$this->importExternalFieldData($properties, $opportunity->getId());Helper Code will help IDE to understand your Laravel app code. // Generate // Don't Show Anymore (today 8:59)Playground~Gajiminny~select * from crm_profiles where crm_configuration_id = 31026 A9 A22 X3 2103Mselect * from opportunities where crm_configuration_id = 319 and crm_provider_id = 41015012select * from accounts where crm_configuration_id = 319 and crm_provider_id = 47150650569;select * from contacts where crm_configuration_id = 319 and crm_provider_id IN ('665587441€* Owner 10z0 04/09000* contact16779180 665587441856 - activity - Alex Hoves [EMAIL] created 202# contact 219247563 742723347700 - [EMAIL] 2026-03-24# company 4176133 47150650569# deal 7100953 410150124747SELECTCONCAT(u.id, CASE WHEN u.id = t.owner_id THEN'(owner)' ELSE "' END) AS user_id,u.email,sa.*,t.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable_idwul reansTI.n<->I. on t.10 = U.tean 10iWreke U.teanl_ld- 400 and sa.provider - nupspotaselect x tron reacuresaselect * from team_features where feature_id = 40;select * from teams where id = 556; # owner: 18101, crm: 477select * from crm_configurations where id = 477;SELEC * FROM USeNS VHERE 10 = 181000DELEEITCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,u.email,sarxt.owner id FROM social accounts saJuin users u on u.1a = sa.soclable 10JOIN teams t 1.n<->1: on t.id = u.team_idWHERE u.team_id = 556 and sa.provider = 'integration-app';select * from opportunities where id = 7594349;select * from opportunity_stages where opportunity_id = 7594349;select * from business_processes where id = 6024;select * from business_process_stages where stage_id = 16352;select * from business_process_stages where business_process_id = 6024;select * tron stades wereLean 10 = 4571select * from teams where id = 4591SELECTCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' ELSE "' END) AS user_id,u.email,sa.*,t.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable_idJOIN teams t1..n<->1: on t.id = u.team_idWHERE U. team_id = 459 and sa.provider = 'hubspot';, 0lablSupport Daily - in 3h 3mL AutomatedReportsCommandTestv100% C•8 • Fri 17 Apr 11:57:05CascadeAutomated Report RetrC Investigating HubSp+D ...CUNUTUUUDiNWGcrm provider 1d => SS'1d',1, [...I:wThis is fine — it reuses the same DB id. BUT resolveBusinessProcess( also calls importStages( whena pipeline is missing (line 920). If a pipeline gets recreated with a new BusinessProcess DB record, the business_process_id - stage relationship could point to a different stage DB ID.Most llkely acrual cause: Iwo amerent sync oatns are runnino concurrenty or in rapia succession:. syncud ects scheculea oo 7 processes tne deal → wrles stade 10 = 4502. SyncOpportunity job (triggered by something else) → resolves via a different businessProcessinstance → writes stage id = 123These two jobs run independently with no coordination, both calling upsertopportunityl) on the sameopportunity, alternating between two valid stage IDs that belong to different BusinessProcess recordspointine lo the same Huosoot plpeline —le., auplicate BusinessProcess rows in the Db tor the same cmprovider_id.Command dockeforeach(\$bpsexe damkeny Mode 15(Crm Consaguratkon: :hereuas("team', fn(1$q) →> 15q-rocesses ()->withTrashed()-\$bp-'deleted_at']):• \$bp->created_at •I deletesip-soproveteted at PHP_EOL;Error Call to a member tunction businessprocesses( on null.command docke.• docker execdocker_lamp_1-artndastinker -execute"-get 1s conrprovader.foreach(\$bps\$bp-\$bp)'deleted at']);¡ created:' . \sbp->created_at .PHP_EOL; }, Nsoe teredrov gop de leted_at .Error Call to a member function getCrmConfiguration() on null.Command dockeo docker execdocker_lamp_1php artisan tinker --execute='use JiminnyVBusinessProcess;ind opportunaty 7594349PHP_EOL;echo 'Current stage id:Check for duplicate businessprocesses under samea Same contig(Sbps BustnespProces Iwithtrashed()-swhere("csm configuration_id', Isopp-CTueoTtvider_id''created_at', 'deleted_at'])reach(\$bps ass created echosbp-created_at1Psbpeteted:rov dsbv Isbp-sdeleted_at.IP_EOL; }the crm has pipeline (business_process) and stage id that exists in DB. However there are thousands ofupdates (part of them ). Also the opportunity stage_id is updated all the time. What causes that.|<> Code Claude Sonnet 4.6winasun leamsuir-o( 4 spaces...
|
NULL
|
4657013332987101101
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorFV PhpStormFileEditViewNavigateCodeLaravelRefactorFV faVsco.js v#11894 on JY-18909-automated-reports-ask-iminnyProject vToolsWindowHelp> D Redisv D ServiceTraits€ OpportunitySy& SyncCrmEntiti© SyncFieldsTra© WriteCrm Trait.→IUTIS•Weohook© BatchSyncCollect© BatchSyncRedisS(c) Client.php© ClosedDealStage6 DealFieldsService© DecorateActivity.© FieldDefinitions.p© FieldTypeConveri© HubspotClientInte© HubspotTokenMa© PayloadBuilder.pt© RemoteCrmObjec(C) ResponseNormali© Service.php© SyncFieldAction.f© SyncRelatedActiv© WebhookSyncBa1v D IntegrationApp> D Accessors~ D Api© ActionUrl.php• EnumUrllnterfe© FlowUrl.php© PageResult.phe Proxyun.php(c) recuestsuloeLa kequestcxecu• RequestExecuSystemEvents© SystemUrl.phpC TokenBuilder.f• TokenBuilderlr© UrlBuilder.php> D Config> DDTO> MFilters>MJobs› _ ProspectSearchS> D ServiceTraits© DataClient.php© DecorateActivity.© LocalSearch.php© LocalSearchlntert© RemoteSearch.pr© Service.phpustenersM Metadata[ MigrationPipedriveD SalesforceD Traits© AutomatedReportsService.php© ReportController.phplokenbullaer.ono© Team.php© AutomatedReportsCallbackService.phpC RequestGenerateReportJob.phg© SendReportJob.php© SendReportMailJob.phpc leamsetuocontroller.onpphp api.phpTrackProviderInstalledEvent.php• Filesystem.php© ActivityLogged.php= custom.log= laravel.logA SF ljiminny@localhost]C" scratch_1.json< Hs local liminnyalocalnostA console [EU] )c crmenutykeposilory.onoA console [PROD]A console [STAGING]V connect.vueV Onboard.vue(i crm_configurations [EU]keouestoenerateaskJiminnykeportdob.ongT OpportunitySyncTrait.php xOpoortunity.onpOpportunityUpdated.phpEventServiceProvider.php© OpportunityPendingAiAnalysisAfterStageChanged.php© RunOpportunityAiAnalysis.php© ProcessAiAutomationAnalysisResults.php© ImportBatchJobTrait.php• HasAttributes.php© Service.php© AutomatedReportResult.php© AutomatedReport.phpO results155715581559156015041563"poacast aualo unl"X3 Cc W15641565trait OpportunitySyncTraitA32 X2 219 A Y 1566private function createOpportunity(string $crmId, array $properties, array Sassocia 156777277377477577615681569Sdata = Sthis->buidOpportunityData($properties, $accountId, $businessProcess =15701571nartrioures ='crm_configuration_id' => $this->config->getId(),'crm_provider_id' => $crmId,157215737781/7= 1574]:1575101782783784785786787788789790791792793794795796797$values = array_merge($attributes, $data);-15761577— 1578$opportunity = $this->crmEntityRepository->upsert0pportunity($attributes, $val™ 15791580$this->importExternalFieldData($properties, $opportunity->getId());sth1s->1mporcupporcunityconcacus(sopporcunlty, sassoclatlonst concactsJ:1581_1582-1583if ($oppornitv->wasRecentlyCreated &MatchActivitiesToNew0pportunity::dispatch($opportunity->getId());198415851080100/return $opportunity;15881589* Update existing opportunity1 usageprivate tunccion upaateupporcuntcy,scring pcrmta, array epropercles, array passocla 1595800802803804805806807159215931594$accountId = $this->resolveAccountId(Sassociations);1596$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? nul 1598$stage = $businessProcess ? $this->resolveStage($businessProcess, $propertiesl'!15991600$data = $this->buildOpportunityData($properties, $accountId,$businessProcess,160116021604808$attributes = ['crm_configuration_id' => $this->config->getId(),crm_provider_1d = scrmld,8078101:811812$values = array_merge($attributes, $data);$opportunity = $this->crmEntityRepository->upsert0pportunity($attributes, $valur813814$this->importExternalFieldData($properties, $opportunity->getId());Helper Code will help IDE to understand your Laravel app code. // Generate // Don't Show Anymore (today 8:59)Playground~Gajiminny~select * from crm_profiles where crm_configuration_id = 31026 A9 A22 X3 2103Mselect * from opportunities where crm_configuration_id = 319 and crm_provider_id = 41015012select * from accounts where crm_configuration_id = 319 and crm_provider_id = 47150650569;select * from contacts where crm_configuration_id = 319 and crm_provider_id IN ('665587441€* Owner 10z0 04/09000* contact16779180 665587441856 - activity - Alex Hoves [EMAIL] created 202# contact 219247563 742723347700 - [EMAIL] 2026-03-24# company 4176133 47150650569# deal 7100953 410150124747SELECTCONCAT(u.id, CASE WHEN u.id = t.owner_id THEN'(owner)' ELSE "' END) AS user_id,u.email,sa.*,t.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable_idwul reansTI.n<->I. on t.10 = U.tean 10iWreke U.teanl_ld- 400 and sa.provider - nupspotaselect x tron reacuresaselect * from team_features where feature_id = 40;select * from teams where id = 556; # owner: 18101, crm: 477select * from crm_configurations where id = 477;SELEC * FROM USeNS VHERE 10 = 181000DELEEITCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,u.email,sarxt.owner id FROM social accounts saJuin users u on u.1a = sa.soclable 10JOIN teams t 1.n<->1: on t.id = u.team_idWHERE u.team_id = 556 and sa.provider = 'integration-app';select * from opportunities where id = 7594349;select * from opportunity_stages where opportunity_id = 7594349;select * from business_processes where id = 6024;select * from business_process_stages where stage_id = 16352;select * from business_process_stages where business_process_id = 6024;select * tron stades wereLean 10 = 4571select * from teams where id = 4591SELECTCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' ELSE "' END) AS user_id,u.email,sa.*,t.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable_idJOIN teams t1..n<->1: on t.id = u.team_idWHERE U. team_id = 459 and sa.provider = 'hubspot';, 0lablSupport Daily - in 3h 3mL AutomatedReportsCommandTestv100% C•8 • Fri 17 Apr 11:57:05CascadeAutomated Report RetrC Investigating HubSp+D ...CUNUTUUUDiNWGcrm provider 1d => SS'1d',1, [...I:wThis is fine — it reuses the same DB id. BUT resolveBusinessProcess( also calls importStages( whena pipeline is missing (line 920). If a pipeline gets recreated with a new BusinessProcess DB record, the business_process_id - stage relationship could point to a different stage DB ID.Most llkely acrual cause: Iwo amerent sync oatns are runnino concurrenty or in rapia succession:. syncud ects scheculea oo 7 processes tne deal → wrles stade 10 = 4502. SyncOpportunity job (triggered by something else) → resolves via a different businessProcessinstance → writes stage id = 123These two jobs run independently with no coordination, both calling upsertopportunityl) on the sameopportunity, alternating between two valid stage IDs that belong to different BusinessProcess recordspointine lo the same Huosoot plpeline —le., auplicate BusinessProcess rows in the Db tor the same cmprovider_id.Command dockeforeach(\$bpsexe damkeny Mode 15(Crm Consaguratkon: :hereuas("team', fn(1$q) →> 15q-rocesses ()->withTrashed()-\$bp-'deleted_at']):• \$bp->created_at •I deletesip-soproveteted at PHP_EOL;Error Call to a member tunction businessprocesses( on null.command docke.• docker execdocker_lamp_1-artndastinker -execute"-get 1s conrprovader.foreach(\$bps\$bp-\$bp)'deleted at']);¡ created:' . \sbp->created_at .PHP_EOL; }, Nsoe teredrov gop de leted_at .Error Call to a member function getCrmConfiguration() on null.Command dockeo docker execdocker_lamp_1php artisan tinker --execute='use JiminnyVBusinessProcess;ind opportunaty 7594349PHP_EOL;echo 'Current stage id:Check for duplicate businessprocesses under samea Same contig(Sbps BustnespProces Iwithtrashed()-swhere("csm configuration_id', Isopp-CTueoTtvider_id''created_at', 'deleted_at'])reach(\$bps ass created echosbp-created_at1Psbpeteted:rov dsbv Isbp-sdeleted_at.IP_EOL; }the crm has pipeline (business_process) and stage id that exists in DB. However there are thousands ofupdates (part of them ). Also the opportunity stage_id is updated all the time. What causes that.|<> Code Claude Sonnet 4.6winasun leamsuir-o( 4 spaces...
|
44656
|
|
44659
|
943
|
0
|
2026-04-17T08:57:10.613313+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776416230613_m1.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
+FirefoxFileEditViewHistoryBookmarksProfilesToolsW +FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelp→Cmeet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)DBeaverFileSearchI soL •Database Navigator Xee ar scorecarosE crm_configurationsE crm_field_datatacrureerweeenoweE crm_JayoutsE crm.JogsE crm_profilescrm.sync_batchestcentieoromdopportunity_stageststeamua contexth teomaresturesE team_settingswcrowencesBa TriggersBt Events> E3 Administer|Du System Info4 Prod VIEW localhost:7832v CyDatabasesJ Files - General Xro bookтarksSy Dashboardsan DiaorameEl Scripts164M170276MS00K96K320K|112K|528K|В•+?E Value•T DOLEE3 Metadata X123 kd" wuid123 crm_confi crm_configuratiAz crm_provi crm_provider_JeCatalog NameO INTEGER UNSIG jiminny1 BINARY3 VARCHAR4 VARCHAR"NADCUAGAt descroto descnotionAEYES123 length|lengthAz default_vi default_valueRecort123 is_selecta is_selectable123 is_manda is_mandatoryusnurterab is titerabie7 INTEGER UNSIG jiminny8 VARCHAR9 VARCHAR11 TINYINT12 TINYINTiminnye Refresh • | Save • |X CanceProor ditnPhpStorm4 Prod EU VIEW • jminny » crm.fieldsallSupport Daily • in 3 h 3 m100% <478 • Fri 17 Apr 11:57:10Help..••1 0 8 @ P Q 8• F17A0r 11:57Dwvcroo.ecumtiereE Datam•о..9.E al_crm_templar& Diagram# crm_fields X EB ai_crm_templatesE ai_crm_ templatesE opportunitiesE ai_crm_templatesE ai_crm_templatesEE SELECT ct.* FROM jiminny.crm_felds AS ef WHERE id in (3Jo01Lo306/08123 crm_configuration._jd366,708366,710366,713366,714|366,717.366,71986 uuidMeSOyae3 eni gE36760*S Ü-u ME "A [™ 367Hò ABbX* 7 clFB60x367367G e04J,au "sCE- [1 367ISeieÜ_%/R ànO [16 367Gdmo-oads ve [1.367Az crm_provider_idcompetition..detailsdecision_criteria_detailsdecision_process__detailseconomic_buyer_detailsAZ label|Champion - Detailsidentified Pain - DetallsAZ description• Az type |How strong is our champion'y i7 textaresCompetition - How weil do we i textareaDecision Criteria - How well do textarea- How well do textareaEconomic Buyer - How well do ' textareaIdentified Pain - How well do wi textareaMetrics - How weil do we under textareallian Kyuchukov4NNNikolay Nikolovonemd antVasil VasilevMihail MihaylovTable Namecrm_fieldscrm_fieldsCrmtcrm_fieldscrm_fieldscrm_fieldscrm. fieldcrm-fieloMax Lenge»8 a8255Precision8a&%a8a8Scale JOBC TypeO INTEGERO BINARYO INTEGERO VARCHARo vArcHArO VARCHARO VARCHARO VARCHARo VARCHARO TINYNTO TINYINTOTENTENT7 row(s) fetched - 0.102s (0.03s fetch), on 2026-04-17 at 10-30-254-11._6.56,pngLukas Kovalik11:57 AM | Daily - ProcessingLộ3...
|
NULL
|
-1366043289683679730
|
NULL
|
click
|
ocr
|
NULL
|
+FirefoxFileEditViewHistoryBookmarksProfilesToolsW +FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelp→Cmeet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)DBeaverFileSearchI soL •Database Navigator Xee ar scorecarosE crm_configurationsE crm_field_datatacrureerweeenoweE crm_JayoutsE crm.JogsE crm_profilescrm.sync_batchestcentieoromdopportunity_stageststeamua contexth teomaresturesE team_settingswcrowencesBa TriggersBt Events> E3 Administer|Du System Info4 Prod VIEW localhost:7832v CyDatabasesJ Files - General Xro bookтarksSy Dashboardsan DiaorameEl Scripts164M170276MS00K96K320K|112K|528K|В•+?E Value•T DOLEE3 Metadata X123 kd" wuid123 crm_confi crm_configuratiAz crm_provi crm_provider_JeCatalog NameO INTEGER UNSIG jiminny1 BINARY3 VARCHAR4 VARCHAR"NADCUAGAt descroto descnotionAEYES123 length|lengthAz default_vi default_valueRecort123 is_selecta is_selectable123 is_manda is_mandatoryusnurterab is titerabie7 INTEGER UNSIG jiminny8 VARCHAR9 VARCHAR11 TINYINT12 TINYINTiminnye Refresh • | Save • |X CanceProor ditnPhpStorm4 Prod EU VIEW • jminny » crm.fieldsallSupport Daily • in 3 h 3 m100% <478 • Fri 17 Apr 11:57:10Help..••1 0 8 @ P Q 8• F17A0r 11:57Dwvcroo.ecumtiereE Datam•о..9.E al_crm_templar& Diagram# crm_fields X EB ai_crm_templatesE ai_crm_ templatesE opportunitiesE ai_crm_templatesE ai_crm_templatesEE SELECT ct.* FROM jiminny.crm_felds AS ef WHERE id in (3Jo01Lo306/08123 crm_configuration._jd366,708366,710366,713366,714|366,717.366,71986 uuidMeSOyae3 eni gE36760*S Ü-u ME "A [™ 367Hò ABbX* 7 clFB60x367367G e04J,au "sCE- [1 367ISeieÜ_%/R ànO [16 367Gdmo-oads ve [1.367Az crm_provider_idcompetition..detailsdecision_criteria_detailsdecision_process__detailseconomic_buyer_detailsAZ label|Champion - Detailsidentified Pain - DetallsAZ description• Az type |How strong is our champion'y i7 textaresCompetition - How weil do we i textareaDecision Criteria - How well do textarea- How well do textareaEconomic Buyer - How well do ' textareaIdentified Pain - How well do wi textareaMetrics - How weil do we under textareallian Kyuchukov4NNNikolay Nikolovonemd antVasil VasilevMihail MihaylovTable Namecrm_fieldscrm_fieldsCrmtcrm_fieldscrm_fieldscrm_fieldscrm. fieldcrm-fieloMax Lenge»8 a8255Precision8a&%a8a8Scale JOBC TypeO INTEGERO BINARYO INTEGERO VARCHARo vArcHArO VARCHARO VARCHARO VARCHARo VARCHARO TINYNTO TINYINTOTENTENT7 row(s) fetched - 0.102s (0.03s fetch), on 2026-04-17 at 10-30-254-11._6.56,pngLukas Kovalik11:57 AM | Daily - ProcessingLộ3...
|
44657
|
|
44660
|
944
|
0
|
2026-04-17T08:57:23.618646+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776416243618_m2.jpg...
|
PhpStorm
|
faVsco.js – OpportunitySyncTrait.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
"podcast_audio_url"
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
0 results
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.03046875,"top":0.017361112,"width":0.0453125,"height":0.022222223},"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#11894 on JY-18909-automated-reports-ask-jiminny, menu","depth":5,"bounds":{"left":0.07578125,"top":0.017361112,"width":0.14960937,"height":0.022222223},"help_text":"Pull request #11894 exists for current branch JY-18909-automated-reports-ask-jiminny, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.78515625,"top":0.017361112,"width":0.01328125,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AutomatedReportsCommandTest","depth":6,"bounds":{"left":0.803125,"top":0.017361112,"width":0.09765625,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AutomatedReportsCommandTest'","depth":6,"bounds":{"left":0.9007813,"top":0.017361112,"width":0.01328125,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AutomatedReportsCommandTest'","depth":6,"bounds":{"left":0.9140625,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9273437,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.96015626,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9734375,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9867188,"top":0.017361112,"width":0.013281226,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Show Replace Field","depth":4,"bounds":{"left":0.12382813,"top":0.24236111,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Search History","depth":3,"bounds":{"left":0.13867188,"top":0.24166666,"width":0.00859375,"height":0.015277778},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"\"podcast_audio_url\"","depth":4,"bounds":{"left":0.1515625,"top":0.24166666,"width":0.06367187,"height":0.013888889},"value":"\"podcast_audio_url\"","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"New Line","depth":3,"bounds":{"left":0.22578125,"top":0.24166666,"width":0.00859375,"height":0.015277778},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Match Case","depth":3,"bounds":{"left":0.2375,"top":0.24166666,"width":0.00859375,"height":0.015277778},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Words","depth":3,"bounds":{"left":0.24765626,"top":0.24166666,"width":0.00859375,"height":0.015277778},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Regex","depth":3,"bounds":{"left":0.2578125,"top":0.24166666,"width":0.00859375,"height":0.015277778},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Replace History","depth":3,"bounds":{"left":0.23320313,"top":1.0,"width":0.00859375,"height":0.0},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextField","text":"Replace","depth":4,"role_description":"text field","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"New Line","depth":3,"bounds":{"left":0.23320313,"top":1.0,"width":0.00859375,"height":0.0},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Preserve case","depth":3,"bounds":{"left":0.23320313,"top":1.0,"width":0.00859375,"height":0.0},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"0 results","depth":4,"bounds":{"left":0.27382812,"top":0.24097222,"width":0.030078124,"height":0.015277778},"role_description":"text"},{"role":"AXButton","text":"Previous Occurrence","depth":4,"bounds":{"left":0.30390626,"top":0.24027778,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Occurrence","depth":4,"bounds":{"left":0.3140625,"top":0.24027778,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Filter Search Results","depth":4,"bounds":{"left":0.32421875,"top":0.24027778,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open in Window, Multiple Cursors","depth":4,"bounds":{"left":0.334375,"top":0.24027778,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXLink","text":"Click to highlight","depth":4,"role_description":"link","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Close","depth":4,"bounds":{"left":0.39804688,"top":0.24027778,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
5839034911645423165
|
-3926781795161090238
|
visual_change
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
"podcast_audio_url"
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
0 results
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
PhpStormFileEditViewNavigateCodeLaravelRefactorToolsWindowHelpFV faVsco.js#11894 on JY-18909-automated-reports-ask-jiminny k•Project v© AutomatedReportsService.php© SendReportJob.php© SendReportMailJob.php> D Redisv D ServiceTraits€ OpportunitySy& SyncCrmEntiti© SyncFieldsTra© WriteCrm Trait.→IUTIS•Weohook© BatchSyncCollect© BatchSyncRedisS(c) Client.php© ClosedDealStage6 DealFieldsService© DecorateActivity.© FieldDefinitions.p© FieldTypeConveri© HubspotClientInte© HubspotTokenMa© PayloadBuilder.pt© RemoteCrmObjec(C) ResponseNormali© Service.php© SyncFieldAction.f© SyncRelatedActiv© WebhookSyncBa1v D IntegrationApp> D Accessors~ D Api© ActionUrl.php• EnumUrllnterfe© FlowUrl.php© PageResult.phe Proxyun.php(c) recuestsuloeLa kequestcxecu• RequestExecuSystemEvents© SystemUrl.phpC TokenBuilder.f• TokenBuilderlr© UrlBuilder.php> D Config> MDTO> MFilters>MJobs› _ ProspectSearchS> D ServiceTraits© DataClient.php© DecorateActivity.© LocalSearch.php© LocalSearchlntert© RemoteSearch.pr© Service.php_ ListenersM Metadata[ MigrationPipedriveD SalesforceD Traits© ReportController.phpTokenBuilder.php• TeamSetupController.phpphp api.php© Team.php© CreateHeldActivityEvent.php© TrackProviderInstalledEvent.php• Filesystem.php© ActivityLogged.php© AutomatedReportsCallbackService.php© RequestGenerateAskJiminnyReportJob.phpC RequestGenerateReportJob.phg( OpportunitySyncTrait.php xC Opportunity.php© OpportunityUpdated.php© OpportunityStageUpdated.php© EventServiceProvider.php© OpportunityPendingAiAnalysisAfterStageChanged.php© RunOpportunityAiAnalysis.php1557155815591560© ProcessAiAutomationAnalysisResults.php(C) ImportOpportunityBatch.php© ImportBatchJobTrait.php• HasAttributes.php© Service.php© AutomatedReportResult.php© AutomatedReport.php"podcast_audio_url"X3 Cc WO resultstrait OpportunitySyncTrait($)BS2M2M19 ^926927Y48929750931704933934935936private function resolveBusinessProcess(?string $pipelineld): ?BusinessProcess'THubSpot] Deal is not attached to a pipeline',"onoe uune"→ sonoeuinelol$this->cachedBusinessProcesses[$pipelineId] = $businessProcess;15041563156415651566156715681569E 1570—157115721573=[CREDIT_CARD]— 1578=1579158015812 usages1582e private function hesolvestage(BusinesProcess SbusinessProcess, Pstring Sstageid) =1583if Cempty($stageId)) {1584return null;return $businessProcess;2 usages9379411private function getBusinessProcess(string $pipelineId): ?BusinessProcessf..}942943944945946947948949950951754953954955Yo0957958959960961964963964965966967968969970$cacheKey = $businessProcess->getId) . ':'• $stageId;if (isset($this->cachedStages[$cacheKey])) €return $this->cachedStages[$cacheKey];$stage = $this->crmEntityRepository->getPipelineStageByConditions(sousinessrrocess.'crm_provider_id' => $stageId,'type' => Stage::TYPE_OPPORTUNITY,):1158015871588158915901591159215931594159515961597m10Y8JoYY1600if ($stage === null) {$this->importStages(null, $stageId);16021605if ($stage === null) {U 1606$this->logger->info('[HubSpot] Stage does not exist => ' . $stageId);$this->cachedStages[$cacheKey] = $stage;= custom.log= laravel.logA SF ljiminny@localhost]C" scratch_1.json< Hs local liminnyalocalnostA console [EU] )• CrmEntityRepository.phpA console [PROD]A console [STAGING]V connect.vue(i crm_configurations [EU]V Onboard.vueHelper Code will help IDE to understand your Laravel app code. // Generate // Don't Show Anymore (today 8:59)PlaygroundGajiminny~select * from crm_profiles where crm_configuration_id = 31026 49 A22 X 3 X 103 ^select * from opportunities where crm_configuration_id = 319 and crm_provider_id = 41015012select * from accounts where crm_configuration_id = 319 and crm_provider_id = 47150650569;select * from contacts where crm_configuration_id = 319 and crm_provider_id IN ('665587441€* Owner 10z0 04/09000* contact16779180 665587441856 - activity - Alex Hoves [EMAIL] created 202# contact 2 19247563 742723347700 - [EMAIL] 2026-03-24# company 4176133 47150650569# deal 7100953 410150124747SELECTCONCAT(u.id, CASE WHEN u.id = t.owner_id THEN'(owner)' ELSE "' END) AS user_id,u.email,sa.*,t.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable_idJul reanst1..n<->1: on t.id = u.team idWreke U.teanl_ld- 400 and sa.provider - nupspotaselect x tron reacuresaselect * from team_features where feature_id = 40;select * from teams where id = 556; # owner: 18101, crm: 477select * from crm_configurations where id = 477;SELECT * FROM users WHERE id = 18101;DELEEITCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' ELSE '' END) AS user_id,u.email,sarxt.owner_id FROM social_accounts saJuin users u on u.1a = sa.soclable 10JOIN teams t 1.n<->1: on t.id = u.team_idWHERE u.team_id = 556 and sa.provider = 'integration-app';select * from opportunities where id = 7594349;select * from opportunity_stages where opportunity_id = 7594349;select * from business_processes where id = 6024;select * from business_process_stages where stage_id = 16352;select * from business_process_stages where business_process_id = 6024;select * tron stades wiereLean 10 = 4571select * from teams where id = 4591SELECTCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' ELSE "' END) AS user_id,u.email,sa.*,t.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable_idJOIN teams t1..n<->1: on t.id = u.team_idWHERE U. team_id = 459 and sa.provider = 'hubspot';, 0lablSupport Daily - in 3h 3mAutomatedRenortsCommandTest100% 1Z78 • Fri 17 Apr 11:57:23CascadeAutomated Report RetrInvestigating HubS:1. SyncObjects scheduled job → processes the deal → writes stage_id = 4562. SyncOpportunity job (triggered by something else) → resolves via a different businessProcessInstance → writes stade 1d = 123wThese two jobs run independently with no coordination, both calling upsertOpportlcy on tne sameopportunity, alternating between two valid stage IDs that belong to ditferent BusinessProcess recordspointing to the same HubSpot pipeline - i.e. duplicate BusinessProcess rows in the DB for the same crmprovider_id.Command docke,• dockerexee>wheret°1a",artisan tinker —-execute="e15 (Cp Consaguratkon: :eercuas(" team', fn(\$a) => Isa-foreach(\$bpsoproyi deredLat PHP EOL;Error Call to a member function businessProcesses on null.Command docker• docker execdocker_lamp_1php artisan tinker --execute="\$team = \Jiminny \Models\Team: : find(459);I$config =oLeall\$config-(['iasconfig->busithTrashed ()--nangbps as (seate d.*>created_atPHP_EOL; }iepp-odereted at .Error Call to a member function getCrmConfiguration() on null.command docke,o doc 2imxnc dockes Comleus phe srtosan tinker -execute"1nd opportunity 1594349ÍSOPP = О31Opportunity:: find(7594349);busineforeach(\$bpsPHP- EOL; O,as created: eccreated_at',deleted at'->created atIsbp-Teted:rov Isbp->deleted_at .nuil on tine 3?WARNING </warning> Attempt to read property "crm_configuration_id" onConfig ID:<warning> WARNING </warning> Attempt to read property "stage_id" on null on linethe crm has pipeline (business_process) and stage id that exists in DB. However there are thousands ofupdates (part of them ). Also the opportunity stage_id is updated all the time. What causes that.]<> Code Claude Sonnet 4.6winasun leams942:24uir-o( 4 spaces...
|
NULL
|
|
44741
|
NULL
|
0
|
2026-04-17T09:02:23.750504+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776416543750_m2.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorToo PhpStormFileEditViewNavigateCodeLaravelRefactorToolsWindowHelpFV faVsco.s v#11894 on JY-18909-automated-reports-ask-jiminny k ~Project v© AutomatedReportsService.php© SendReportJob.php© SendReportMailJob.php© ReportController.phplo lokenbullder.ono© TeamSetupController.phpphp api.php= ids.txtCreateHeldActivityEvent.phpTrackProviderInstalledEvent.php© ActivityLoggea.phpAutomatedReportsCallbackService.phpRequestGenerateaskJiminnykeportJob.ono=infection.son.dist© SyncOpportunity.phpOpportunitySyncTrait.php© Opportunity.php© OpportunityUpdated.php© OpportunityStageUpdated.php© EventServiceProvider.phpM+INSTALL.mdM+INTERNAL_WEBHOOK_SETUP.m© RunOpportunityAiAnalysis.php© ProcessAiAutomationAnalysisResults.php© ImportOpportunityBatch.php© ImportBatchJobTrait.php©HasAttributes.php© Service.php xE jiminny_storage10.02.zs vasllevclass service excenas baseservice ImplementsM+ licenses.md24.01.25 Papazovpublic function importStages(?array $types = null, ?string $missingStageName = null): ?StageM Makefile19.03.1o Granamreturn $missingStage;O package-lock.json19.03.18 Graham482= phpstan.neon.dist19.03.18 Graham483= phpstan-baseline.neor25.06.18 Graham484/**< phpunit.xml25.06.18 Graham485* OinheritdacTe raw_sql_query.sql25.06.18 Graham486*/M+ KEADME.mO14.08.24 Vasilev487 C›public function syncOrganization(): voidf...}{o sonar-project.properties7.04.18Graham499E test.py25.06.18 Granam500<> Untitled Diagram.xml**Z.Uo.lo Granam501* @inheritdocIs vetur.config.js140112Pa0aZ0V502M+ WEBHOOK_FILTERING_IMPLEMEih External LibrariesL.01.44tonl-)iminny503* @throws CrmException25.06.18 Graham504E° Scratches and Consoles25.09.19 Graham505 €t >public function syncProfiles(?User $userToSearch = null): ?Profilef...}v D Database Consoles2.04.18Graham557« console [EU]4 DEAL RISKS [EU]A DI [EU]A EU [EU]v A jiminny@localhostA console [jiminny@localhosDI [jiminny@localhost]A HS_local [iminny@localhoA SF [jiminny@localhost]A zoho_dev ljiminny@localhV & PROD& consoe PRODIc consoe IrrouIA DI [PROD]A QAÁ QAI2 QAI PROD• A STAGINGA console [STAGING]A console_1 [STAGING]« uranus [STAGING]> D Extensionsv D ScratchesE°phpstorm_shortcuts.txt° scratch.txtC° scratch_1.json(° scratch_2.jsonC* scratch_3.json= scratch_4.txtphy scratch_5.phpphg scratch_6.phpC° scratch_7jsonC° stage2.jsonE° test<°test.htmlph$ tmp.phpFilesystem.php© Team.php© RequestGenerateReportJob.php© OpportunityPendingAiAnalysisAfterStageChanged.php© AutomatedReportResult.php48 842 M1 M33 11 ^24.10.20 Graham24.10.20 Graham4.04.18Graham4.04.18Graham4.04.18Graham23.09.22 Papazov2.04.18 Graham14.04.22 Kovalik2.04.18olahalt2.04.18 Graham2.04.18 Graham12.11.24 Kovalik4.04.18Graham4.04.18 Graham4.04.18Graham4.04.18Granam18.03.25 Ivanov4.04.10iranalm4.04.18Granam4.04.18Jlahalt4.04.18Jlahalt23.09.22 Papazov19.03.18 Graham28.06.19 Graham15.05.23 Stamatov15.05.23 Stamatov22.05.23 Vasilev2.05.23 Vasllev4.0o.45 vaslevLL.Uo.zs vasllevLL.Uo.zs vasllevLL.Uo.cs VasllevLL.Uo.cs Vasllev26.05.23 Stamatov28.06.19 Graham12.11.24 Kovalik4.04.18cranam558593594595596597 €t >085684685686687688 €t >793794795796797 €t >834855856857858 6t >862863864865866867809869870871872873875 CT >Lusagesprivate function generateNameSearchPayLoad(string $name, int $offset, int $limit): arrayf..,* @inheritdocpublic function find(string $name, array $scopes): arrayf...}/*** @inheritdoc*/public function findOpportunities(?string $crmAccountId, ?string $crmContactid, ?int $userId = null): array{...}* Oinheritdocpublic function getTasks(?string $objectType, string $objectid, ?string $opportunityId): arrayf...}* Oinheritdoc*/public function getEvents(string $objectType, string $objectId, ?string $opportunityId): arrayf...,/*** Try to find CRM Objects using email address* @return null/arrayfLead|nuLL,Accounc/null,uppor cuntuu nout.contace nuet.Stage|null,string|nullpublic function matchExactlyByEmail(string $email, ?int $userId = null): ?arrayf...}Helper code will nelp IDt lo understand vour Laravel apo code. Generale Don't snow Anymore loday 8.09> 0lablSupport Daily - in 2h 58 m100% C•U AutomatedReportsCommandTestv= custom.log= laravel.logA SF [jiminny@localhost]C scratch_1.jsonV Onboard.vueA HS_local [jiminny@localhost]A console (EU]V connect.vue© CrmEntityRepository.phpfi crm_configurations [EU]A console [PROD]A console [STAGING]row v50,0T- WHERE id = 367X:Auto v=- ORDER BYQMA8 • Fri 17 Apr 12:02:23Diduuid (UUID with time-low and time-high swapped)I team_id[notifiable_user_idJ providerDedition0 instanceis_sandboxI versionI installed_app_version!O sync_metadatasync_objectsJO auto_sync_activitycrm_provider_id- I crm_base_url=last_synced_atIn leads sunced ataccounts_synced_atcontacts_synced_atopportunities_synced_at# contact_roles_synced_at*Dover_quota_atDapi_disabled_atsettingsopportunity_assignment_ruleopoorrunty lax valuue! opportunity_max_age[ opportunity_value_field_id! trigger_assignment_rulesstore transcript! softphone_override_prospectdefault_currencyI created_atI updated at3671a0cт045-0502-4508-2050-1T21025400459<null>nubspoc<null><nul>ShULL3364459sensat.co2026-04-17 08:46:04ShULU<nU L<nuli><null>SIULL<null><null>K"opportunity_sync_period": "6m", "oopen-recently-updated6958000.003230<null>GRP2025-04-02 11:33:462026-04-17 08:46:04SUM: 0 24:1 W Windsurf Teams...
|
NULL
|
7325751266207744462
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorToo PhpStormFileEditViewNavigateCodeLaravelRefactorToolsWindowHelpFV faVsco.s v#11894 on JY-18909-automated-reports-ask-jiminny k ~Project v© AutomatedReportsService.php© SendReportJob.php© SendReportMailJob.php© ReportController.phplo lokenbullder.ono© TeamSetupController.phpphp api.php= ids.txtCreateHeldActivityEvent.phpTrackProviderInstalledEvent.php© ActivityLoggea.phpAutomatedReportsCallbackService.phpRequestGenerateaskJiminnykeportJob.ono=infection.son.dist© SyncOpportunity.phpOpportunitySyncTrait.php© Opportunity.php© OpportunityUpdated.php© OpportunityStageUpdated.php© EventServiceProvider.phpM+INSTALL.mdM+INTERNAL_WEBHOOK_SETUP.m© RunOpportunityAiAnalysis.php© ProcessAiAutomationAnalysisResults.php© ImportOpportunityBatch.php© ImportBatchJobTrait.php©HasAttributes.php© Service.php xE jiminny_storage10.02.zs vasllevclass service excenas baseservice ImplementsM+ licenses.md24.01.25 Papazovpublic function importStages(?array $types = null, ?string $missingStageName = null): ?StageM Makefile19.03.1o Granamreturn $missingStage;O package-lock.json19.03.18 Graham482= phpstan.neon.dist19.03.18 Graham483= phpstan-baseline.neor25.06.18 Graham484/**< phpunit.xml25.06.18 Graham485* OinheritdacTe raw_sql_query.sql25.06.18 Graham486*/M+ KEADME.mO14.08.24 Vasilev487 C›public function syncOrganization(): voidf...}{o sonar-project.properties7.04.18Graham499E test.py25.06.18 Granam500<> Untitled Diagram.xml**Z.Uo.lo Granam501* @inheritdocIs vetur.config.js140112Pa0aZ0V502M+ WEBHOOK_FILTERING_IMPLEMEih External LibrariesL.01.44tonl-)iminny503* @throws CrmException25.06.18 Graham504E° Scratches and Consoles25.09.19 Graham505 €t >public function syncProfiles(?User $userToSearch = null): ?Profilef...}v D Database Consoles2.04.18Graham557« console [EU]4 DEAL RISKS [EU]A DI [EU]A EU [EU]v A jiminny@localhostA console [jiminny@localhosDI [jiminny@localhost]A HS_local [iminny@localhoA SF [jiminny@localhost]A zoho_dev ljiminny@localhV & PROD& consoe PRODIc consoe IrrouIA DI [PROD]A QAÁ QAI2 QAI PROD• A STAGINGA console [STAGING]A console_1 [STAGING]« uranus [STAGING]> D Extensionsv D ScratchesE°phpstorm_shortcuts.txt° scratch.txtC° scratch_1.json(° scratch_2.jsonC* scratch_3.json= scratch_4.txtphy scratch_5.phpphg scratch_6.phpC° scratch_7jsonC° stage2.jsonE° test<°test.htmlph$ tmp.phpFilesystem.php© Team.php© RequestGenerateReportJob.php© OpportunityPendingAiAnalysisAfterStageChanged.php© AutomatedReportResult.php48 842 M1 M33 11 ^24.10.20 Graham24.10.20 Graham4.04.18Graham4.04.18Graham4.04.18Graham23.09.22 Papazov2.04.18 Graham14.04.22 Kovalik2.04.18olahalt2.04.18 Graham2.04.18 Graham12.11.24 Kovalik4.04.18Graham4.04.18 Graham4.04.18Graham4.04.18Granam18.03.25 Ivanov4.04.10iranalm4.04.18Granam4.04.18Jlahalt4.04.18Jlahalt23.09.22 Papazov19.03.18 Graham28.06.19 Graham15.05.23 Stamatov15.05.23 Stamatov22.05.23 Vasilev2.05.23 Vasllev4.0o.45 vaslevLL.Uo.zs vasllevLL.Uo.zs vasllevLL.Uo.cs VasllevLL.Uo.cs Vasllev26.05.23 Stamatov28.06.19 Graham12.11.24 Kovalik4.04.18cranam558593594595596597 €t >085684685686687688 €t >793794795796797 €t >834855856857858 6t >862863864865866867809869870871872873875 CT >Lusagesprivate function generateNameSearchPayLoad(string $name, int $offset, int $limit): arrayf..,* @inheritdocpublic function find(string $name, array $scopes): arrayf...}/*** @inheritdoc*/public function findOpportunities(?string $crmAccountId, ?string $crmContactid, ?int $userId = null): array{...}* Oinheritdocpublic function getTasks(?string $objectType, string $objectid, ?string $opportunityId): arrayf...}* Oinheritdoc*/public function getEvents(string $objectType, string $objectId, ?string $opportunityId): arrayf...,/*** Try to find CRM Objects using email address* @return null/arrayfLead|nuLL,Accounc/null,uppor cuntuu nout.contace nuet.Stage|null,string|nullpublic function matchExactlyByEmail(string $email, ?int $userId = null): ?arrayf...}Helper code will nelp IDt lo understand vour Laravel apo code. Generale Don't snow Anymore loday 8.09> 0lablSupport Daily - in 2h 58 m100% C•U AutomatedReportsCommandTestv= custom.log= laravel.logA SF [jiminny@localhost]C scratch_1.jsonV Onboard.vueA HS_local [jiminny@localhost]A console (EU]V connect.vue© CrmEntityRepository.phpfi crm_configurations [EU]A console [PROD]A console [STAGING]row v50,0T- WHERE id = 367X:Auto v=- ORDER BYQMA8 • Fri 17 Apr 12:02:23Diduuid (UUID with time-low and time-high swapped)I team_id[notifiable_user_idJ providerDedition0 instanceis_sandboxI versionI installed_app_version!O sync_metadatasync_objectsJO auto_sync_activitycrm_provider_id- I crm_base_url=last_synced_atIn leads sunced ataccounts_synced_atcontacts_synced_atopportunities_synced_at# contact_roles_synced_at*Dover_quota_atDapi_disabled_atsettingsopportunity_assignment_ruleopoorrunty lax valuue! opportunity_max_age[ opportunity_value_field_id! trigger_assignment_rulesstore transcript! softphone_override_prospectdefault_currencyI created_atI updated at3671a0cт045-0502-4508-2050-1T21025400459<null>nubspoc<null><nul>ShULL3364459sensat.co2026-04-17 08:46:04ShULU<nU L<nuli><null>SIULL<null><null>K"opportunity_sync_period": "6m", "oopen-recently-updated6958000.003230<null>GRP2025-04-02 11:33:462026-04-17 08:46:04SUM: 0 24:1 W Windsurf Teams...
|
NULL
|
|
44744
|
NULL
|
0
|
2026-04-17T09:02:29.716576+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776416549716_m1.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
+FirefoxFileEditViewHistoryBookmarksProfilesToolsW +FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelp→meet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)PhpStormToolsHelpnyDebugCommand © a hand© DetermineUpdateOperationAction© UpdateCrmTargetDto18© HubspotWebhookServiceProviderweboooktventprocesson© OpportunityStageUpdated© Opportunity|© OpportunityPendingAlAnalysisAfter StageChanged@ DebugCommand© JminnyDebugCommand«?php228declare(strict_types=1);10 12* Class JiminnyOebugConmand12 1015 9114 81* Bnackase Jininng|Console\Conmands1 usage & Nikola Pedcanski +1class Jainrocouocoocano extends coccano16 €17 56*18 4protected Ssignature = "Jininny:debug":NENNWNN22ш N H• en aSopportunity • |Jininny|Models|Opportunity:: find(id: 115):Sopportunity->stage_id = '1':sd(Sopportunitx):Sres = SzoonRecordingDetector->isZoonRecording(httos:/laps-eul.hubspot.com/sa(Scts):(ahl= Support Daily • in 2h 58 m100% C478 • Fri 17 Apr 12:02:29A 6SubmAudiofileServiceTestvCascadeNew Cascade@ • Q 8• Fri17 Apr 12:02.dn|•llian KyuchukovNikolay NikolovMIWCascade Code x 0Kick off a new project. Make changeslacross your entire codebase.Vasil VasilevMihail MihayloAsk anything (XOL)W Windsurf Teams (Pre-Release)Symfony22:36 LFUTF-8Co 4 spacesI master •184-11.6.56,pngLukas Kovalik12:02 PM Daily - Processing...
|
NULL
|
-3593321754767228791
|
NULL
|
visual_change
|
ocr
|
NULL
|
+FirefoxFileEditViewHistoryBookmarksProfilesToolsW +FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelp→meet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)PhpStormToolsHelpnyDebugCommand © a hand© DetermineUpdateOperationAction© UpdateCrmTargetDto18© HubspotWebhookServiceProviderweboooktventprocesson© OpportunityStageUpdated© Opportunity|© OpportunityPendingAlAnalysisAfter StageChanged@ DebugCommand© JminnyDebugCommand«?php228declare(strict_types=1);10 12* Class JiminnyOebugConmand12 1015 9114 81* Bnackase Jininng|Console\Conmands1 usage & Nikola Pedcanski +1class Jainrocouocoocano extends coccano16 €17 56*18 4protected Ssignature = "Jininny:debug":NENNWNN22ш N H• en aSopportunity • |Jininny|Models|Opportunity:: find(id: 115):Sopportunity->stage_id = '1':sd(Sopportunitx):Sres = SzoonRecordingDetector->isZoonRecording(httos:/laps-eul.hubspot.com/sa(Scts):(ahl= Support Daily • in 2h 58 m100% C478 • Fri 17 Apr 12:02:29A 6SubmAudiofileServiceTestvCascadeNew Cascade@ • Q 8• Fri17 Apr 12:02.dn|•llian KyuchukovNikolay NikolovMIWCascade Code x 0Kick off a new project. Make changeslacross your entire codebase.Vasil VasilevMihail MihayloAsk anything (XOL)W Windsurf Teams (Pre-Release)Symfony22:36 LFUTF-8Co 4 spacesI master •184-11.6.56,pngLukas Kovalik12:02 PM Daily - Processing...
|
NULL
|
|
44745
|
946
|
0
|
2026-04-17T09:02:55.599188+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776416575599_m2.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorToo PhpStormFileEditViewNavigateCodeLaravelRefactorToolsWindowHelpFV faVsco.js#11894 on JY-18909-automated-reports-ask-jiminny k ~Project v© AutomatedReportsService.php© SendReportJob.php© SendReportMailJob.php© ReportController.php© TokenBuilder.php= ids.txt© TeamSetupController.phppnp apl.onp• Filesystem.php© Team.phpc CrealenelaAcuviyevent.onoTrackProviderInstalledEvent.php=infection.son.dist© ActivityLogged.php© AutomatedReportsCallbackService.php© RequestGenerateAskJiminnyReportJob.php© RequestGenerateReportJob.phpM+INSTALL.mdM+INTERNAL_WEBHOOK_SETUP.m© SyncOpportunity.php© OpportunitySyncTrait.php© Opportunity.php© OpportunityUpdated.php© OpportunityStageUpdated.phpE jiminny_storageC EventServiceProvider.phpOpoorunityrenaingAlAnalysisArterstagecnangea.ono© RunOpportunityAiAnalysis.phpM+ licenses.md© ProcessAiAutomationAnalysisResults.php© ImportOpportunityBatch.php© ImportBatchJobTrait.php© HasAttributes.php© Service.php xM MakefileO package-lock.json© AutomatedReportResult.phpE team_id= phpstan.neon.dist10.02.23 Vasilevclass Service extends BaseService implementsBMA MMATA= phpstan-baseline.neor< phpunit.xml24.01.25 Papazov414public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage[notifiable_user_idTe raw_sql_query.sql19.03.1o Granam481return $missingStage;providerDedition19.03.18 Graham482M+ KEADME.mO{o sonar-project.properties19.03.18 Graham483In instanceE test.py25.06.18 Graham484/**[ is_sandbox<> Untitled Diagram.xml25.06.18 Graham485* OinheritdacI versionIs vetur.config.js25.06.18 Graham486*/D installed_app_versionM+ WEBHOOK_FILTERING_IMPLEME14.08.24 Vasilev487 Ct>public function syncOrganization(): voidf...}ih External Libraries7.04.18Graham499O sync_metadataE° Scratches and Consoles25.06.18 Graham500/**! sync_objectsv D Database ConsolesZ.Uo.lo Granam501*oinnentcaoeauto_sync_activity140112Pa0aZ0V50/4crm_provider_id2.01.24 toni-iiminny505* @throws CrmException« console [EU]4 DEAL RISKS [EU]25.06.18 Graham5041TIN crm base urlA DI [EU]25.09.19 Graham505 €t >public function syncProfiles(?User $userToSearch = null): ?Profile{...}! last_synced_atA EU [EU]2.04.18 Graham• leads_synced_atv A jiminny@localhost2 usagesA console [jiminny@localhos24.10.20 Graham558I accounts_synced_atprivate function generateNameSearchPayload(string $name, int $offset, int $limit): arrayf...In contacts snced atDI [jiminny@localhost]24.10.20 Graham593A HS_local [iminny@localho4.04.18Graham594opportunities_synced_at4.04.18Graham595A SF [jiminny@localhost]* @inheritdoc• contact_roles_synced_atA zoho_dev ljiminny@localh4.04.18Granam596over_quota_atV & PROD23.09.22 Papazov597 €t >public function find(string $name, array $scopes): arrayf...3• api_disabled_at& consoe PRODI2.04.18iranalm08514.04.22 KOVallkc consoe IrrouI684• settingsA DI [PROD]2.04.18Olanain685/**!O opportunity_assignment_ruleA QA2.04.18Graham686* OinheritdocÁ QAI2.04.18Graham687*/. opportunity_max_value2 QAI PROD12.11.24Kovalik688 €t >public function findOpportunities(?string $crmAccountId, ?string $crmContactid, ?int $userIdopportunity_max_ageY A STAGING4.04.18Graham793E opportunity_value_field_idA console [STAGING]4.04.18Graham794/**•O trigger_assignment_rulesA console_1 [STAGING]4.04.18Graham795* @inheritdoc« uranus [STAGING]store_transcript4.04.18Graham> D Extensions18.03.25 Ivanovpublic function getTasks(?string $objectType, string $objectId, ?string $opportunityId): arr !U softphone_override_prospectv D Scratches4.04.10Granam834! default_currencyE°phpstorm_shortcuts.txt4.04.18Granam805° scratch.txt4.04.18Grahamcreated_at856"oailelacuoeC° scratch_1.jsonupdated_at4.04.18 Graham857(° scratch_2.json23.09.22 Papazov858 6t >public function getEvents(string $objectType, string $objectId, ?string $opportunityId): arrC* scratch_3.json19.03.18 Graham= scratch_4.txt28.06.19 Graham86311Iphy scratch_5.php15.05.23 Stamatov864* Try to find CRM Objects using email addressphg scratch_6.php15.05.23 Stamatov865C° scratch_7json24.05.23 Vasilev866* Creturn null/arrayfC° stage2.json2.05.23 Vasilev867Lead|nuLL,E° test40o.45 vasley868Accounc/null,I 11<9 test.html24.00.23 vasllev807Opportunity nullph$ tmp.php22.05.23 Vasilev870Contact|null,22.05.23 Vasilev871Stage|null,22.05.23 Vasilev872Helper code will nelp IDe lo understanoAnymore (today 8:59)40hal"Suoport Daiv . in 2h.58m100% 1Z78 • Fri 17 Apr 12:02:551= AutomatedRenortsCommandTest= custom.log= laravel.logA SF [jiminny@localhost]C* scratch_1.json• CrmEntityRepository.phpii crm_configurations [EU] x ||L console [PROD]1 rowv50,0IX. Aulo VDDLQGEAT- WHERE id = 367V connent vueV Onboard vueA HS_local [jiminny@localhost]Al console (EU]Á console [STAGING]CSv~E- ORDER BYuvid (UUID with time-low and time-high swapped) ÷fa0cf643-d30e-43b8-ab3d-1fe18254609c459<hUILLhubspot<null><null><null>3364459sensat.co2026-04-1 08:46704<null><null><null><null><null><null>ShULl:"6m", "opportunity_sync_strategies":open-recently-updated6958000.000/00<hUILLGBP2025-04-02 11:33:462026-04-17 08:46:04SUM: 0 24:1winasur leams...
|
NULL
|
-9041178111812725005
|
NULL
|
idle
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorToo PhpStormFileEditViewNavigateCodeLaravelRefactorToolsWindowHelpFV faVsco.js#11894 on JY-18909-automated-reports-ask-jiminny k ~Project v© AutomatedReportsService.php© SendReportJob.php© SendReportMailJob.php© ReportController.php© TokenBuilder.php= ids.txt© TeamSetupController.phppnp apl.onp• Filesystem.php© Team.phpc CrealenelaAcuviyevent.onoTrackProviderInstalledEvent.php=infection.son.dist© ActivityLogged.php© AutomatedReportsCallbackService.php© RequestGenerateAskJiminnyReportJob.php© RequestGenerateReportJob.phpM+INSTALL.mdM+INTERNAL_WEBHOOK_SETUP.m© SyncOpportunity.php© OpportunitySyncTrait.php© Opportunity.php© OpportunityUpdated.php© OpportunityStageUpdated.phpE jiminny_storageC EventServiceProvider.phpOpoorunityrenaingAlAnalysisArterstagecnangea.ono© RunOpportunityAiAnalysis.phpM+ licenses.md© ProcessAiAutomationAnalysisResults.php© ImportOpportunityBatch.php© ImportBatchJobTrait.php© HasAttributes.php© Service.php xM MakefileO package-lock.json© AutomatedReportResult.phpE team_id= phpstan.neon.dist10.02.23 Vasilevclass Service extends BaseService implementsBMA MMATA= phpstan-baseline.neor< phpunit.xml24.01.25 Papazov414public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage[notifiable_user_idTe raw_sql_query.sql19.03.1o Granam481return $missingStage;providerDedition19.03.18 Graham482M+ KEADME.mO{o sonar-project.properties19.03.18 Graham483In instanceE test.py25.06.18 Graham484/**[ is_sandbox<> Untitled Diagram.xml25.06.18 Graham485* OinheritdacI versionIs vetur.config.js25.06.18 Graham486*/D installed_app_versionM+ WEBHOOK_FILTERING_IMPLEME14.08.24 Vasilev487 Ct>public function syncOrganization(): voidf...}ih External Libraries7.04.18Graham499O sync_metadataE° Scratches and Consoles25.06.18 Graham500/**! sync_objectsv D Database ConsolesZ.Uo.lo Granam501*oinnentcaoeauto_sync_activity140112Pa0aZ0V50/4crm_provider_id2.01.24 toni-iiminny505* @throws CrmException« console [EU]4 DEAL RISKS [EU]25.06.18 Graham5041TIN crm base urlA DI [EU]25.09.19 Graham505 €t >public function syncProfiles(?User $userToSearch = null): ?Profile{...}! last_synced_atA EU [EU]2.04.18 Graham• leads_synced_atv A jiminny@localhost2 usagesA console [jiminny@localhos24.10.20 Graham558I accounts_synced_atprivate function generateNameSearchPayload(string $name, int $offset, int $limit): arrayf...In contacts snced atDI [jiminny@localhost]24.10.20 Graham593A HS_local [iminny@localho4.04.18Graham594opportunities_synced_at4.04.18Graham595A SF [jiminny@localhost]* @inheritdoc• contact_roles_synced_atA zoho_dev ljiminny@localh4.04.18Granam596over_quota_atV & PROD23.09.22 Papazov597 €t >public function find(string $name, array $scopes): arrayf...3• api_disabled_at& consoe PRODI2.04.18iranalm08514.04.22 KOVallkc consoe IrrouI684• settingsA DI [PROD]2.04.18Olanain685/**!O opportunity_assignment_ruleA QA2.04.18Graham686* OinheritdocÁ QAI2.04.18Graham687*/. opportunity_max_value2 QAI PROD12.11.24Kovalik688 €t >public function findOpportunities(?string $crmAccountId, ?string $crmContactid, ?int $userIdopportunity_max_ageY A STAGING4.04.18Graham793E opportunity_value_field_idA console [STAGING]4.04.18Graham794/**•O trigger_assignment_rulesA console_1 [STAGING]4.04.18Graham795* @inheritdoc« uranus [STAGING]store_transcript4.04.18Graham> D Extensions18.03.25 Ivanovpublic function getTasks(?string $objectType, string $objectId, ?string $opportunityId): arr !U softphone_override_prospectv D Scratches4.04.10Granam834! default_currencyE°phpstorm_shortcuts.txt4.04.18Granam805° scratch.txt4.04.18Grahamcreated_at856"oailelacuoeC° scratch_1.jsonupdated_at4.04.18 Graham857(° scratch_2.json23.09.22 Papazov858 6t >public function getEvents(string $objectType, string $objectId, ?string $opportunityId): arrC* scratch_3.json19.03.18 Graham= scratch_4.txt28.06.19 Graham86311Iphy scratch_5.php15.05.23 Stamatov864* Try to find CRM Objects using email addressphg scratch_6.php15.05.23 Stamatov865C° scratch_7json24.05.23 Vasilev866* Creturn null/arrayfC° stage2.json2.05.23 Vasilev867Lead|nuLL,E° test40o.45 vasley868Accounc/null,I 11<9 test.html24.00.23 vasllev807Opportunity nullph$ tmp.php22.05.23 Vasilev870Contact|null,22.05.23 Vasilev871Stage|null,22.05.23 Vasilev872Helper code will nelp IDe lo understanoAnymore (today 8:59)40hal"Suoport Daiv . in 2h.58m100% 1Z78 • Fri 17 Apr 12:02:551= AutomatedRenortsCommandTest= custom.log= laravel.logA SF [jiminny@localhost]C* scratch_1.json• CrmEntityRepository.phpii crm_configurations [EU] x ||L console [PROD]1 rowv50,0IX. Aulo VDDLQGEAT- WHERE id = 367V connent vueV Onboard vueA HS_local [jiminny@localhost]Al console (EU]Á console [STAGING]CSv~E- ORDER BYuvid (UUID with time-low and time-high swapped) ÷fa0cf643-d30e-43b8-ab3d-1fe18254609c459<hUILLhubspot<null><null><null>3364459sensat.co2026-04-1 08:46704<null><null><null><null><null><null>ShULl:"6m", "opportunity_sync_strategies":open-recently-updated6958000.000/00<hUILLGBP2025-04-02 11:33:462026-04-17 08:46:04SUM: 0 24:1winasur leams...
|
44741
|
|
44746
|
945
|
0
|
2026-04-17T09:03:00.169368+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776416580169_m1.jpg...
|
PhpStorm
|
faVsco.js – crm_configurations [EU]
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
42
1
33
1
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Exception;
use Generator;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\Cache;
use InvalidArgumentException;
use Jiminny\Contracts\Repositories\TeamRepository;
use Jiminny\Contracts\Services\Crm\ClientInterface;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\HubspotInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SavePlaybackLinkToCrmInterface;
use Jiminny\Contracts\Services\Crm\SendSummaryToCrmInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Jobs\Crm\NoteObject;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Contracts\ActivityContract;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\Layout;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Participant;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\ParticipantRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\Hubspot\Actions\SyncArchivedProfilesAction;
use Jiminny\Services\Crm\Hubspot\Fields\ValueNormalizer;
use Jiminny\Services\Crm\Hubspot\ServiceTraits\OpportunitySyncTrait;
use Jiminny\Services\Crm\Hubspot\ServiceTraits\SyncCrmEntitiesTrait;
use Jiminny\Services\Crm\Hubspot\ServiceTraits\SyncFieldsTrait;
use Jiminny\Services\Crm\Hubspot\ServiceTraits\WriteCrmTrait;
use Jiminny\Services\Crm\MatchDomainByEmailInterface;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Services\Crm\ResolveCompanyNameByEmailTrait;
use Jiminny\Utils\PlaybackUrlBuilder;
use Sentry;
use SevenShores\Hubspot\Exceptions\BadRequest;
use Throwable;
use UnexpectedValueException;
/**
* @phpstan-type CrmFieldDefinition array{
* name: string,
* label: string,
* description: string,
* type: string,
* fieldType: string,
* hidden: bool,
* showCurrencySymbol: bool,
* options: array<array{
* id: string,
* label: string,
* value?: string,
* }
*/
class Service extends BaseService implements
HubspotInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
SendSummaryToCrmInterface,
MatchDomainByEmailInterface,
SavePlaybackLinkToCrmInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
use ResolveCompanyNameByEmailTrait;
use SyncCrmEntitiesTrait;
use WriteCrmTrait;
use SyncFieldsTrait;
use OpportunitySyncTrait;
private const int ENGAGEMENT_BODY_MAX_LENGTH = 65536;
private const string LOG_DATE_FORMAT = 'Y-m-d H:i:s';
private const int BATCH_UPDATE_LIMIT = 100;
private const string TEN_SECONDLY_ROLLING_POLICY = 'TEN_SECONDLY_ROLLING';
private const int TEN_SECONDLY_ROLLING_LIMIT = 10;
private const string CALLS_SEARCH_ENDPOINT = '[URL_WITH_CREDENTIALS] ClientInterface|Client
*/
protected $client;
protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
protected CrmEntityRepository $crmEntityRepository;
protected ProspectPhotoPathService $prospectPhotoPathService;
private SyncFieldAction $syncFieldAction;
private PayloadBuilder $payloadBuilder;
private SyncRelatedActivityManager $syncRelatedActivityManager;
private SyncArchivedProfilesAction $syncArchivedProfilesAction;
private WebhookSyncBatchProcessor $batchProcessor;
public function __construct(
Client $client,
SyncFieldAction $syncFieldAction,
PayloadBuilder $payloadBuilder,
ProspectPhotoPathService $prospectPhotoPathService,
SyncArchivedProfilesAction $syncArchivedProfilesAction,
WebhookSyncBatchProcessor $batchProcessor,
) {
parent::__construct();
$this->client = $client;
$this->syncFieldAction = $syncFieldAction;
$this->prospectPhotoPathService = $prospectPhotoPathService;
$this->payloadBuilder = $payloadBuilder;
$this->syncArchivedProfilesAction = $syncArchivedProfilesAction;
$this->batchProcessor = $batchProcessor;
$this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$this->syncRelatedActivityManager = app(SyncRelatedActivityManager::class, [
'client' => $this->client,
'payloadBuilder' => $this->payloadBuilder,
'logger' => $this->logger,
]);
$this->crmEntityRepository = app(CrmEntityRepository::class);
$this->dealFieldsService = app(DealFieldsService::class);
}
public function getDisplayName(): string
{
return 'HubSpot';
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_HUBSPOT);
}
public function getClient(): Client
{
/** @var Client */
return $this->client;
}
/**
* Convert raw field data into a format compatible with CRM APIs.
*
* @param bool $internal Direction of the conversion.
* True is pulling from CRM, false normalize before sending to CRM.
*/
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return ValueNormalizer::normalize(
fieldType: $fieldType,
fieldValue: $fieldValue,
isInbound: $internal,
);
}
public function getRecordTypes(string $crmObject): array
{
return [];
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {
$defaultFields = FieldDefinitions::defaultTaskFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'activityType',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
/**
* @inheritdoc
*/
public function getDefaultActivityLayoutFields(string $activityType, string $layoutType): array
{
$fields = [];
if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {
// Outcome should always be provided calls/meetings.
$fieldData = [
[
'crm_provider_id' => $layoutType === Layout::TYPE_SOFTPHONE_SUMMARY ? 'disposition' : 'meetingOutcome',
'object_type' => Field::OBJECT_TASK,
],
];
foreach ($fieldData as $data) {
$field = $this->config->fields()->where($data)->first();
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
}
return $fields;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldData = FieldDefinitions::followupFieldsFilter();
foreach ($fieldData as $data) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function syncField(Field $field): void
{
switch ($field->object_type) {
case Field::OBJECT_ACCOUNT:
$crmField = $this->client->getInstance()->companyProperties()->get($field->crm_provider_id);
break;
case Field::OBJECT_CONTACT:
$crmField = $this->client->getInstance()->contactProperties()->get($field->crm_provider_id);
break;
case Field::OBJECT_OPPORTUNITY:
$crmField = $this->client->getInstance()->dealProperties()->get($field->crm_provider_id);
break;
case Field::OBJECT_TASK:
$this->syncSingleTaskField($field);
return;
default:
return;
}
$this->syncFieldAction->execute($field, $crmField->toArray());
}
/**
* @param array<array{
* id:string,
* label:string,
* value?:string
* }> $options
*
* @throws CrmException
*
* @return FieldData[]
*
*/
public function importPicklistValues(
Field $field,
array $options = [['id' => '', 'label' => '', 'value' => '']],
): array {
if (! empty($options[0]['id']) || ! empty($options[0]['value'])) {
// We already have the options, no need to fetch them again
return $this->importOptions($field, $options);
}
$options = [];
switch ($field->getObjectType()) {
case Field::OBJECT_ACCOUNT:
$options = $this->getClient()->fetchPropertyOptions('company', $field->getCrmProviderId());
break;
case Field::OBJECT_CONTACT:
$options = $this->getClient()->fetchPropertyOptions('contact', $field->getCrmProviderId());
break;
case Field::OBJECT_OPPORTUNITY:
// Hubspot has different endpoint for stages
$options = $this->getClient()->fetchOpportunityFieldOptions($field);
break;
case Field::OBJECT_TASK:
if ($field->getCrmProviderId() === 'disposition') {
$options = $this->getClient()->fetchDispositionFieldOptions();
} elseif (in_array($field->getCrmProviderId(), ['meetingOutcome', 'activityType'])) {
$options = $this->getClient()->fetchMeetingOutcomeFieldOptions($field);
}
break;
default:
$this->logger->warning('Invalid object type', [
'object_type' => $field->getObjectType(),
'field_id' => $field->getId(),
]);
throw new CrmException('Invalid object type');
}
return $this->importOptions($field, $options);
}
/**
* Gets business processes.
*/
public function importBusinessProcesses(): void
{
// Taken care of in importStages().
}
/**
* Gets business process stages.
*/
public function importBusinessProcessStages(BusinessProcess $businessProcess): void
{
// Taken care of in importStages().
}
/**
* Gets record types.
*/
public function importRecordTypes(): void
{
// Taken care of in importStages().
}
/**
* @inheritdoc
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$missingStage = null;
try {
// Use the HubSpot API client instead of the SDK crmPipelines() method
$endpoint = self::getDealsPipelinesEndpoint();
$pipelinesResponse = $this->client->getInstance()->getClient()->request('GET', $endpoint);
$pipelines = $pipelinesResponse->data->results;
} catch (RequestException|BadRequest $exception) {
throw $exception;
}
foreach ($pipelines as $pipeline) {
$stages = [];
// We create a business process to contain the pipeline, and store all stages against it.
$p = ResponseNormalize::normalizePipeline($pipeline);
// Create/update business process for this pipeline
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => $p['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($p['label'], 0, 150),
'type' => BusinessProcess::TYPE_OPPORTUNITY,
'is_selectable' => $p['active'],
]);
// A record type is really a clone of the business process, used to store which record uses which pipeline.
// Create/update record type clone
$this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => $p['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($p['label'], 0, 150),
'is_selectable' => $p['active'],
'business_process_id' => $businessProcess->id ?? null,
]);
// Stages
foreach ($p['stages'] as $dealStage) {
$s = ResponseNormalize::normalizeDealStage($dealStage);
// Upsert all stages for the team.
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $s['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($s['label'], 0, 50),
'label' => mb_strimwidth($s['label'], 0, 191),
'type' => Stage::TYPE_OPPORTUNITY,
'sequence' => $s['displayOrder'],
'is_selectable' => $s['active'],
'probability' => $s['probability'] * 100,
]);
if ($missingStageName && $missingStageName === $s['id']) {
$missingStage = $stage;
}
$stages[] = $stage->id;
}
$businessProcess->stages()->sync($stages);
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncOrganization(): void
{
try {
$endpoint = '[URL_WITH_CREDENTIALS]
*/
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
/** @var array<int, array<string, mixed>> */
return Cache::remember(
key: $this->team->getId() . $name . $count . $offset,
ttl: 300,
callback: function () use ($name, $offset, $count): array {
$data = [];
// Use the new V3 API to find contacts based on additional fields.
foreach (['companies', 'contacts'] as $objectType) {
$endpoint = '[URL_WITH_CREDENTIALS]
*/
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
if ($crmAccountId === null) {
return $data;
}
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
$closedStages = $this->getClosedDealStages();
$payload = $this->payloadBuilder->generateOpportunitiesSearchPayload(
$this->config,
$crmAccountId,
$closedStages,
);
$results = $this->client->getPaginatedData($payload, 'deals');
foreach ($results['results'] as $object) {
$properties = $object['properties'];
$amount = null;
if (empty($properties['amount']) === false) {
$currency = $properties['deal_currency_code'] ?? $this->config->default_currency;
// Values can contain commas and any junk so strip them.
$value = (float) preg_replace('/[^\d.]/', '', $properties['amount']);
$amount = formatCurrency($value, $currency);
}
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', $properties['pipeline'])
->first();
if ($businessProcess === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $properties['dealstage']);
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', $properties['pipeline'])
->first();
} else {
$stage = $businessProcess
->stages()
->where('crm_provider_id', $properties['dealstage'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages(null, $properties['dealstage']);
}
}
$recordType = null;
if ($businessProcess) {
$recordType = $businessProcess->recordTypes()->first();
}
$isWon = in_array($properties['dealstage'], $closedStages['won']);
$isLost = in_array($properties['dealstage'], $closedStages['lost']);
$record = [
'crmId' => $object['id'],
'name' => $properties['dealname'] ?? 'Unknown Deal',
'value' => $amount,
'won' => $isWon,
'closed' => $isWon || $isLost,
'stage' => [
'id' => $stage?->getUuid() ?? '',
'name' => $stage?->getName() ?? '',
],
];
if ($recordType) {
$record += [
'recordType' => [
'id' => $recordType->id_string,
'name' => $recordType->name,
],
];
}
if ($ownerId && isset($properties['hubspot_owner_id']) && $properties['hubspot_owner_id'] === $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
/**
* @inheritdoc
*/
public function getTasks(?string $objectType, string $objectId, ?string $opportunityId): array
{
$data = [];
switch ($objectType) {
case 'contact':
$hsObject = 'contact';
break;
case 'account':
$hsObject = 'company';
break;
default:
// This is a hack to prioritise and override a contact/company with a deal.
if ($opportunityId) {
$hsObject = 'deal';
$objectId = $opportunityId;
} else {
throw new InvalidArgumentException('Object type not supported.');
}
}
$engagementTypes = ['meetings', 'tasks'];
foreach ($engagementTypes as $engagementType) {
$payload = $this->payloadBuilder->getLinkToTaskPayload($hsObject, $objectId, $engagementType);
$this->logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
$engagements = $this->client->getPaginatedData($payload, $engagementType);
foreach ($engagements['results'] as $engagement) {
if ($engagementType == 'meetings') {
$title = $engagement['properties']['hs_meeting_title'] ?? 'Scheduled meeting';
} elseif ($engagementType == 'tasks') {
$title = $engagement['properties']['hs_task_subject'];
} else {
$title = 'Scheduled meeting';
}
$data[] = [
'crmId' => $engagement['id'],
'subject' => $title,
'due' => $engagement['properties']['hs_timestamp'],
'type' => $engagement['properties']['hs_activity_type'] ?? null,
];
}
}
usort($data, function ($item1, $item2) {
return $item2['due'] <=> $item1['due'];
});
return $data;
}
/**
* @inheritdoc
*/
public function getEvents(string $objectType, string $objectId, ?string $opportunityId): array
{
return [];
}
/**
* Try to find CRM Objects using email address
*
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
* }
*/
public function matchExactlyByEmail(string $email, ?int $userId = null): ?array
{
$contactProperties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
$contact = null;
$account = null;
try {
$hsContact = $this->getClient()->getContactByEmail($email, $contactProperties);
if ($hsContact) {
$contact = $this->importContact($hsContact);
$account = $contact->account;
}
$data = $this->convertCrmData($contact, $account, $userId);
return ! empty(array_filter($data)) ? $data : null;
} catch (BadRequest $e) {
$this->logger->warning('[HubSpot] Search failed', [
'team_id' => $this->team->getId(),
'search_identifier' => $email,
'reason' => $e->getMessage(),
]);
}
return null;
}
public function getDomain(string $email): ?string
{
return $this->getDomainFromEmail($email);
}
/**
* Try to find CRM objects using domain name of the email address
*
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
* }
*/
public function matchByDomain(string $domain, ?int $userId = null): ?array
{
$companyName = $domain;
// Try to find a company matching their email domain.
$companyProperties = [
'country',
'phone',
'name',
'hs_avatar_filemanager_key',
'industry',
'hubspot_owner_id',
'domain',
];
try {
$hsAccounts = $this->client
->getInstance()
->companies()
->searchByDomain($companyName, $companyProperties);
} catch (Throwable $e) {
$this->logger->info('[HubSpot] Search failed', [
'error' => $e->getMessage(),
'domain' => $domain,
]);
return null;
}
$account = null;
// If there are multiple accounts, don't guess, we'll ask later.
if (\count($hsAccounts->data->results) === 1) {
// Persist this remote object.
$account = $this->syncAccount($hsAccounts->data->results[0]->companyId);
}
$data = $this->convertCrmData(null, $account, $userId);
return ! empty(array_filter($data)) ? $data : null;
}
/**
* @return array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
* }
*/
protected function convertCrmData(?Contact $contact, ?Account $account, ?int $userId = null): array
{
$countryCode = null;
if ($contact && $contact->country_code) {
$countryCode = $contact->country_code;
} elseif ($account && $account->country_code) {
$countryCode = $account->country_code;
}
try {
$hsOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact ? $contact->crm_provider_id : null,
$userId
);
} catch (Exception $e) {
$hsOpportunities = [];
}
// If there are multiple opportunities, don't guess, we'll ask later.
$opportunity = null;
$stage = null;
if (! empty($hsOpportunities)) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($hsOpportunities[0]['crmId']);
$stage = $opportunity?->getStage();
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
protected function getCacheKey(string $object, ?int $userId = null): ?string
{
$key = $this->team->getId() . $object;
$keySuffix = $this->getOwnerKeySuffix($userId);
return $key . $keySuffix;
}
private function getOwnerKeySuffix(?int $userId = null): string
{
return $userId === null ? '' : (string) $userId;
}
/**
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array
{
if (str_contains($phone, '**')) {
return null;
}
// trim all whitespaces if present so the lookup doesn't fail
$phone = str_replace(' ', '', $phone);
// Check if the user is internal.
if ($this->isPhoneNumberOfTeamMember($phone)) {
return null;
}
$response = $this->searchForPhoneNumber($phone);
if (empty($response)) {
return null;
}
// This would ideally importContact instead but the response type differs.
$contact = $this->findAndSyncContact($response['results'][0]['id']);
if (! $contact instanceof Contact) {
return null;
}
$account = $contact->account;
$countryCode = $contact->country_code ?? $account->country_code ?? null;
try {
$hsOpportunities = $this->findOpportunities(
$account?->crm_provider_id,
$contact->crm_provider_id,
$userId
);
} catch (Exception $e) {
$hsOpportunities = [];
}
$opportunity = null;
$stage = null;
try {
if (! empty($hsOpportunities)) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($hsOpportunities[0]['crmId']);
$stage = $opportunity?->getStage();
}
} catch (Exception $e) {
$this->logger->debug('[HubSpot] Opportunity failed to sync.', [
'reason' => $e->getMessage(),
]);
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
private function isPhoneNumberOfTeamMember(string $phone): bool
{
$teamRepository = app(TeamRepository::class);
$user = $teamRepository->findTeamMemberByPhone($this->team, $phone);
if ($user instanceof User) {
return true;
}
return false;
}
private function findAndSyncContact(string $crmId): ?Contact
{
try {
return $this->syncContact($crmId);
} catch (Exception $exception) {
$this->logger->info('[HubSpot] Phone match failed', [
'reason' => $exception->getMessage(),
]);
return null;
}
}
private function hasResults(array $response): bool
{
return isset($response['total']) && is_numeric($response['total']) && $response['total'] > 0;
}
private function searchForPhoneNumber(string $phone): array
{
// Normalizes the provided phone number for the API search.
$normalizedPhone = $this->normalizePhoneNumber($phone);
$payload = $this->payloadBuilder->generatePhoneSearchPayload($normalizedPhone);
$this->logger->info('[HubSpot] Phone match search triggered', [
'phone' => $phone,
'normalizedPhone' => $normalizedPhone,
'payload' => $payload,
]);
$response = $this->handlePhoneSearchRequest($normalizedPhone, $payload);
if (! $this->hasResults($response)) {
$nationalPhone = preg_replace('/\D/', '', phone_national(null, $phone));
$payload = $this->payloadBuilder->generatePhoneSearchPayload($nationalPhone);
$this->logger->info('[HubSpot] Phone match national number search triggered', [
'phone' => $phone,
'nationalPhone' => $nationalPhone,
'payload' => $payload,
]);
$response = $this->handlePhoneSearchRequest($phone, $payload);
}
if (! $this->hasResults($response)) {
$payload = $this->payloadBuilder->generatePhoneSearchPayload($normalizedPhone, true);
$this->logger->info('[HubSpot] Phone match alternative search triggered', [
'phone' => $phone,
'normalizedPhone' => $normalizedPhone,
'payload' => $payload,
]);
$response = $this->handlePhoneSearchRequest($phone, $payload);
}
return $this->hasResults($response) ? $response : [];
}
private function handlePhoneSearchRequest(string $phone, array $payload): array
{
$endpoint = '[URL_WITH_CREDENTIALS] null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
* }
*/
public function matchByName(string $name, ?int $userId = null): ?array
{
// Don't waste time searching for single character strings.
if (\strlen($name) <= 1) {
return null;
}
$cacheKey = $this->getCacheKey($name, $userId);
$result = Cache::remember($cacheKey, 60, function () use ($name, $userId) {
$payload = $this->payloadBuilder->generateSearchContactsByNamePayload(
$name,
$this->getContactFields()
);
$hsContacts = $this->client->getPaginatedData($payload, 'contact');
if (empty($hsContacts['results'])) {
return false;
}
$contact = $this->importContact($hsContacts['results'][0]);
if ($contact === null) {
return false;
}
$account = $contact->account;
$countryCode = $contact->country_code ?? $account->country_code ?? null;
try {
$hsOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId
);
} catch (Exception $e) {
$hsOpportunities = [];
}
$opportunity = null;
$stage = null;
if (! empty($hsOpportunities)) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($hsOpportunities[0]['crmId']);
$stage = $opportunity?->getStage();
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
});
return is_array($result) ? $result : null;
}
private function convertActivityAssociations(Activity $activity): array
{
return [
'contactIds' => $this->getParticipantsIds($activity),
'companyIds' => $activity->hasAccount() ? [$activity->account->crm_provider_id] : [],
'dealIds' => $activity->hasOpportunity() ? [$activity->opportunity->crm_provider_id] : [],
'ownerIds' => [],
];
}
private function getParticipantsIds(Activity $activity): array
{
$attendees = [];
$participantRepository = app(ParticipantRepository::class);
$participants = $participantRepository->getParticipantsWhoEnteredMeeting($activity);
foreach ($participants as $participant) {
if ($participant->user_id || $participant->isCoach()) {
continue;
}
$contact = $participant->contact()->first();
if ($contact && $contact->crm_provider_id) {
$attendees[] = $contact->crm_provider_id;
} else {
if (! empty($participant->name)) {
$attendeeData = $this->fetchMissingAttendeeInfo($participant);
}
if (! empty($attendeeData['id'])) {
$attendees[] = $attendeeData['id'];
}
}
}
if ($activity->hasContact()) {
$attendees[] = $activity->contact->crm_provider_id;
}
return array_unique($attendees);
}
private function fetchMissingAttendeeInfo(Participant $participant): array
{
// Check if we need to look inside an account context.
$activity = $participant->getActivity();
$companyId = $activity->hasAccount() ? $activity->getAccount()->crm_provider_id : null;
// First check the local data.
/** @var Contact[] $contacts */
$contacts = $this->team->contacts()
->with('account')
->where('name', $participant->name)
->whereNotNull('email')
->get();
foreach ($contacts as $contact) {
// If we have a company in scope, check the contact is associated to it.
if (
$companyId !== null
&& ($contact->account_id === null || $companyId !== $contact->account->crm_provider_id)
) {
continue;
}
return [
'id' => $contact->crm_provider_id,
'email' => $contact->email,
];
}
$payload = $this->generateNameSearchPayload($participant->name, 0, 20);
try {
$response = $this->client->getNewInstance()->crm()->contacts()->searchApi()->doSearch($payload);
// TODO add some logic to choose the most suitable contact if multiple
foreach ($response['results'] as $object) {
$properties = $object['properties'];
if (empty($object['properties']) === false) {
// Check the company matches the contact.
// Todo: Move this check inside the API search.
if ($companyId !== null && $companyId !== $properties['associatedcompanyid']) {
continue;
}
return [
'id' => $object['id'],
'email' => $properties['email'],
];
}
}
} catch (Exception $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Search failed', [
'teamId' => $this->team->id_string,
'request' => $payload,
'reason' => $e->getMessage(),
]);
}
return [];
}
/**
* Store transcripts as note engagement.
*
* @throws Exception
*/
public function createTranscriptNotes(Activity $activity): void
{
// For HS no need to check if Crm profile - Log Notes field is enabled
// We only check if store_transcript toggle is enabled on crm profile.
$engagement = [
'active' => true,
'ownerId' => $this->profile->crm_provider_id,
'timestamp' => $activity->created_at->tz($activity->user->timezone)->getTimestamp() * 1000,
'type' => 'NOTE',
];
// Generate activity transcription.
$transcriptionData = $this->generateTranscription($activity);
// Truncate Notes with max notes length because transcription text could be very long.
$transcripts = mb_strimwidth($transcriptionData, 0, static::ENGAGEMENT_BODY_MAX_LENGTH);
$metadata = [
'body' => $transcripts,
];
$associations = $this->convertActivityAssociations($activity);
try {
$hsEngagement = $this->client
->getInstance()
->engagements()
->create($engagement, $associations, $metadata);
$this->logCrmEngagementManipulation(self::ACTION_CREATE, $engagement, $metadata, $associations);
$noteId = $hsEngagement->data->engagement->id;
// Store crm logged id in transcription.
$transcription = $activity->getTranscription();
$transcription->crm_activity_id = $noteId;
$transcription->save();
} catch (Exception $e) {
Sentry::captureException($e);
}
}
/*
* @inheritdoc
*/
public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void
{
$payload = [
'properties' => $data,
];
try {
switch ($objectType) {
case FieldData::OBJECT_OPPORTUNITY:
$this->client->getNewInstance()->crm()->deals()->basicApi()->update($objectId, $payload);
break;
case FieldData::OBJECT_CONTACT:
$this->client->getNewInstance()->crm()->contacts()->basicApi()->update($objectId, $payload);
break;
case FieldData::OBJECT_ACCOUNT:
$this->client->getNewInstance()->crm()->companies()->basicApi()->update($objectId, $payload);
break;
case FieldData::OBJECT_TASK:
// Endpoint for Engagements not ready
$engagements = [
'type' => 'TASK',
];
$metadata = $data;
$this->client->getInstance()->engagements()->update($objectId, $engagements, $metadata);
$this->logCrmEngagementManipulation(
self::ACTION_UPDATE,
['crmId' => $objectId],
$metadata,
);
break;
default:
throw new UnexpectedValueException('Unsupported object type "' . $objectType . '"');
}
} catch (\HubSpot\Client\Crm\Deals\ApiException $apiException) {
$errorMessage = $apiException->getMessage();
if ($apiException->getResponseBody()) {
$responseBody = json_decode($apiException->getResponseBody(), true, 512, JSON_THROW_ON_ERROR);
$errorMessage = $responseBody['message'] ?? $apiException->getMessage();
}
$this->logger->error(
'[HubSpot] Update record failed',
[
'objectType' => $objectT...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#11894 on JY-18909-automated-reports-ask-jiminny, menu","depth":5,"help_text":"Pull request #11894 exists for current branch JY-18909-automated-reports-ask-jiminny, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AutomatedReportsCommandTest","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AutomatedReportsCommandTest'","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AutomatedReportsCommandTest'","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"More Actions","depth":6,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"JetBrains AI","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Search Everywhere","depth":5,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"IDE and Project Settings","depth":5,"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},"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},"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},"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},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"8","depth":4,"role_description":"text"},{"role":"AXStaticText","text":"42","depth":4,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"role_description":"text"},{"role":"AXStaticText","text":"33","depth":4,"role_description":"text"},{"role":"AXStaticText","text":"1","depth":4,"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Highlighted Error","depth":4,"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Generator;\nuse GuzzleHttp\\Exception\\RequestException;\nuse Illuminate\\Support\\Facades\\Cache;\nuse InvalidArgumentException;\nuse Jiminny\\Contracts\\Repositories\\TeamRepository;\nuse Jiminny\\Contracts\\Services\\Crm\\ClientInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\HubspotInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SavePlaybackLinkToCrmInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SendSummaryToCrmInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Jobs\\Crm\\NoteObject;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Contracts\\ActivityContract;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\Layout;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Participant;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\ParticipantRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\Hubspot\\Actions\\SyncArchivedProfilesAction;\nuse Jiminny\\Services\\Crm\\Hubspot\\Fields\\ValueNormalizer;\nuse Jiminny\\Services\\Crm\\Hubspot\\ServiceTraits\\OpportunitySyncTrait;\nuse Jiminny\\Services\\Crm\\Hubspot\\ServiceTraits\\SyncCrmEntitiesTrait;\nuse Jiminny\\Services\\Crm\\Hubspot\\ServiceTraits\\SyncFieldsTrait;\nuse Jiminny\\Services\\Crm\\Hubspot\\ServiceTraits\\WriteCrmTrait;\nuse Jiminny\\Services\\Crm\\MatchDomainByEmailInterface;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Services\\Crm\\ResolveCompanyNameByEmailTrait;\nuse Jiminny\\Utils\\PlaybackUrlBuilder;\nuse Sentry;\nuse SevenShores\\Hubspot\\Exceptions\\BadRequest;\nuse Throwable;\nuse UnexpectedValueException;\n\n/**\n * @phpstan-type CrmFieldDefinition array{\n * name: string,\n * label: string,\n * description: string,\n * type: string,\n * fieldType: string,\n * hidden: bool,\n * showCurrencySymbol: bool,\n * options: array<array{\n * id: string,\n * label: string,\n * value?: string,\n * }\n */\nclass Service extends BaseService implements\n HubspotInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n SendSummaryToCrmInterface,\n MatchDomainByEmailInterface,\n SavePlaybackLinkToCrmInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n use ResolveCompanyNameByEmailTrait;\n use SyncCrmEntitiesTrait;\n use WriteCrmTrait;\n use SyncFieldsTrait;\n use OpportunitySyncTrait;\n\n private const int ENGAGEMENT_BODY_MAX_LENGTH = 65536;\n\n private const string LOG_DATE_FORMAT = 'Y-m-d H:i:s';\n private const int BATCH_UPDATE_LIMIT = 100;\n private const string TEN_SECONDLY_ROLLING_POLICY = 'TEN_SECONDLY_ROLLING';\n private const int TEN_SECONDLY_ROLLING_LIMIT = 10;\n private const string CALLS_SEARCH_ENDPOINT = 'https://api.hubapi.com/crm/v3/objects/calls/search';\n\n private const string TYPE_NOTE = 'NOTE';\n\n private const string TYPE_MEETING = 'MEETING';\n\n private const string TYPE_CALL = 'CALL';\n\n private const string API_URL = 'https://api.hubapi.com';\n\n // NB: v1 is legacy - v3 is the newest\n private const string ENDPOINT_PIPELINES = '/crm-pipelines/v1/pipelines/';\n private const string PIPELINE_OBJECT_TYPE_DEALS = 'deals';\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n /**\n * @var ClientInterface|Client\n */\n protected $client;\n protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n protected CrmEntityRepository $crmEntityRepository;\n protected ProspectPhotoPathService $prospectPhotoPathService;\n\n private SyncFieldAction $syncFieldAction;\n private PayloadBuilder $payloadBuilder;\n private SyncRelatedActivityManager $syncRelatedActivityManager;\n private SyncArchivedProfilesAction $syncArchivedProfilesAction;\n private WebhookSyncBatchProcessor $batchProcessor;\n\n public function __construct(\n Client $client,\n SyncFieldAction $syncFieldAction,\n PayloadBuilder $payloadBuilder,\n ProspectPhotoPathService $prospectPhotoPathService,\n SyncArchivedProfilesAction $syncArchivedProfilesAction,\n WebhookSyncBatchProcessor $batchProcessor,\n ) {\n parent::__construct();\n\n $this->client = $client;\n $this->syncFieldAction = $syncFieldAction;\n $this->prospectPhotoPathService = $prospectPhotoPathService;\n $this->payloadBuilder = $payloadBuilder;\n $this->syncArchivedProfilesAction = $syncArchivedProfilesAction;\n $this->batchProcessor = $batchProcessor;\n $this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $this->syncRelatedActivityManager = app(SyncRelatedActivityManager::class, [\n 'client' => $this->client,\n 'payloadBuilder' => $this->payloadBuilder,\n 'logger' => $this->logger,\n ]);\n $this->crmEntityRepository = app(CrmEntityRepository::class);\n $this->dealFieldsService = app(DealFieldsService::class);\n }\n\n public function getDisplayName(): string\n {\n return 'HubSpot';\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_HUBSPOT);\n }\n\n public function getClient(): Client\n {\n /** @var Client */\n return $this->client;\n }\n\n /**\n * Convert raw field data into a format compatible with CRM APIs.\n *\n * @param bool $internal Direction of the conversion.\n * True is pulling from CRM, false normalize before sending to CRM.\n */\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return ValueNormalizer::normalize(\n fieldType: $fieldType,\n fieldValue: $fieldValue,\n isInbound: $internal,\n );\n }\n\n public function getRecordTypes(string $crmObject): array\n {\n return [];\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {\n $defaultFields = FieldDefinitions::defaultTaskFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'activityType',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityLayoutFields(string $activityType, string $layoutType): array\n {\n $fields = [];\n\n if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {\n // Outcome should always be provided calls/meetings.\n $fieldData = [\n [\n 'crm_provider_id' => $layoutType === Layout::TYPE_SOFTPHONE_SUMMARY ? 'disposition' : 'meetingOutcome',\n 'object_type' => Field::OBJECT_TASK,\n ],\n ];\n\n foreach ($fieldData as $data) {\n $field = $this->config->fields()->where($data)->first();\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n }\n\n return $fields;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n $fieldData = FieldDefinitions::followupFieldsFilter();\n\n foreach ($fieldData as $data) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function syncField(Field $field): void\n {\n switch ($field->object_type) {\n case Field::OBJECT_ACCOUNT:\n $crmField = $this->client->getInstance()->companyProperties()->get($field->crm_provider_id);\n\n break;\n case Field::OBJECT_CONTACT:\n $crmField = $this->client->getInstance()->contactProperties()->get($field->crm_provider_id);\n\n break;\n case Field::OBJECT_OPPORTUNITY:\n $crmField = $this->client->getInstance()->dealProperties()->get($field->crm_provider_id);\n\n break;\n case Field::OBJECT_TASK:\n $this->syncSingleTaskField($field);\n\n return;\n default:\n return;\n }\n\n $this->syncFieldAction->execute($field, $crmField->toArray());\n }\n\n /**\n * @param array<array{\n * id:string,\n * label:string,\n * value?:string\n * }> $options\n *\n * @throws CrmException\n *\n * @return FieldData[]\n *\n */\n public function importPicklistValues(\n Field $field,\n array $options = [['id' => '', 'label' => '', 'value' => '']],\n ): array {\n if (! empty($options[0]['id']) || ! empty($options[0]['value'])) {\n // We already have the options, no need to fetch them again\n return $this->importOptions($field, $options);\n }\n\n $options = [];\n\n switch ($field->getObjectType()) {\n case Field::OBJECT_ACCOUNT:\n $options = $this->getClient()->fetchPropertyOptions('company', $field->getCrmProviderId());\n\n break;\n\n case Field::OBJECT_CONTACT:\n $options = $this->getClient()->fetchPropertyOptions('contact', $field->getCrmProviderId());\n\n break;\n\n case Field::OBJECT_OPPORTUNITY:\n // Hubspot has different endpoint for stages\n $options = $this->getClient()->fetchOpportunityFieldOptions($field);\n\n break;\n\n case Field::OBJECT_TASK:\n if ($field->getCrmProviderId() === 'disposition') {\n $options = $this->getClient()->fetchDispositionFieldOptions();\n } elseif (in_array($field->getCrmProviderId(), ['meetingOutcome', 'activityType'])) {\n $options = $this->getClient()->fetchMeetingOutcomeFieldOptions($field);\n }\n\n break;\n\n default:\n $this->logger->warning('Invalid object type', [\n 'object_type' => $field->getObjectType(),\n 'field_id' => $field->getId(),\n ]);\n\n throw new CrmException('Invalid object type');\n }\n\n return $this->importOptions($field, $options);\n }\n\n /**\n * Gets business processes.\n */\n public function importBusinessProcesses(): void\n {\n // Taken care of in importStages().\n }\n\n /**\n * Gets business process stages.\n */\n public function importBusinessProcessStages(BusinessProcess $businessProcess): void\n {\n // Taken care of in importStages().\n }\n\n /**\n * Gets record types.\n */\n public function importRecordTypes(): void\n {\n // Taken care of in importStages().\n }\n\n /**\n * @inheritdoc\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $missingStage = null;\n\n try {\n // Use the HubSpot API client instead of the SDK crmPipelines() method\n $endpoint = self::getDealsPipelinesEndpoint();\n $pipelinesResponse = $this->client->getInstance()->getClient()->request('GET', $endpoint);\n $pipelines = $pipelinesResponse->data->results;\n } catch (RequestException|BadRequest $exception) {\n throw $exception;\n }\n\n foreach ($pipelines as $pipeline) {\n $stages = [];\n\n // We create a business process to contain the pipeline, and store all stages against it.\n $p = ResponseNormalize::normalizePipeline($pipeline);\n\n // Create/update business process for this pipeline\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $p['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($p['label'], 0, 150),\n 'type' => BusinessProcess::TYPE_OPPORTUNITY,\n 'is_selectable' => $p['active'],\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n // Create/update record type clone\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $p['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($p['label'], 0, 150),\n 'is_selectable' => $p['active'],\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n // Stages\n foreach ($p['stages'] as $dealStage) {\n $s = ResponseNormalize::normalizeDealStage($dealStage);\n\n // Upsert all stages for the team.\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $s['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($s['label'], 0, 50),\n 'label' => mb_strimwidth($s['label'], 0, 191),\n 'type' => Stage::TYPE_OPPORTUNITY,\n 'sequence' => $s['displayOrder'],\n 'is_selectable' => $s['active'],\n 'probability' => $s['probability'] * 100,\n ]);\n\n if ($missingStageName && $missingStageName === $s['id']) {\n $missingStage = $stage;\n }\n\n $stages[] = $stage->id;\n }\n\n $businessProcess->stages()->sync($stages);\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n try {\n $endpoint = 'https://api.hubapi.com/integrations/v1/me';\n $response = $this->client->getInstance()->getClient()->request('get', $endpoint);\n\n $accountData = $response->data;\n $this->config->update(['default_currency' => $accountData->currency]);\n } catch (BadRequest $e) {\n throw new CrmException('Could not sync the organization.', $e->getCode(), $e);\n }\n }\n\n /**\n * @inheritdoc\n *\n * @throws CrmException\n */\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $this->syncArchivedProfilesAction->execute($this->team, $this->client, $this->config);\n\n try {\n $owners = $this->client->getOwners();\n } catch (\\HubSpot\\Client\\Crm\\Owners\\ApiException $e) {\n $this->logger->error('[HubSpot] Could not sync the profiles.', [\n 'team_id' => $this->team->getId(),\n 'reason' => $e->getMessage(),\n ]);\n\n throw new CrmException('Could not sync the profiles.', $e->getCode(), $e);\n }\n\n $profileRepository = app(ProfileRepository::class);\n $teamRepository = app(TeamRepository::class);\n\n foreach ($owners as $owner) {\n if ($owner->getArchived()) {\n // not supposed to fetch archived, but log anyway\n $this->logger->warning('[HubSpot] Found archived owner', [\n 'crm_provider_id' => $owner->getId(),\n 'email' => $owner->getEmail(),\n ]);\n\n continue;\n }\n\n $email = $owner->getEmail();\n if ($email === null) {\n continue;\n }\n\n $user = $teamRepository->findActiveTeamMemberByEmail($this->team, $email);\n\n if (! $user instanceof User) {\n continue;\n }\n\n $profile = $profileRepository->updateOrCreateProfile($user, [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $owner->getId(),\n ]);\n\n if ($userToSearch && $userToSearch->getId() === $user->getId()) {\n return $profile;\n }\n }\n\n return null;\n }\n\n private function generateNameSearchPayload(string $name, int $offset, int $limit): array\n {\n $payload = [\n 'query' => $name,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\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 'industry',\n 'name',\n 'company',\n ],\n 'limit' => $limit,\n 'after' => $offset,\n ];\n\n $this->logger->debug('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n /** @var array<int, array<string, mixed>> */\n return Cache::remember(\n key: $this->team->getId() . $name . $count . $offset,\n ttl: 300,\n callback: function () use ($name, $offset, $count): array {\n $data = [];\n\n // Use the new V3 API to find contacts based on additional fields.\n foreach (['companies', 'contacts'] as $objectType) {\n $endpoint = 'https://api.hubapi.com/crm/v3/objects/' . $objectType . '/search';\n $payload = $this->generateNameSearchPayload($name, $offset, $count);\n $type = $objectType === 'companies' ? 'account' : 'contact';\n\n try {\n $response = $this->client->getInstance()->getClient()->request('POST', $endpoint, [\n 'json' => $payload,\n ]);\n\n // Build mapped list.\n foreach ($response['results'] as $object) {\n $properties = $object['properties'];\n\n $objectName = $this->buildContactName($properties);\n\n $record = [\n 'crmId' => $object['id'],\n // Pass crmUrl to the FE, needed for success message in the extension when you log activity.\n 'crmUrl' => $this->generateProviderUrl($object['id'], $type),\n 'name' => $objectName,\n 'prospectType' => $type,\n 'phoneNumbers' => [],\n ];\n\n if ($type === 'account') {\n $record['industry'] = $properties['industry'] ?? null;\n } else {\n $record['title'] = $properties['jobtitle'] ?? null;\n $record['organization'] = $properties['company'] ?? null;\n }\n\n $countryCode = $this->buildContactCountry($properties);\n $parsedNumber = $this->buildContactPhone($countryCode, $properties);\n\n // Add phone number to record.\n if (! empty($parsedNumber['phone'])) {\n $record['phoneNumbers'][] = [\n 'number' => $parsedNumber['phone'],\n 'nationalFormat' => phone_national($countryCode, $parsedNumber['phone']),\n 'type' => 'phone',\n ];\n }\n\n // Add mobile phone number to record.\n if (! empty($properties['mobilephone'])) {\n $mobileNumber = phone_e164($countryCode, $properties['mobilephone']);\n if ($mobileNumber !== null) {\n $record['phoneNumbers'][] = [\n 'number' => $mobileNumber,\n 'nationalFormat' => phone_national($countryCode, $mobileNumber),\n 'type' => 'mobile',\n ];\n }\n }\n\n $data[] = $record;\n }\n } catch (BadRequest $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Search failed', [\n 'teamId' => $this->team->getUuid(),\n 'request' => $payload,\n 'reason' => $e->getMessage(),\n ]);\n\n throw $e;\n }\n }\n\n return $data;\n },\n );\n }\n\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n\n if ($crmAccountId === null) {\n return $data;\n }\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n $closedStages = $this->getClosedDealStages();\n $payload = $this->payloadBuilder->generateOpportunitiesSearchPayload(\n $this->config,\n $crmAccountId,\n $closedStages,\n );\n\n $results = $this->client->getPaginatedData($payload, 'deals');\n\n foreach ($results['results'] as $object) {\n $properties = $object['properties'];\n\n $amount = null;\n if (empty($properties['amount']) === false) {\n $currency = $properties['deal_currency_code'] ?? $this->config->default_currency;\n\n // Values can contain commas and any junk so strip them.\n $value = (float) preg_replace('/[^\\d.]/', '', $properties['amount']);\n $amount = formatCurrency($value, $currency);\n }\n\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', $properties['pipeline'])\n ->first();\n\n if ($businessProcess === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $properties['dealstage']);\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', $properties['pipeline'])\n ->first();\n } else {\n $stage = $businessProcess\n ->stages()\n ->where('crm_provider_id', $properties['dealstage'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages(null, $properties['dealstage']);\n }\n }\n\n $recordType = null;\n if ($businessProcess) {\n $recordType = $businessProcess->recordTypes()->first();\n }\n\n $isWon = in_array($properties['dealstage'], $closedStages['won']);\n $isLost = in_array($properties['dealstage'], $closedStages['lost']);\n\n $record = [\n 'crmId' => $object['id'],\n 'name' => $properties['dealname'] ?? 'Unknown Deal',\n 'value' => $amount,\n 'won' => $isWon,\n 'closed' => $isWon || $isLost,\n 'stage' => [\n 'id' => $stage?->getUuid() ?? '',\n 'name' => $stage?->getName() ?? '',\n ],\n ];\n\n if ($recordType) {\n $record += [\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n }\n\n if ($ownerId && isset($properties['hubspot_owner_id']) && $properties['hubspot_owner_id'] === $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(?string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = [];\n switch ($objectType) {\n case 'contact':\n $hsObject = 'contact';\n\n break;\n case 'account':\n $hsObject = 'company';\n\n break;\n default:\n // This is a hack to prioritise and override a contact/company with a deal.\n if ($opportunityId) {\n $hsObject = 'deal';\n $objectId = $opportunityId;\n } else {\n throw new InvalidArgumentException('Object type not supported.');\n }\n }\n\n $engagementTypes = ['meetings', 'tasks'];\n\n foreach ($engagementTypes as $engagementType) {\n $payload = $this->payloadBuilder->getLinkToTaskPayload($hsObject, $objectId, $engagementType);\n\n $this->logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n $engagements = $this->client->getPaginatedData($payload, $engagementType);\n\n foreach ($engagements['results'] as $engagement) {\n if ($engagementType == 'meetings') {\n $title = $engagement['properties']['hs_meeting_title'] ?? 'Scheduled meeting';\n } elseif ($engagementType == 'tasks') {\n $title = $engagement['properties']['hs_task_subject'];\n } else {\n $title = 'Scheduled meeting';\n }\n\n $data[] = [\n 'crmId' => $engagement['id'],\n 'subject' => $title,\n 'due' => $engagement['properties']['hs_timestamp'],\n 'type' => $engagement['properties']['hs_activity_type'] ?? null,\n ];\n }\n }\n\n usort($data, function ($item1, $item2) {\n return $item2['due'] <=> $item1['due'];\n });\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getEvents(string $objectType, string $objectId, ?string $opportunityId): array\n {\n return [];\n }\n\n /**\n * Try to find CRM Objects using email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $contactProperties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n $contact = null;\n $account = null;\n\n try {\n $hsContact = $this->getClient()->getContactByEmail($email, $contactProperties);\n\n if ($hsContact) {\n $contact = $this->importContact($hsContact);\n $account = $contact->account;\n }\n\n $data = $this->convertCrmData($contact, $account, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n } catch (BadRequest $e) {\n $this->logger->warning('[HubSpot] Search failed', [\n 'team_id' => $this->team->getId(),\n 'search_identifier' => $email,\n 'reason' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n public function getDomain(string $email): ?string\n {\n return $this->getDomainFromEmail($email);\n }\n\n /**\n * Try to find CRM objects using domain name of the email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByDomain(string $domain, ?int $userId = null): ?array\n {\n $companyName = $domain;\n\n // Try to find a company matching their email domain.\n $companyProperties = [\n 'country',\n 'phone',\n 'name',\n 'hs_avatar_filemanager_key',\n 'industry',\n 'hubspot_owner_id',\n 'domain',\n ];\n\n try {\n $hsAccounts = $this->client\n ->getInstance()\n ->companies()\n ->searchByDomain($companyName, $companyProperties);\n } catch (Throwable $e) {\n $this->logger->info('[HubSpot] Search failed', [\n 'error' => $e->getMessage(),\n 'domain' => $domain,\n ]);\n\n return null;\n }\n\n $account = null;\n // If there are multiple accounts, don't guess, we'll ask later.\n if (\\count($hsAccounts->data->results) === 1) {\n // Persist this remote object.\n $account = $this->syncAccount($hsAccounts->data->results[0]->companyId);\n }\n\n $data = $this->convertCrmData(null, $account, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @return array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n protected function convertCrmData(?Contact $contact, ?Account $account, ?int $userId = null): array\n {\n $countryCode = null;\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account && $account->country_code) {\n $countryCode = $account->country_code;\n }\n\n try {\n $hsOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact ? $contact->crm_provider_id : null,\n $userId\n );\n } catch (Exception $e) {\n $hsOpportunities = [];\n }\n\n // If there are multiple opportunities, don't guess, we'll ask later.\n $opportunity = null;\n $stage = null;\n if (! empty($hsOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($hsOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->team->getId() . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n if (str_contains($phone, '**')) {\n return null;\n }\n\n // trim all whitespaces if present so the lookup doesn't fail\n $phone = str_replace(' ', '', $phone);\n\n // Check if the user is internal.\n if ($this->isPhoneNumberOfTeamMember($phone)) {\n return null;\n }\n\n $response = $this->searchForPhoneNumber($phone);\n if (empty($response)) {\n return null;\n }\n\n // This would ideally importContact instead but the response type differs.\n $contact = $this->findAndSyncContact($response['results'][0]['id']);\n if (! $contact instanceof Contact) {\n return null;\n }\n\n $account = $contact->account;\n $countryCode = $contact->country_code ?? $account->country_code ?? null;\n\n try {\n $hsOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact->crm_provider_id,\n $userId\n );\n } catch (Exception $e) {\n $hsOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n\n try {\n if (! empty($hsOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($hsOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n } catch (Exception $e) {\n $this->logger->debug('[HubSpot] Opportunity failed to sync.', [\n 'reason' => $e->getMessage(),\n ]);\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n private function isPhoneNumberOfTeamMember(string $phone): bool\n {\n $teamRepository = app(TeamRepository::class);\n $user = $teamRepository->findTeamMemberByPhone($this->team, $phone);\n\n if ($user instanceof User) {\n return true;\n }\n\n return false;\n }\n\n private function findAndSyncContact(string $crmId): ?Contact\n {\n try {\n return $this->syncContact($crmId);\n } catch (Exception $exception) {\n $this->logger->info('[HubSpot] Phone match failed', [\n 'reason' => $exception->getMessage(),\n ]);\n\n return null;\n }\n }\n\n private function hasResults(array $response): bool\n {\n return isset($response['total']) && is_numeric($response['total']) && $response['total'] > 0;\n }\n\n private function searchForPhoneNumber(string $phone): array\n {\n // Normalizes the provided phone number for the API search.\n $normalizedPhone = $this->normalizePhoneNumber($phone);\n $payload = $this->payloadBuilder->generatePhoneSearchPayload($normalizedPhone);\n\n $this->logger->info('[HubSpot] Phone match search triggered', [\n 'phone' => $phone,\n 'normalizedPhone' => $normalizedPhone,\n 'payload' => $payload,\n ]);\n\n $response = $this->handlePhoneSearchRequest($normalizedPhone, $payload);\n\n if (! $this->hasResults($response)) {\n $nationalPhone = preg_replace('/\\D/', '', phone_national(null, $phone));\n $payload = $this->payloadBuilder->generatePhoneSearchPayload($nationalPhone);\n\n $this->logger->info('[HubSpot] Phone match national number search triggered', [\n 'phone' => $phone,\n 'nationalPhone' => $nationalPhone,\n 'payload' => $payload,\n ]);\n\n $response = $this->handlePhoneSearchRequest($phone, $payload);\n }\n\n if (! $this->hasResults($response)) {\n $payload = $this->payloadBuilder->generatePhoneSearchPayload($normalizedPhone, true);\n\n $this->logger->info('[HubSpot] Phone match alternative search triggered', [\n 'phone' => $phone,\n 'normalizedPhone' => $normalizedPhone,\n 'payload' => $payload,\n ]);\n\n $response = $this->handlePhoneSearchRequest($phone, $payload);\n }\n\n return $this->hasResults($response) ? $response : [];\n }\n\n private function handlePhoneSearchRequest(string $phone, array $payload): array\n {\n $endpoint = 'https://api.hubapi.com/crm/v3/objects/contacts/search';\n\n try {\n $response = $this->client->getInstance()->getClient()->request(\n 'POST',\n $endpoint,\n ['json' => ($payload)],\n );\n } catch (Exception $exception) {\n $this->logger->info('[HubSpot] Phone match failed', [\n 'phone' => $phone,\n 'reason' => $exception->getMessage(),\n ]);\n\n return [];\n }\n\n $this->logger->info('[HubSpot] Phone match completed', [\n 'phone' => $phone,\n 'response' => $response,\n ]);\n\n return $response->toArray();\n }\n\n private function normalizePhoneNumber(string $phone): string\n {\n return ltrim(phone_e164(null, $phone), '+0');\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n $payload = $this->payloadBuilder->generateSearchContactsByNamePayload(\n $name,\n $this->getContactFields()\n );\n\n $hsContacts = $this->client->getPaginatedData($payload, 'contact');\n if (empty($hsContacts['results'])) {\n return false;\n }\n\n $contact = $this->importContact($hsContacts['results'][0]);\n if ($contact === null) {\n return false;\n }\n\n $account = $contact->account;\n $countryCode = $contact->country_code ?? $account->country_code ?? null;\n\n try {\n $hsOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId\n );\n } catch (Exception $e) {\n $hsOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n if (! empty($hsOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($hsOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n });\n\n return is_array($result) ? $result : null;\n }\n\n\n private function convertActivityAssociations(Activity $activity): array\n {\n return [\n 'contactIds' => $this->getParticipantsIds($activity),\n 'companyIds' => $activity->hasAccount() ? [$activity->account->crm_provider_id] : [],\n 'dealIds' => $activity->hasOpportunity() ? [$activity->opportunity->crm_provider_id] : [],\n 'ownerIds' => [],\n ];\n }\n\n private function getParticipantsIds(Activity $activity): array\n {\n $attendees = [];\n\n $participantRepository = app(ParticipantRepository::class);\n $participants = $participantRepository->getParticipantsWhoEnteredMeeting($activity);\n foreach ($participants as $participant) {\n if ($participant->user_id || $participant->isCoach()) {\n continue;\n }\n\n $contact = $participant->contact()->first();\n if ($contact && $contact->crm_provider_id) {\n $attendees[] = $contact->crm_provider_id;\n } else {\n if (! empty($participant->name)) {\n $attendeeData = $this->fetchMissingAttendeeInfo($participant);\n }\n if (! empty($attendeeData['id'])) {\n $attendees[] = $attendeeData['id'];\n }\n }\n }\n\n if ($activity->hasContact()) {\n $attendees[] = $activity->contact->crm_provider_id;\n }\n\n return array_unique($attendees);\n }\n\n private function fetchMissingAttendeeInfo(Participant $participant): array\n {\n // Check if we need to look inside an account context.\n $activity = $participant->getActivity();\n $companyId = $activity->hasAccount() ? $activity->getAccount()->crm_provider_id : null;\n\n // First check the local data.\n /** @var Contact[] $contacts */\n $contacts = $this->team->contacts()\n ->with('account')\n ->where('name', $participant->name)\n ->whereNotNull('email')\n ->get();\n\n foreach ($contacts as $contact) {\n // If we have a company in scope, check the contact is associated to it.\n if (\n $companyId !== null\n && ($contact->account_id === null || $companyId !== $contact->account->crm_provider_id)\n ) {\n continue;\n }\n\n return [\n 'id' => $contact->crm_provider_id,\n 'email' => $contact->email,\n ];\n }\n\n $payload = $this->generateNameSearchPayload($participant->name, 0, 20);\n\n try {\n $response = $this->client->getNewInstance()->crm()->contacts()->searchApi()->doSearch($payload);\n\n // TODO add some logic to choose the most suitable contact if multiple\n foreach ($response['results'] as $object) {\n $properties = $object['properties'];\n if (empty($object['properties']) === false) {\n // Check the company matches the contact.\n // Todo: Move this check inside the API search.\n if ($companyId !== null && $companyId !== $properties['associatedcompanyid']) {\n continue;\n }\n\n return [\n 'id' => $object['id'],\n 'email' => $properties['email'],\n ];\n }\n }\n } catch (Exception $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Search failed', [\n 'teamId' => $this->team->id_string,\n 'request' => $payload,\n 'reason' => $e->getMessage(),\n ]);\n }\n\n return [];\n }\n\n /**\n * Store transcripts as note engagement.\n *\n * @throws Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // For HS no need to check if Crm profile - Log Notes field is enabled\n // We only check if store_transcript toggle is enabled on crm profile.\n $engagement = [\n 'active' => true,\n 'ownerId' => $this->profile->crm_provider_id,\n 'timestamp' => $activity->created_at->tz($activity->user->timezone)->getTimestamp() * 1000,\n 'type' => 'NOTE',\n ];\n\n // Generate activity transcription.\n $transcriptionData = $this->generateTranscription($activity);\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $transcripts = mb_strimwidth($transcriptionData, 0, static::ENGAGEMENT_BODY_MAX_LENGTH);\n\n $metadata = [\n 'body' => $transcripts,\n ];\n\n $associations = $this->convertActivityAssociations($activity);\n\n try {\n $hsEngagement = $this->client\n ->getInstance()\n ->engagements()\n ->create($engagement, $associations, $metadata);\n\n $this->logCrmEngagementManipulation(self::ACTION_CREATE, $engagement, $metadata, $associations);\n\n $noteId = $hsEngagement->data->engagement->id;\n\n // Store crm logged id in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $noteId;\n $transcription->save();\n } catch (Exception $e) {\n Sentry::captureException($e);\n }\n }\n\n /*\n * @inheritdoc\n */\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $payload = [\n 'properties' => $data,\n ];\n\n try {\n switch ($objectType) {\n case FieldData::OBJECT_OPPORTUNITY:\n $this->client->getNewInstance()->crm()->deals()->basicApi()->update($objectId, $payload);\n\n break;\n case FieldData::OBJECT_CONTACT:\n $this->client->getNewInstance()->crm()->contacts()->basicApi()->update($objectId, $payload);\n\n break;\n\n case FieldData::OBJECT_ACCOUNT:\n $this->client->getNewInstance()->crm()->companies()->basicApi()->update($objectId, $payload);\n\n break;\n\n case FieldData::OBJECT_TASK:\n // Endpoint for Engagements not ready\n $engagements = [\n 'type' => 'TASK',\n ];\n $metadata = $data;\n $this->client->getInstance()->engagements()->update($objectId, $engagements, $metadata);\n\n $this->logCrmEngagementManipulation(\n self::ACTION_UPDATE,\n ['crmId' => $objectId],\n $metadata,\n );\n\n break;\n\n default:\n throw new UnexpectedValueException('Unsupported object type \"' . $objectType . '\"');\n }\n } catch (\\HubSpot\\Client\\Crm\\Deals\\ApiException $apiException) {\n $errorMessage = $apiException->getMessage();\n if ($apiException->getResponseBody()) {\n $responseBody = json_decode($apiException->getResponseBody(), true, 512, JSON_THROW_ON_ERROR);\n $errorMessage = $responseBody['message'] ?? $apiException->getMessage();\n }\n\n $this->logger->error(\n '[HubSpot] Update record failed',\n [\n 'objectType' => $objectType,\n 'objectId' => $objectId,\n 'payload' => $payload,\n 'reason' => $errorMessage,\n 'team' => $this->team->getUuid(),\n ]\n );\n\n throw new CrmException($errorMessage);\n }\n }\n\n /*\n * @inheritdoc\n */\n public function getRecord(string $objectType, string $objectId, array $fields = []): array\n {\n switch ($objectType) {\n case FieldData::OBJECT_OPPORTUNITY:\n return $this->client->getInstance()->deals()->getById($objectId)->toArray();\n\n case FieldData::OBJECT_CONTACT:\n return $this->client->getInstance()->contacts()->getById($objectId)->toArray();\n\n case FieldData::OBJECT_ACCOUNT:\n return $this->client->getInstance()->companies()->getById($objectId)->toArray();\n\n case FieldData::OBJECT_TASK:\n return $this->client->getInstance()->engagements()->get($objectId)->toArray();\n\n default:\n throw new UnexpectedValueException('Unsupported object type \"' . $objectType . '\"');\n }\n }\n\n /**\n * @throws BadRequest\n * @throws CrmException\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n $payload = [\n 'properties' => [\n [\n 'name' => 'dealstage',\n 'value' => $stage->crm_provider_id,\n ],\n ],\n ];\n\n try {\n $this->client->getInstance()->deals()->update($crmObject->crm_provider_id, $payload);\n } catch (BadRequest $badRequest) {\n if ($badRequest->getCode() === 403) {\n throw new CrmException(\n \"Sorry, you don't have permission to update this stage.\",\n $badRequest->getCode(),\n $badRequest,\n );\n }\n\n $this->logger->warning('[HubSpot] Stage update failed', [\n 'dealId' => $crmObject->crm_provider_id,\n 'payload' => $payload,\n 'message' => $badRequest->getMessage(),\n ]);\n\n throw $badRequest;\n }\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $url = null;\n $baseUrl = 'https://app.hubspot.com/contacts/' . $this->config->crm_provider_id . '/';\n\n switch ($objectType) {\n case 'account':\n $url = $baseUrl . 'company/' . $providerId;\n\n break;\n\n case 'contact':\n $url = $baseUrl . 'contact/' . $providerId;\n\n break;\n\n case 'opportunity':\n $url = $baseUrl . 'deal/' . $providerId;\n\n break;\n\n case 'task':\n case 'activity':\n return null;\n\n // This should not be deep-linked as per JMNY-3934.\n //$url = $baseUrl.'tasks/list/view/all/?taskId='.$providerId;\n break;\n }\n\n return $url;\n }\n\n public function searchCalls(Carbon $from, Carbon $to, string $activityProvider): array\n {\n $this->logger->info('[HubSpot] Search calls', [\n 'from' => $from->format(self::LOG_DATE_FORMAT),\n 'to' => $to->format(self::LOG_DATE_FORMAT),\n ]);\n\n $calls = [];\n $page = 1;\n\n do {\n try {\n $payload = $this->payloadBuilder->generateGetCallsPayload($from, $to, $activityProvider, $page);\n $response = $this->client->getInstance()->getClient()->request(\n 'POST',\n self::CALLS_SEARCH_ENDPOINT,\n ['json' => ($payload)],\n );\n } catch (Exception $exception) {\n $this->logger->info('[HubSpot] Search calls failed', [\n 'from' => $from->format(self::LOG_DATE_FORMAT),\n 'to' => $to->format(self::LOG_DATE_FORMAT),\n 'reason' => $exception->getMessage(),\n ]);\n $response = null;\n }\n\n $responseResults = empty($response['results']) ? [] : $response['results'];\n $calls = array_merge($calls, $responseResults);\n $page++;\n } while (! empty($responseResults));\n\n return $calls;\n }\n\n public function searchCallsForPeriodByPage(Carbon $from, Carbon $to, int $page, bool $retry = true)\n {\n try {\n $payload = $this->payloadBuilder->generateSearchCallsByPeriodPayload($from, $to, $page);\n $response = $this->client->getInstance()->getClient()->request(\n 'POST',\n self::CALLS_SEARCH_ENDPOINT,\n ['json' => ($payload)],\n );\n } catch (Exception $exception) {\n $this->logger->info('[HubSpot] Search calls for period failed', [\n 'from' => $from->format(self::LOG_DATE_FORMAT),\n 'to' => $to->format(self::LOG_DATE_FORMAT),\n 'reason' => $exception->getMessage(),\n 'retry' => $retry,\n ]);\n\n if ($retry) {\n sleep(1);\n\n return $this->searchCallsForPeriodByPage($from, $to, $page, false);\n }\n $response = null;\n }\n\n return $response;\n }\n\n public function searchCallsForPeriod(Carbon $from, Carbon $to): Generator\n {\n $this->logger->info('[HubSpot] Search calls for period', [\n 'from' => $from->format(self::LOG_DATE_FORMAT),\n 'to' => $to->format(self::LOG_DATE_FORMAT),\n ]);\n\n $page = 1;\n\n do {\n $response = $this->searchCallsForPeriodByPage($from, $to, $page);\n\n $responseResults = empty($response['results']) ? [] : $response['results'];\n\n $associationContacts = $this->getAssociationDataForCollection($responseResults, 'calls', 'contacts');\n $associationCompanies = $this->getAssociationDataForCollection($responseResults, 'calls', 'companies');\n $associationDeals = $this->getAssociationDataForCollection($responseResults, 'calls', 'deals');\n\n foreach ($responseResults as $call) {\n $call['associations'] = [\n 'contacts' => $this->importAssociationData($call, $associationContacts),\n 'companies' => $this->importAssociationData($call, $associationCompanies),\n 'deals' => $this->importAssociationData($call, $associationDeals),\n ];\n\n yield $call;\n }\n $page++;\n } while (! empty($responseResults));\n }\n\n public function getCall(string $callId): array\n {\n $this->logger->info('[HubSpot] Get call', [\n 'call_id' => $callId,\n ]);\n\n $searchAttributes = $this->payloadBuilder->getSearchCallAttributes();\n $endpoint = sprintf(\n 'https://api.hubapi.com/crm/v3/objects/calls/%s',\n $callId,\n );\n\n try {\n $response = $this->client->getInstance()->getClient()->request(\n 'GET',\n $endpoint,\n [],\n sprintf(\n 'properties=%s&associations=contacts,companies,deals',\n implode(',', $searchAttributes),\n ),\n );\n } catch (Exception $exception) {\n $this->logger->info('[HubSpot] Get call failed', [\n 'call_id' => $callId,\n 'reason' => $exception->getMessage(),\n ]);\n $response = null;\n }\n\n return empty($response) ? [] : $response->toArray();\n }\n\n public function bulkAddPlaybackURLToDescription(array $crmUpdateData): array\n {\n $crmUpdateBatches = array_chunk($crmUpdateData, self::BATCH_UPDATE_LIMIT);\n\n $updatedCrmIds = [];\n\n foreach ($crmUpdateBatches as $crmBatch) {\n $payload = $this->payloadBuilder->generatePlaybackAddUrlBatchPayload($crmBatch);\n $updateSuccess = $this->bulkAddPlaybackURLToDescriptionRequest($payload);\n if ($updateSuccess) {\n $updatedCrmIds = array_merge($updatedCrmIds, array_column($crmBatch, 'crm_id'));\n }\n }\n\n return $updatedCrmIds;\n }\n\n private function bulkAddPlaybackURLToDescriptionRequest(array $payload, bool $retry = true): bool\n {\n try {\n $this->client->getNewInstance()->crm()->objects()->batchApi()->update('calls', $payload);\n\n return true;\n } catch (\\HubSpot\\Client\\Crm\\Objects\\ApiException $e) {\n $response = json_decode($e->getResponseBody(), true);\n $retryAfter =\n isset($response['policyName'])\n && $response['policyName'] == self::TEN_SECONDLY_ROLLING_POLICY\n ? self::TEN_SECONDLY_ROLLING_LIMIT\n : 1;\n } catch (Exception $e) {\n $retryAfter = 1;\n }\n\n $this->logger->warning('[HubSpot] Bulk add playback url to CRM failed', [\n 'reason' => $e->getMessage(),\n 'retry' => $retry,\n ]);\n\n if ($retry) {\n sleep($retryAfter);\n\n return $this->bulkAddPlaybackURLToDescriptionRequest($payload, false);\n }\n\n return false;\n }\n\n /**\n * Sometimes we have secondly rate limit error, then retry request after 1 second\n */\n public function searchCallByRecordingURLToken(string $playbackURLToken, bool $retry = true): array\n {\n $endpoint = 'https://api.hubapi.com/crm/v3/objects/calls/search';\n $payload = $this->payloadBuilder->generateSearchCallByTokenPayload($playbackURLToken);\n\n $this->logger->info('[HubSpot] CRM Search by playback URL token requested', [\n 'request' => $payload,\n ]);\n\n try {\n $response = $this->client->getInstance()->getClient()->request('POST', $endpoint, ['json' => ($payload)]);\n } catch (Exception $exception) {\n $this->logger->info('[HubSpot] Search by playback URL token failed', [\n 'playbackURLToken' => $playbackURLToken,\n 'reason' => $exception->getMessage(),\n 'retry' => $retry,\n ]);\n\n if ($retry) {\n sleep(1);\n\n return $this->searchCallByRecordingURLToken($playbackURLToken, false);\n }\n\n return [];\n }\n\n return empty($response['results']) ? [] : $response['results'][0];\n }\n\n /**\n * Generate transcription for the activity.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! $this->config->store_transcript) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n $transcriptionSegments = $this->transcriptionService->findTranscriptionByActivity($activity);\n\n if ($transcriptionSegments->isEmpty()) {\n return '';\n }\n\n $transcription = sprintf(\n '<p><strong>Transcript for %s</strong></p><p></p>',\n $activity->title ?? $activity->activity_title,\n );\n\n $roomOwnerParticipant = $activity->findParticipantRoomOwner();\n $roomOwnerParticipantId = $roomOwnerParticipant !== null\n ? $roomOwnerParticipant->getId()\n : null;\n\n\n $transcription .= $transcriptionSegments\n ->map(static function (array $transcriptionSegment) use ($roomOwnerParticipantId): string {\n $isOrganiser = $roomOwnerParticipantId === $transcriptionSegment['participantId']\n && $roomOwnerParticipantId !== null;\n $transcriptColor = $isOrganiser ? '#000000' : '#f0415a';\n\n return sprintf(\n '<span style=\"color: %s;\">%s | </span>%s',\n $transcriptColor,\n $transcriptionSegment['formattedStartsAt'],\n $transcriptionSegment['transcript'],\n );\n })\n ->implode('<br />');\n\n return $transcription;\n }\n\n /**\n * @param array<array{\n * id: string,\n * label: string,\n * value?: string,\n * }> $options\n *\n * @return FieldData[]\n */\n private function importOptions(Field $field, array $options): array\n {\n $fieldValues = [];\n $values = [];\n $sequence = 0;\n\n foreach ($options as $option) {\n $values[] = [\n 'value' => $option['value'] ?? $option['id'],\n 'label' => substr($option['label'], 0, 255),\n 'sequence' => $sequence++,\n ];\n }\n\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n $value['value'] = substr($value['value'], 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n if (($key = array_search($value['value'], $fieldsToPurge, false)) !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n\n return $fieldValues;\n }\n\n public function saveTranscriptionSummaryAsNote(\n ActivityContract $activity,\n string $title,\n string $body,\n ?string $objectId,\n ?NoteObject $noteObject = null,\n ): ?string {\n if ($noteObject === null || $objectId === null) {\n return null;\n }\n\n /** @var User $user */\n $user = $activity->getUser();\n\n $profile = $this->assignCrmOwner($user, $activity);\n if (! $profile instanceof Profile) {\n return null;\n }\n\n $timestamp = Carbon::now($user->getTimezone())->getTimestamp() * 1000;\n $engagement = [\n 'active' => true,\n 'ownerId' => $profile->getAttribute('crm_provider_id'),\n 'timestamp' => $timestamp,\n 'type' => 'NOTE',\n ];\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $body = mb_strimwidth($body, 0, self::ENGAGEMENT_BODY_MAX_LENGTH);\n $metadata = [\n 'body' => $body,\n ];\n\n $associations = $this->convertActivityAssociations($activity);\n\n try {\n $hsActivityId = $this->client->createNote(\n body: $body,\n ownerId: $profile->getCrmProviderId(),\n timestamp: $timestamp,\n objectId: $objectId,\n noteObject: $noteObject,\n );\n\n $this->logCrmEngagementManipulation(self::ACTION_CREATE, $engagement, $metadata, $associations);\n\n $this->logger->info('[HubSpot] Saving Transcription Summary as Note', [\n 'activity' => $activity->getUuid(),\n 'crmActivity' => $hsActivityId,\n ]);\n\n return $hsActivityId;\n } catch (Exception $e) {\n Sentry::captureException($e);\n }\n\n return null;\n }\n\n public function attachSummaryToActivity(ActivityContract $activity, string $summaryTitle, string $summaryContents): bool\n {\n $this->logger->info('[HubSpot] Attaching summary to activity', [\n 'activity' => $activity->getUuid(),\n 'summary_content' => $summaryContents,\n ]);\n\n if (! $activity instanceof Activity) {\n throw new InvalidArgumentException('Expected instance of Activity');\n }\n\n $summary = '<p><strong>' . $summaryTitle . '</strong></p>';\n $summary .= '<p>' . $summaryContents . '</p>';\n $metadata = $this->buildMetadataForSummaryUpdate($activity, $summary);\n\n try {\n $type = $this->matchActivityEngagementType($activity);\n $engagement = ['type' => $type];\n\n $this->client->updateEngagement($activity->getCrmProviderId(), $engagement, $metadata);\n } catch (Exception $e) {\n $this->logger->warning('[HubSpot] Update summary failed', [\n 'activity' => $activity->getUuid(),\n 'reason' => $e->getMessage(),\n ]);\n\n return false;\n }\n\n $this->logCrmEngagementManipulation(\n self::ACTION_UPDATE,\n ['crmId' => $activity->getCrmProviderId()],\n $metadata,\n );\n\n return true;\n }\n\n private function buildMetadataForSummaryUpdate(Activity $activity, string $summary): array\n {\n $descriptionField = $activity->getType() === Activity::TYPE_CONFERENCE ? 'internalMeetingNotes' : 'body';\n $engagement = $this->client->getEngagementData($activity->getCrmProviderId());\n // Meeting without internalMeetingNotes might mean it just does not have any notes;\n $description = $engagement['metadata'][$descriptionField] ?? null;\n\n if (empty($description)) {\n $data = $summary;\n } else {\n // avoid playbook url link to Jiminny being sent twice in the activity description\n $targetUrl = PlaybackUrlBuilder::build($activity);\n\n if (str_contains($description, $targetUrl)) {\n $jiminnyUrl = '<p><a href=\"' . $targetUrl . '\" title=\"Play at Jiminny\">Play at Jiminny</a></p>';\n $summary = str_replace($jiminnyUrl, '', $summary);\n\n $this->logger->info('[HubSpot] Summary modified', [\n 'activity' => $activity->getUuid(),\n 'target_url' => $jiminnyUrl,\n 'modified_summary_content' => $summary,\n ]);\n }\n\n $data = $description . '<p></p>' . $summary;\n }\n\n return [\n $descriptionField => $data,\n ];\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n return $this->syncRelatedActivityManager->fetchAndAssociateRelatedActivity($activity);\n }\n\n public function fetchRelatedActivity(Activity $activity): array\n {\n return [];\n }\n\n public function getDealsInBulk(array $dealIds): array\n {\n $payload = $this->payloadBuilder->getDealsInBulkPayload($dealIds);\n\n return $this->client->getPaginatedData($payload, 'deals');\n }\n\n /**\n * Extract deal IDs from HubSpot search response.\n *\n * @param array $hubspotResponse The raw HubSpot search API response.\n * @param bool $includeArchived Whether to include archived deals (default: false).\n *\n * @return string[] Array of deal IDs as strings.\n */\n public function extractDealIds(array $hubspotResponse, bool $includeArchived = false): array\n {\n if (empty($hubspotResponse['results'])) {\n return [];\n }\n\n return array_values(\n array_map(\n fn ($deal) => $deal['id'],\n array_filter(\n $hubspotResponse['results'],\n fn ($deal) => $includeArchived || empty($deal['archived'])\n )\n )\n );\n }\n\n public function matchActivityEngagementType(Activity $activity): string\n {\n return match ($activity->getType()) {\n Activity::TYPE_CONFERENCE => self::TYPE_MEETING,\n Activity::TYPE_SOFTPHONE, Activity::TYPE_SOFTPHONE_INBOUND => self::TYPE_CALL,\n default => self::TYPE_NOTE,\n };\n }\n\n private function assignCrmOwner(User $user, ActivityContract $activity): ?Profile\n {\n $profile = $user->getProfile();\n if ($profile instanceof Profile) {\n return $profile;\n }\n\n $this->logger->info('[HubSpot] Unable to save summary. No profile', [\n 'activity' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n private static function getDealsPipelinesEndpoint(): string\n {\n return self::API_URL . self::ENDPOINT_PIPELINES . self::PIPELINE_OBJECT_TYPE_DEALS;\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n $engagement = $this->client->getEngagementData($crmProviderId);\n\n return ! empty($engagement);\n } catch (HttpNotFoundException|BadRequest) {\n // Engagement not found in CRM - this is expected and permanent\n $this->logger->info('[Hubspot] Engagement not found during verification', [\n 'engagement_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","depth":4,"value":"<?php\n\nnamespace Jiminny\\Services\\Crm\\Hubspot;\n\nuse Carbon\\Carbon;\nuse Exception;\nuse Generator;\nuse GuzzleHttp\\Exception\\RequestException;\nuse Illuminate\\Support\\Facades\\Cache;\nuse InvalidArgumentException;\nuse Jiminny\\Contracts\\Repositories\\TeamRepository;\nuse Jiminny\\Contracts\\Services\\Crm\\ClientInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\FetchRelatedActivityInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\LayoutManagementInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\MatchCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\Provider\\HubspotInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityLookupInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\RemoteEntityManipulationInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SavePlaybackLinkToCrmInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SendSummaryToCrmInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SettingsInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmEntitiesInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\SyncCrmMetadataInterface;\nuse Jiminny\\Contracts\\Services\\Crm\\VerifyTaskExistsInterface;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Exceptions\\HttpNotFoundException;\nuse Jiminny\\Jobs\\Crm\\NoteObject;\nuse Jiminny\\Models\\Account;\nuse Jiminny\\Models\\Activity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Contracts\\ActivityContract;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Models\\Crm\\Field;\nuse Jiminny\\Models\\Crm\\FieldData;\nuse Jiminny\\Models\\Crm\\Layout;\nuse Jiminny\\Models\\Crm\\Profile;\nuse Jiminny\\Models\\Lead;\nuse Jiminny\\Models\\Opportunity;\nuse Jiminny\\Models\\Participant;\nuse Jiminny\\Models\\Playbook;\nuse Jiminny\\Models\\SocialAccount;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Models\\User;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Repositories\\Crm\\FieldRepository;\nuse Jiminny\\Repositories\\Crm\\ProfileRepository;\nuse Jiminny\\Repositories\\ParticipantRepository;\nuse Jiminny\\Services\\Avatar\\ProspectPhotoPathService;\nuse Jiminny\\Services\\Crm\\BaseService;\nuse Jiminny\\Services\\Crm\\Hubspot\\Actions\\SyncArchivedProfilesAction;\nuse Jiminny\\Services\\Crm\\Hubspot\\Fields\\ValueNormalizer;\nuse Jiminny\\Services\\Crm\\Hubspot\\ServiceTraits\\OpportunitySyncTrait;\nuse Jiminny\\Services\\Crm\\Hubspot\\ServiceTraits\\SyncCrmEntitiesTrait;\nuse Jiminny\\Services\\Crm\\Hubspot\\ServiceTraits\\SyncFieldsTrait;\nuse Jiminny\\Services\\Crm\\Hubspot\\ServiceTraits\\WriteCrmTrait;\nuse Jiminny\\Services\\Crm\\MatchDomainByEmailInterface;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Services\\Crm\\ResolveCompanyNameByEmailTrait;\nuse Jiminny\\Utils\\PlaybackUrlBuilder;\nuse Sentry;\nuse SevenShores\\Hubspot\\Exceptions\\BadRequest;\nuse Throwable;\nuse UnexpectedValueException;\n\n/**\n * @phpstan-type CrmFieldDefinition array{\n * name: string,\n * label: string,\n * description: string,\n * type: string,\n * fieldType: string,\n * hidden: bool,\n * showCurrencySymbol: bool,\n * options: array<array{\n * id: string,\n * label: string,\n * value?: string,\n * }\n */\nclass Service extends BaseService implements\n HubspotInterface,\n SyncCrmEntitiesInterface,\n SyncCrmMetadataInterface,\n SendSummaryToCrmInterface,\n MatchDomainByEmailInterface,\n SavePlaybackLinkToCrmInterface,\n RemoteEntityManipulationInterface,\n FetchRelatedActivityInterface,\n LayoutManagementInterface,\n SettingsInterface,\n MatchCrmEntitiesInterface,\n RemoteEntityLookupInterface,\n VerifyTaskExistsInterface\n{\n use ResolveCompanyNameByEmailTrait;\n use SyncCrmEntitiesTrait;\n use WriteCrmTrait;\n use SyncFieldsTrait;\n use OpportunitySyncTrait;\n\n private const int ENGAGEMENT_BODY_MAX_LENGTH = 65536;\n\n private const string LOG_DATE_FORMAT = 'Y-m-d H:i:s';\n private const int BATCH_UPDATE_LIMIT = 100;\n private const string TEN_SECONDLY_ROLLING_POLICY = 'TEN_SECONDLY_ROLLING';\n private const int TEN_SECONDLY_ROLLING_LIMIT = 10;\n private const string CALLS_SEARCH_ENDPOINT = 'https://api.hubapi.com/crm/v3/objects/calls/search';\n\n private const string TYPE_NOTE = 'NOTE';\n\n private const string TYPE_MEETING = 'MEETING';\n\n private const string TYPE_CALL = 'CALL';\n\n private const string API_URL = 'https://api.hubapi.com';\n\n // NB: v1 is legacy - v3 is the newest\n private const string ENDPOINT_PIPELINES = '/crm-pipelines/v1/pipelines/';\n private const string PIPELINE_OBJECT_TYPE_DEALS = 'deals';\n\n private const int TASK_VERIFICATION_CACHE_TTL = 86400; // 1 day\n\n /**\n * @var ClientInterface|Client\n */\n protected $client;\n protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n protected CrmEntityRepository $crmEntityRepository;\n protected ProspectPhotoPathService $prospectPhotoPathService;\n\n private SyncFieldAction $syncFieldAction;\n private PayloadBuilder $payloadBuilder;\n private SyncRelatedActivityManager $syncRelatedActivityManager;\n private SyncArchivedProfilesAction $syncArchivedProfilesAction;\n private WebhookSyncBatchProcessor $batchProcessor;\n\n public function __construct(\n Client $client,\n SyncFieldAction $syncFieldAction,\n PayloadBuilder $payloadBuilder,\n ProspectPhotoPathService $prospectPhotoPathService,\n SyncArchivedProfilesAction $syncArchivedProfilesAction,\n WebhookSyncBatchProcessor $batchProcessor,\n ) {\n parent::__construct();\n\n $this->client = $client;\n $this->syncFieldAction = $syncFieldAction;\n $this->prospectPhotoPathService = $prospectPhotoPathService;\n $this->payloadBuilder = $payloadBuilder;\n $this->syncArchivedProfilesAction = $syncArchivedProfilesAction;\n $this->batchProcessor = $batchProcessor;\n $this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [\n 'client' => $this->client,\n ]);\n $this->syncRelatedActivityManager = app(SyncRelatedActivityManager::class, [\n 'client' => $this->client,\n 'payloadBuilder' => $this->payloadBuilder,\n 'logger' => $this->logger,\n ]);\n $this->crmEntityRepository = app(CrmEntityRepository::class);\n $this->dealFieldsService = app(DealFieldsService::class);\n }\n\n public function getDisplayName(): string\n {\n return 'HubSpot';\n }\n\n protected function getOAuthAccount(User $user): ?SocialAccount\n {\n // In this case, the Account Owner is always the connection for any API operations.\n $owner = $user->team->owner;\n\n return $owner->getSocialAccount(SocialAccount::PROVIDER_HUBSPOT);\n }\n\n public function getClient(): Client\n {\n /** @var Client */\n return $this->client;\n }\n\n /**\n * Convert raw field data into a format compatible with CRM APIs.\n *\n * @param bool $internal Direction of the conversion.\n * True is pulling from CRM, false normalize before sending to CRM.\n */\n public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string\n {\n return ValueNormalizer::normalize(\n fieldType: $fieldType,\n fieldValue: $fieldValue,\n isInbound: $internal,\n );\n }\n\n public function getRecordTypes(string $crmObject): array\n {\n return [];\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultFields(string $activityType): array\n {\n $fields = [];\n\n if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {\n $defaultFields = FieldDefinitions::defaultTaskFields();\n\n // This lazy creates these fields if not already setup.\n foreach ($defaultFields as $defaultField) {\n $fields[] = $this->config->fields()->firstOrCreate($defaultField);\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityField(string $activityType): Field\n {\n /** @var Field $activityField */\n $activityField = $this->config->fields()->where([\n 'crm_provider_id' => 'activityType',\n 'object_type' => $activityType,\n ])->first();\n\n return $activityField;\n }\n\n /**\n * @inheritdoc\n */\n public function getSupportedPlaybookTypes(): array\n {\n return [Playbook::ACTIVITY_TYPE_TASK];\n }\n\n /**\n * @inheritdoc\n */\n public function getDefaultActivityLayoutFields(string $activityType, string $layoutType): array\n {\n $fields = [];\n\n if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {\n // Outcome should always be provided calls/meetings.\n $fieldData = [\n [\n 'crm_provider_id' => $layoutType === Layout::TYPE_SOFTPHONE_SUMMARY ? 'disposition' : 'meetingOutcome',\n 'object_type' => Field::OBJECT_TASK,\n ],\n ];\n\n foreach ($fieldData as $data) {\n $field = $this->config->fields()->where($data)->first();\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n }\n\n return $fields;\n }\n\n public function getDealInsightsFields(): array\n {\n return FieldDefinitions::dealInsightsFields();\n }\n\n protected function getDefaultFollowupLayoutFields(string $activityType): array\n {\n $fields = [];\n $fieldRepo = app(FieldRepository::class);\n $fieldData = FieldDefinitions::followupFieldsFilter();\n\n foreach ($fieldData as $data) {\n $field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);\n\n // Only add the field if it is created, which it should be.\n if ($field) {\n $fields[] = $field;\n }\n }\n\n return $fields;\n }\n\n /**\n * @inheritdoc\n */\n public function syncField(Field $field): void\n {\n switch ($field->object_type) {\n case Field::OBJECT_ACCOUNT:\n $crmField = $this->client->getInstance()->companyProperties()->get($field->crm_provider_id);\n\n break;\n case Field::OBJECT_CONTACT:\n $crmField = $this->client->getInstance()->contactProperties()->get($field->crm_provider_id);\n\n break;\n case Field::OBJECT_OPPORTUNITY:\n $crmField = $this->client->getInstance()->dealProperties()->get($field->crm_provider_id);\n\n break;\n case Field::OBJECT_TASK:\n $this->syncSingleTaskField($field);\n\n return;\n default:\n return;\n }\n\n $this->syncFieldAction->execute($field, $crmField->toArray());\n }\n\n /**\n * @param array<array{\n * id:string,\n * label:string,\n * value?:string\n * }> $options\n *\n * @throws CrmException\n *\n * @return FieldData[]\n *\n */\n public function importPicklistValues(\n Field $field,\n array $options = [['id' => '', 'label' => '', 'value' => '']],\n ): array {\n if (! empty($options[0]['id']) || ! empty($options[0]['value'])) {\n // We already have the options, no need to fetch them again\n return $this->importOptions($field, $options);\n }\n\n $options = [];\n\n switch ($field->getObjectType()) {\n case Field::OBJECT_ACCOUNT:\n $options = $this->getClient()->fetchPropertyOptions('company', $field->getCrmProviderId());\n\n break;\n\n case Field::OBJECT_CONTACT:\n $options = $this->getClient()->fetchPropertyOptions('contact', $field->getCrmProviderId());\n\n break;\n\n case Field::OBJECT_OPPORTUNITY:\n // Hubspot has different endpoint for stages\n $options = $this->getClient()->fetchOpportunityFieldOptions($field);\n\n break;\n\n case Field::OBJECT_TASK:\n if ($field->getCrmProviderId() === 'disposition') {\n $options = $this->getClient()->fetchDispositionFieldOptions();\n } elseif (in_array($field->getCrmProviderId(), ['meetingOutcome', 'activityType'])) {\n $options = $this->getClient()->fetchMeetingOutcomeFieldOptions($field);\n }\n\n break;\n\n default:\n $this->logger->warning('Invalid object type', [\n 'object_type' => $field->getObjectType(),\n 'field_id' => $field->getId(),\n ]);\n\n throw new CrmException('Invalid object type');\n }\n\n return $this->importOptions($field, $options);\n }\n\n /**\n * Gets business processes.\n */\n public function importBusinessProcesses(): void\n {\n // Taken care of in importStages().\n }\n\n /**\n * Gets business process stages.\n */\n public function importBusinessProcessStages(BusinessProcess $businessProcess): void\n {\n // Taken care of in importStages().\n }\n\n /**\n * Gets record types.\n */\n public function importRecordTypes(): void\n {\n // Taken care of in importStages().\n }\n\n /**\n * @inheritdoc\n */\n public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage\n {\n $missingStage = null;\n\n try {\n // Use the HubSpot API client instead of the SDK crmPipelines() method\n $endpoint = self::getDealsPipelinesEndpoint();\n $pipelinesResponse = $this->client->getInstance()->getClient()->request('GET', $endpoint);\n $pipelines = $pipelinesResponse->data->results;\n } catch (RequestException|BadRequest $exception) {\n throw $exception;\n }\n\n foreach ($pipelines as $pipeline) {\n $stages = [];\n\n // We create a business process to contain the pipeline, and store all stages against it.\n $p = ResponseNormalize::normalizePipeline($pipeline);\n\n // Create/update business process for this pipeline\n $businessProcess = $this->config->businessProcesses()->updateOrCreate([\n 'crm_provider_id' => $p['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($p['label'], 0, 150),\n 'type' => BusinessProcess::TYPE_OPPORTUNITY,\n 'is_selectable' => $p['active'],\n ]);\n\n // A record type is really a clone of the business process, used to store which record uses which pipeline.\n // Create/update record type clone\n $this->config->recordTypes()->updateOrCreate([\n 'crm_provider_id' => $p['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($p['label'], 0, 150),\n 'is_selectable' => $p['active'],\n 'business_process_id' => $businessProcess->id ?? null,\n ]);\n\n // Stages\n foreach ($p['stages'] as $dealStage) {\n $s = ResponseNormalize::normalizeDealStage($dealStage);\n\n // Upsert all stages for the team.\n $stage = $this->config->stages()->updateOrCreate([\n 'crm_provider_id' => $s['id'],\n ], [\n 'team_id' => $this->team->id,\n 'name' => mb_strimwidth($s['label'], 0, 50),\n 'label' => mb_strimwidth($s['label'], 0, 191),\n 'type' => Stage::TYPE_OPPORTUNITY,\n 'sequence' => $s['displayOrder'],\n 'is_selectable' => $s['active'],\n 'probability' => $s['probability'] * 100,\n ]);\n\n if ($missingStageName && $missingStageName === $s['id']) {\n $missingStage = $stage;\n }\n\n $stages[] = $stage->id;\n }\n\n $businessProcess->stages()->sync($stages);\n }\n\n return $missingStage;\n }\n\n /**\n * @inheritdoc\n */\n public function syncOrganization(): void\n {\n try {\n $endpoint = 'https://api.hubapi.com/integrations/v1/me';\n $response = $this->client->getInstance()->getClient()->request('get', $endpoint);\n\n $accountData = $response->data;\n $this->config->update(['default_currency' => $accountData->currency]);\n } catch (BadRequest $e) {\n throw new CrmException('Could not sync the organization.', $e->getCode(), $e);\n }\n }\n\n /**\n * @inheritdoc\n *\n * @throws CrmException\n */\n public function syncProfiles(?User $userToSearch = null): ?Profile\n {\n $this->syncArchivedProfilesAction->execute($this->team, $this->client, $this->config);\n\n try {\n $owners = $this->client->getOwners();\n } catch (\\HubSpot\\Client\\Crm\\Owners\\ApiException $e) {\n $this->logger->error('[HubSpot] Could not sync the profiles.', [\n 'team_id' => $this->team->getId(),\n 'reason' => $e->getMessage(),\n ]);\n\n throw new CrmException('Could not sync the profiles.', $e->getCode(), $e);\n }\n\n $profileRepository = app(ProfileRepository::class);\n $teamRepository = app(TeamRepository::class);\n\n foreach ($owners as $owner) {\n if ($owner->getArchived()) {\n // not supposed to fetch archived, but log anyway\n $this->logger->warning('[HubSpot] Found archived owner', [\n 'crm_provider_id' => $owner->getId(),\n 'email' => $owner->getEmail(),\n ]);\n\n continue;\n }\n\n $email = $owner->getEmail();\n if ($email === null) {\n continue;\n }\n\n $user = $teamRepository->findActiveTeamMemberByEmail($this->team, $email);\n\n if (! $user instanceof User) {\n continue;\n }\n\n $profile = $profileRepository->updateOrCreateProfile($user, [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $owner->getId(),\n ]);\n\n if ($userToSearch && $userToSearch->getId() === $user->getId()) {\n return $profile;\n }\n }\n\n return null;\n }\n\n private function generateNameSearchPayload(string $name, int $offset, int $limit): array\n {\n $payload = [\n 'query' => $name,\n 'sorts' => [\n [\n 'propertyName' => 'modifieddate',\n 'direction' => 'DESCENDING',\n ],\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 'industry',\n 'name',\n 'company',\n ],\n 'limit' => $limit,\n 'after' => $offset,\n ];\n\n $this->logger->debug('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n return $payload;\n }\n\n /**\n * @inheritdoc\n */\n public function find(string $name, array $scopes): array\n {\n $count = $this->limit ?? 20;\n $offset = $this->offset ?? 0;\n\n /** @var array<int, array<string, mixed>> */\n return Cache::remember(\n key: $this->team->getId() . $name . $count . $offset,\n ttl: 300,\n callback: function () use ($name, $offset, $count): array {\n $data = [];\n\n // Use the new V3 API to find contacts based on additional fields.\n foreach (['companies', 'contacts'] as $objectType) {\n $endpoint = 'https://api.hubapi.com/crm/v3/objects/' . $objectType . '/search';\n $payload = $this->generateNameSearchPayload($name, $offset, $count);\n $type = $objectType === 'companies' ? 'account' : 'contact';\n\n try {\n $response = $this->client->getInstance()->getClient()->request('POST', $endpoint, [\n 'json' => $payload,\n ]);\n\n // Build mapped list.\n foreach ($response['results'] as $object) {\n $properties = $object['properties'];\n\n $objectName = $this->buildContactName($properties);\n\n $record = [\n 'crmId' => $object['id'],\n // Pass crmUrl to the FE, needed for success message in the extension when you log activity.\n 'crmUrl' => $this->generateProviderUrl($object['id'], $type),\n 'name' => $objectName,\n 'prospectType' => $type,\n 'phoneNumbers' => [],\n ];\n\n if ($type === 'account') {\n $record['industry'] = $properties['industry'] ?? null;\n } else {\n $record['title'] = $properties['jobtitle'] ?? null;\n $record['organization'] = $properties['company'] ?? null;\n }\n\n $countryCode = $this->buildContactCountry($properties);\n $parsedNumber = $this->buildContactPhone($countryCode, $properties);\n\n // Add phone number to record.\n if (! empty($parsedNumber['phone'])) {\n $record['phoneNumbers'][] = [\n 'number' => $parsedNumber['phone'],\n 'nationalFormat' => phone_national($countryCode, $parsedNumber['phone']),\n 'type' => 'phone',\n ];\n }\n\n // Add mobile phone number to record.\n if (! empty($properties['mobilephone'])) {\n $mobileNumber = phone_e164($countryCode, $properties['mobilephone']);\n if ($mobileNumber !== null) {\n $record['phoneNumbers'][] = [\n 'number' => $mobileNumber,\n 'nationalFormat' => phone_national($countryCode, $mobileNumber),\n 'type' => 'mobile',\n ];\n }\n }\n\n $data[] = $record;\n }\n } catch (BadRequest $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Search failed', [\n 'teamId' => $this->team->getUuid(),\n 'request' => $payload,\n 'reason' => $e->getMessage(),\n ]);\n\n throw $e;\n }\n }\n\n return $data;\n },\n );\n }\n\n\n /**\n * @inheritdoc\n */\n public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array\n {\n $data = [];\n $ownerData = [];\n $ownerId = null;\n\n if ($crmAccountId === null) {\n return $data;\n }\n\n if ($userId) {\n $profileRepository = app(ProfileRepository::class);\n $profile = $profileRepository->findProfileByUserId($this->config, $userId);\n\n $ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;\n }\n\n $closedStages = $this->getClosedDealStages();\n $payload = $this->payloadBuilder->generateOpportunitiesSearchPayload(\n $this->config,\n $crmAccountId,\n $closedStages,\n );\n\n $results = $this->client->getPaginatedData($payload, 'deals');\n\n foreach ($results['results'] as $object) {\n $properties = $object['properties'];\n\n $amount = null;\n if (empty($properties['amount']) === false) {\n $currency = $properties['deal_currency_code'] ?? $this->config->default_currency;\n\n // Values can contain commas and any junk so strip them.\n $value = (float) preg_replace('/[^\\d.]/', '', $properties['amount']);\n $amount = formatCurrency($value, $currency);\n }\n\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', $properties['pipeline'])\n ->first();\n\n if ($businessProcess === null) {\n // Import it.\n $stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $properties['dealstage']);\n $businessProcess = $this->config\n ->businessProcesses()\n ->where('crm_provider_id', $properties['pipeline'])\n ->first();\n } else {\n $stage = $businessProcess\n ->stages()\n ->where('crm_provider_id', $properties['dealstage'])\n ->where('type', Stage::TYPE_OPPORTUNITY)\n ->first();\n\n if ($stage === null) {\n // Import it.\n $stage = $this->importStages(null, $properties['dealstage']);\n }\n }\n\n $recordType = null;\n if ($businessProcess) {\n $recordType = $businessProcess->recordTypes()->first();\n }\n\n $isWon = in_array($properties['dealstage'], $closedStages['won']);\n $isLost = in_array($properties['dealstage'], $closedStages['lost']);\n\n $record = [\n 'crmId' => $object['id'],\n 'name' => $properties['dealname'] ?? 'Unknown Deal',\n 'value' => $amount,\n 'won' => $isWon,\n 'closed' => $isWon || $isLost,\n 'stage' => [\n 'id' => $stage?->getUuid() ?? '',\n 'name' => $stage?->getName() ?? '',\n ],\n ];\n\n if ($recordType) {\n $record += [\n 'recordType' => [\n 'id' => $recordType->id_string,\n 'name' => $recordType->name,\n ],\n ];\n }\n\n if ($ownerId && isset($properties['hubspot_owner_id']) && $properties['hubspot_owner_id'] === $ownerId) {\n $ownerData[] = $record;\n }\n\n $data[] = $record;\n }\n\n if (! empty($ownerData)) {\n return $ownerData;\n }\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getTasks(?string $objectType, string $objectId, ?string $opportunityId): array\n {\n $data = [];\n switch ($objectType) {\n case 'contact':\n $hsObject = 'contact';\n\n break;\n case 'account':\n $hsObject = 'company';\n\n break;\n default:\n // This is a hack to prioritise and override a contact/company with a deal.\n if ($opportunityId) {\n $hsObject = 'deal';\n $objectId = $opportunityId;\n } else {\n throw new InvalidArgumentException('Object type not supported.');\n }\n }\n\n $engagementTypes = ['meetings', 'tasks'];\n\n foreach ($engagementTypes as $engagementType) {\n $payload = $this->payloadBuilder->getLinkToTaskPayload($hsObject, $objectId, $engagementType);\n\n $this->logger->info('[HubSpot] CRM Search requested', [\n 'request' => $payload,\n ]);\n\n $engagements = $this->client->getPaginatedData($payload, $engagementType);\n\n foreach ($engagements['results'] as $engagement) {\n if ($engagementType == 'meetings') {\n $title = $engagement['properties']['hs_meeting_title'] ?? 'Scheduled meeting';\n } elseif ($engagementType == 'tasks') {\n $title = $engagement['properties']['hs_task_subject'];\n } else {\n $title = 'Scheduled meeting';\n }\n\n $data[] = [\n 'crmId' => $engagement['id'],\n 'subject' => $title,\n 'due' => $engagement['properties']['hs_timestamp'],\n 'type' => $engagement['properties']['hs_activity_type'] ?? null,\n ];\n }\n }\n\n usort($data, function ($item1, $item2) {\n return $item2['due'] <=> $item1['due'];\n });\n\n return $data;\n }\n\n /**\n * @inheritdoc\n */\n public function getEvents(string $objectType, string $objectId, ?string $opportunityId): array\n {\n return [];\n }\n\n /**\n * Try to find CRM Objects using email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchExactlyByEmail(string $email, ?int $userId = null): ?array\n {\n $contactProperties = [\n 'email',\n 'firstname',\n 'lastname',\n 'country',\n 'phone',\n 'mobilephone',\n 'jobtitle',\n 'hubspot_owner_id',\n 'associatedcompanyid',\n 'photo',\n ];\n $contact = null;\n $account = null;\n\n try {\n $hsContact = $this->getClient()->getContactByEmail($email, $contactProperties);\n\n if ($hsContact) {\n $contact = $this->importContact($hsContact);\n $account = $contact->account;\n }\n\n $data = $this->convertCrmData($contact, $account, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n } catch (BadRequest $e) {\n $this->logger->warning('[HubSpot] Search failed', [\n 'team_id' => $this->team->getId(),\n 'search_identifier' => $email,\n 'reason' => $e->getMessage(),\n ]);\n }\n\n return null;\n }\n\n public function getDomain(string $email): ?string\n {\n return $this->getDomainFromEmail($email);\n }\n\n /**\n * Try to find CRM objects using domain name of the email address\n *\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByDomain(string $domain, ?int $userId = null): ?array\n {\n $companyName = $domain;\n\n // Try to find a company matching their email domain.\n $companyProperties = [\n 'country',\n 'phone',\n 'name',\n 'hs_avatar_filemanager_key',\n 'industry',\n 'hubspot_owner_id',\n 'domain',\n ];\n\n try {\n $hsAccounts = $this->client\n ->getInstance()\n ->companies()\n ->searchByDomain($companyName, $companyProperties);\n } catch (Throwable $e) {\n $this->logger->info('[HubSpot] Search failed', [\n 'error' => $e->getMessage(),\n 'domain' => $domain,\n ]);\n\n return null;\n }\n\n $account = null;\n // If there are multiple accounts, don't guess, we'll ask later.\n if (\\count($hsAccounts->data->results) === 1) {\n // Persist this remote object.\n $account = $this->syncAccount($hsAccounts->data->results[0]->companyId);\n }\n\n $data = $this->convertCrmData(null, $account, $userId);\n\n return ! empty(array_filter($data)) ? $data : null;\n }\n\n /**\n * @return array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n protected function convertCrmData(?Contact $contact, ?Account $account, ?int $userId = null): array\n {\n $countryCode = null;\n if ($contact && $contact->country_code) {\n $countryCode = $contact->country_code;\n } elseif ($account && $account->country_code) {\n $countryCode = $account->country_code;\n }\n\n try {\n $hsOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact ? $contact->crm_provider_id : null,\n $userId\n );\n } catch (Exception $e) {\n $hsOpportunities = [];\n }\n\n // If there are multiple opportunities, don't guess, we'll ask later.\n $opportunity = null;\n $stage = null;\n if (! empty($hsOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($hsOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n protected function getCacheKey(string $object, ?int $userId = null): ?string\n {\n $key = $this->team->getId() . $object;\n $keySuffix = $this->getOwnerKeySuffix($userId);\n\n return $key . $keySuffix;\n }\n\n private function getOwnerKeySuffix(?int $userId = null): string\n {\n return $userId === null ? '' : (string) $userId;\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n *}\n */\n public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array\n {\n if (str_contains($phone, '**')) {\n return null;\n }\n\n // trim all whitespaces if present so the lookup doesn't fail\n $phone = str_replace(' ', '', $phone);\n\n // Check if the user is internal.\n if ($this->isPhoneNumberOfTeamMember($phone)) {\n return null;\n }\n\n $response = $this->searchForPhoneNumber($phone);\n if (empty($response)) {\n return null;\n }\n\n // This would ideally importContact instead but the response type differs.\n $contact = $this->findAndSyncContact($response['results'][0]['id']);\n if (! $contact instanceof Contact) {\n return null;\n }\n\n $account = $contact->account;\n $countryCode = $contact->country_code ?? $account->country_code ?? null;\n\n try {\n $hsOpportunities = $this->findOpportunities(\n $account?->crm_provider_id,\n $contact->crm_provider_id,\n $userId\n );\n } catch (Exception $e) {\n $hsOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n\n try {\n if (! empty($hsOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($hsOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n } catch (Exception $e) {\n $this->logger->debug('[HubSpot] Opportunity failed to sync.', [\n 'reason' => $e->getMessage(),\n ]);\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n }\n\n private function isPhoneNumberOfTeamMember(string $phone): bool\n {\n $teamRepository = app(TeamRepository::class);\n $user = $teamRepository->findTeamMemberByPhone($this->team, $phone);\n\n if ($user instanceof User) {\n return true;\n }\n\n return false;\n }\n\n private function findAndSyncContact(string $crmId): ?Contact\n {\n try {\n return $this->syncContact($crmId);\n } catch (Exception $exception) {\n $this->logger->info('[HubSpot] Phone match failed', [\n 'reason' => $exception->getMessage(),\n ]);\n\n return null;\n }\n }\n\n private function hasResults(array $response): bool\n {\n return isset($response['total']) && is_numeric($response['total']) && $response['total'] > 0;\n }\n\n private function searchForPhoneNumber(string $phone): array\n {\n // Normalizes the provided phone number for the API search.\n $normalizedPhone = $this->normalizePhoneNumber($phone);\n $payload = $this->payloadBuilder->generatePhoneSearchPayload($normalizedPhone);\n\n $this->logger->info('[HubSpot] Phone match search triggered', [\n 'phone' => $phone,\n 'normalizedPhone' => $normalizedPhone,\n 'payload' => $payload,\n ]);\n\n $response = $this->handlePhoneSearchRequest($normalizedPhone, $payload);\n\n if (! $this->hasResults($response)) {\n $nationalPhone = preg_replace('/\\D/', '', phone_national(null, $phone));\n $payload = $this->payloadBuilder->generatePhoneSearchPayload($nationalPhone);\n\n $this->logger->info('[HubSpot] Phone match national number search triggered', [\n 'phone' => $phone,\n 'nationalPhone' => $nationalPhone,\n 'payload' => $payload,\n ]);\n\n $response = $this->handlePhoneSearchRequest($phone, $payload);\n }\n\n if (! $this->hasResults($response)) {\n $payload = $this->payloadBuilder->generatePhoneSearchPayload($normalizedPhone, true);\n\n $this->logger->info('[HubSpot] Phone match alternative search triggered', [\n 'phone' => $phone,\n 'normalizedPhone' => $normalizedPhone,\n 'payload' => $payload,\n ]);\n\n $response = $this->handlePhoneSearchRequest($phone, $payload);\n }\n\n return $this->hasResults($response) ? $response : [];\n }\n\n private function handlePhoneSearchRequest(string $phone, array $payload): array\n {\n $endpoint = 'https://api.hubapi.com/crm/v3/objects/contacts/search';\n\n try {\n $response = $this->client->getInstance()->getClient()->request(\n 'POST',\n $endpoint,\n ['json' => ($payload)],\n );\n } catch (Exception $exception) {\n $this->logger->info('[HubSpot] Phone match failed', [\n 'phone' => $phone,\n 'reason' => $exception->getMessage(),\n ]);\n\n return [];\n }\n\n $this->logger->info('[HubSpot] Phone match completed', [\n 'phone' => $phone,\n 'response' => $response,\n ]);\n\n return $response->toArray();\n }\n\n private function normalizePhoneNumber(string $phone): string\n {\n return ltrim(phone_e164(null, $phone), '+0');\n }\n\n /**\n * @return null|array{\n * Lead|null,\n * Account|null,\n * Opportunity|null,\n * Contact|null,\n * Stage|null,\n * string|null\n * }\n */\n public function matchByName(string $name, ?int $userId = null): ?array\n {\n // Don't waste time searching for single character strings.\n if (\\strlen($name) <= 1) {\n return null;\n }\n\n $cacheKey = $this->getCacheKey($name, $userId);\n\n $result = Cache::remember($cacheKey, 60, function () use ($name, $userId) {\n $payload = $this->payloadBuilder->generateSearchContactsByNamePayload(\n $name,\n $this->getContactFields()\n );\n\n $hsContacts = $this->client->getPaginatedData($payload, 'contact');\n if (empty($hsContacts['results'])) {\n return false;\n }\n\n $contact = $this->importContact($hsContacts['results'][0]);\n if ($contact === null) {\n return false;\n }\n\n $account = $contact->account;\n $countryCode = $contact->country_code ?? $account->country_code ?? null;\n\n try {\n $hsOpportunities = $this->findOpportunities(\n $account ? $account->crm_provider_id : null,\n $contact->crm_provider_id,\n $userId\n );\n } catch (Exception $e) {\n $hsOpportunities = [];\n }\n\n $opportunity = null;\n $stage = null;\n if (! empty($hsOpportunities)) {\n // Persist this remote object.\n $opportunity = $this->syncOpportunity($hsOpportunities[0]['crmId']);\n $stage = $opportunity?->getStage();\n }\n\n return [\n null,\n $account,\n $opportunity,\n $contact,\n $stage,\n $countryCode,\n ];\n });\n\n return is_array($result) ? $result : null;\n }\n\n\n private function convertActivityAssociations(Activity $activity): array\n {\n return [\n 'contactIds' => $this->getParticipantsIds($activity),\n 'companyIds' => $activity->hasAccount() ? [$activity->account->crm_provider_id] : [],\n 'dealIds' => $activity->hasOpportunity() ? [$activity->opportunity->crm_provider_id] : [],\n 'ownerIds' => [],\n ];\n }\n\n private function getParticipantsIds(Activity $activity): array\n {\n $attendees = [];\n\n $participantRepository = app(ParticipantRepository::class);\n $participants = $participantRepository->getParticipantsWhoEnteredMeeting($activity);\n foreach ($participants as $participant) {\n if ($participant->user_id || $participant->isCoach()) {\n continue;\n }\n\n $contact = $participant->contact()->first();\n if ($contact && $contact->crm_provider_id) {\n $attendees[] = $contact->crm_provider_id;\n } else {\n if (! empty($participant->name)) {\n $attendeeData = $this->fetchMissingAttendeeInfo($participant);\n }\n if (! empty($attendeeData['id'])) {\n $attendees[] = $attendeeData['id'];\n }\n }\n }\n\n if ($activity->hasContact()) {\n $attendees[] = $activity->contact->crm_provider_id;\n }\n\n return array_unique($attendees);\n }\n\n private function fetchMissingAttendeeInfo(Participant $participant): array\n {\n // Check if we need to look inside an account context.\n $activity = $participant->getActivity();\n $companyId = $activity->hasAccount() ? $activity->getAccount()->crm_provider_id : null;\n\n // First check the local data.\n /** @var Contact[] $contacts */\n $contacts = $this->team->contacts()\n ->with('account')\n ->where('name', $participant->name)\n ->whereNotNull('email')\n ->get();\n\n foreach ($contacts as $contact) {\n // If we have a company in scope, check the contact is associated to it.\n if (\n $companyId !== null\n && ($contact->account_id === null || $companyId !== $contact->account->crm_provider_id)\n ) {\n continue;\n }\n\n return [\n 'id' => $contact->crm_provider_id,\n 'email' => $contact->email,\n ];\n }\n\n $payload = $this->generateNameSearchPayload($participant->name, 0, 20);\n\n try {\n $response = $this->client->getNewInstance()->crm()->contacts()->searchApi()->doSearch($payload);\n\n // TODO add some logic to choose the most suitable contact if multiple\n foreach ($response['results'] as $object) {\n $properties = $object['properties'];\n if (empty($object['properties']) === false) {\n // Check the company matches the contact.\n // Todo: Move this check inside the API search.\n if ($companyId !== null && $companyId !== $properties['associatedcompanyid']) {\n continue;\n }\n\n return [\n 'id' => $object['id'],\n 'email' => $properties['email'],\n ];\n }\n }\n } catch (Exception $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Search failed', [\n 'teamId' => $this->team->id_string,\n 'request' => $payload,\n 'reason' => $e->getMessage(),\n ]);\n }\n\n return [];\n }\n\n /**\n * Store transcripts as note engagement.\n *\n * @throws Exception\n */\n public function createTranscriptNotes(Activity $activity): void\n {\n // For HS no need to check if Crm profile - Log Notes field is enabled\n // We only check if store_transcript toggle is enabled on crm profile.\n $engagement = [\n 'active' => true,\n 'ownerId' => $this->profile->crm_provider_id,\n 'timestamp' => $activity->created_at->tz($activity->user->timezone)->getTimestamp() * 1000,\n 'type' => 'NOTE',\n ];\n\n // Generate activity transcription.\n $transcriptionData = $this->generateTranscription($activity);\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $transcripts = mb_strimwidth($transcriptionData, 0, static::ENGAGEMENT_BODY_MAX_LENGTH);\n\n $metadata = [\n 'body' => $transcripts,\n ];\n\n $associations = $this->convertActivityAssociations($activity);\n\n try {\n $hsEngagement = $this->client\n ->getInstance()\n ->engagements()\n ->create($engagement, $associations, $metadata);\n\n $this->logCrmEngagementManipulation(self::ACTION_CREATE, $engagement, $metadata, $associations);\n\n $noteId = $hsEngagement->data->engagement->id;\n\n // Store crm logged id in transcription.\n $transcription = $activity->getTranscription();\n $transcription->crm_activity_id = $noteId;\n $transcription->save();\n } catch (Exception $e) {\n Sentry::captureException($e);\n }\n }\n\n /*\n * @inheritdoc\n */\n public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void\n {\n $payload = [\n 'properties' => $data,\n ];\n\n try {\n switch ($objectType) {\n case FieldData::OBJECT_OPPORTUNITY:\n $this->client->getNewInstance()->crm()->deals()->basicApi()->update($objectId, $payload);\n\n break;\n case FieldData::OBJECT_CONTACT:\n $this->client->getNewInstance()->crm()->contacts()->basicApi()->update($objectId, $payload);\n\n break;\n\n case FieldData::OBJECT_ACCOUNT:\n $this->client->getNewInstance()->crm()->companies()->basicApi()->update($objectId, $payload);\n\n break;\n\n case FieldData::OBJECT_TASK:\n // Endpoint for Engagements not ready\n $engagements = [\n 'type' => 'TASK',\n ];\n $metadata = $data;\n $this->client->getInstance()->engagements()->update($objectId, $engagements, $metadata);\n\n $this->logCrmEngagementManipulation(\n self::ACTION_UPDATE,\n ['crmId' => $objectId],\n $metadata,\n );\n\n break;\n\n default:\n throw new UnexpectedValueException('Unsupported object type \"' . $objectType . '\"');\n }\n } catch (\\HubSpot\\Client\\Crm\\Deals\\ApiException $apiException) {\n $errorMessage = $apiException->getMessage();\n if ($apiException->getResponseBody()) {\n $responseBody = json_decode($apiException->getResponseBody(), true, 512, JSON_THROW_ON_ERROR);\n $errorMessage = $responseBody['message'] ?? $apiException->getMessage();\n }\n\n $this->logger->error(\n '[HubSpot] Update record failed',\n [\n 'objectType' => $objectType,\n 'objectId' => $objectId,\n 'payload' => $payload,\n 'reason' => $errorMessage,\n 'team' => $this->team->getUuid(),\n ]\n );\n\n throw new CrmException($errorMessage);\n }\n }\n\n /*\n * @inheritdoc\n */\n public function getRecord(string $objectType, string $objectId, array $fields = []): array\n {\n switch ($objectType) {\n case FieldData::OBJECT_OPPORTUNITY:\n return $this->client->getInstance()->deals()->getById($objectId)->toArray();\n\n case FieldData::OBJECT_CONTACT:\n return $this->client->getInstance()->contacts()->getById($objectId)->toArray();\n\n case FieldData::OBJECT_ACCOUNT:\n return $this->client->getInstance()->companies()->getById($objectId)->toArray();\n\n case FieldData::OBJECT_TASK:\n return $this->client->getInstance()->engagements()->get($objectId)->toArray();\n\n default:\n throw new UnexpectedValueException('Unsupported object type \"' . $objectType . '\"');\n }\n }\n\n /**\n * @throws BadRequest\n * @throws CrmException\n */\n public function updateStage($crmObject, Stage $stage): void\n {\n $payload = [\n 'properties' => [\n [\n 'name' => 'dealstage',\n 'value' => $stage->crm_provider_id,\n ],\n ],\n ];\n\n try {\n $this->client->getInstance()->deals()->update($crmObject->crm_provider_id, $payload);\n } catch (BadRequest $badRequest) {\n if ($badRequest->getCode() === 403) {\n throw new CrmException(\n \"Sorry, you don't have permission to update this stage.\",\n $badRequest->getCode(),\n $badRequest,\n );\n }\n\n $this->logger->warning('[HubSpot] Stage update failed', [\n 'dealId' => $crmObject->crm_provider_id,\n 'payload' => $payload,\n 'message' => $badRequest->getMessage(),\n ]);\n\n throw $badRequest;\n }\n }\n\n public function generateProviderUrl(string $providerId, string $objectType): ?string\n {\n $url = null;\n $baseUrl = 'https://app.hubspot.com/contacts/' . $this->config->crm_provider_id . '/';\n\n switch ($objectType) {\n case 'account':\n $url = $baseUrl . 'company/' . $providerId;\n\n break;\n\n case 'contact':\n $url = $baseUrl . 'contact/' . $providerId;\n\n break;\n\n case 'opportunity':\n $url = $baseUrl . 'deal/' . $providerId;\n\n break;\n\n case 'task':\n case 'activity':\n return null;\n\n // This should not be deep-linked as per JMNY-3934.\n //$url = $baseUrl.'tasks/list/view/all/?taskId='.$providerId;\n break;\n }\n\n return $url;\n }\n\n public function searchCalls(Carbon $from, Carbon $to, string $activityProvider): array\n {\n $this->logger->info('[HubSpot] Search calls', [\n 'from' => $from->format(self::LOG_DATE_FORMAT),\n 'to' => $to->format(self::LOG_DATE_FORMAT),\n ]);\n\n $calls = [];\n $page = 1;\n\n do {\n try {\n $payload = $this->payloadBuilder->generateGetCallsPayload($from, $to, $activityProvider, $page);\n $response = $this->client->getInstance()->getClient()->request(\n 'POST',\n self::CALLS_SEARCH_ENDPOINT,\n ['json' => ($payload)],\n );\n } catch (Exception $exception) {\n $this->logger->info('[HubSpot] Search calls failed', [\n 'from' => $from->format(self::LOG_DATE_FORMAT),\n 'to' => $to->format(self::LOG_DATE_FORMAT),\n 'reason' => $exception->getMessage(),\n ]);\n $response = null;\n }\n\n $responseResults = empty($response['results']) ? [] : $response['results'];\n $calls = array_merge($calls, $responseResults);\n $page++;\n } while (! empty($responseResults));\n\n return $calls;\n }\n\n public function searchCallsForPeriodByPage(Carbon $from, Carbon $to, int $page, bool $retry = true)\n {\n try {\n $payload = $this->payloadBuilder->generateSearchCallsByPeriodPayload($from, $to, $page);\n $response = $this->client->getInstance()->getClient()->request(\n 'POST',\n self::CALLS_SEARCH_ENDPOINT,\n ['json' => ($payload)],\n );\n } catch (Exception $exception) {\n $this->logger->info('[HubSpot] Search calls for period failed', [\n 'from' => $from->format(self::LOG_DATE_FORMAT),\n 'to' => $to->format(self::LOG_DATE_FORMAT),\n 'reason' => $exception->getMessage(),\n 'retry' => $retry,\n ]);\n\n if ($retry) {\n sleep(1);\n\n return $this->searchCallsForPeriodByPage($from, $to, $page, false);\n }\n $response = null;\n }\n\n return $response;\n }\n\n public function searchCallsForPeriod(Carbon $from, Carbon $to): Generator\n {\n $this->logger->info('[HubSpot] Search calls for period', [\n 'from' => $from->format(self::LOG_DATE_FORMAT),\n 'to' => $to->format(self::LOG_DATE_FORMAT),\n ]);\n\n $page = 1;\n\n do {\n $response = $this->searchCallsForPeriodByPage($from, $to, $page);\n\n $responseResults = empty($response['results']) ? [] : $response['results'];\n\n $associationContacts = $this->getAssociationDataForCollection($responseResults, 'calls', 'contacts');\n $associationCompanies = $this->getAssociationDataForCollection($responseResults, 'calls', 'companies');\n $associationDeals = $this->getAssociationDataForCollection($responseResults, 'calls', 'deals');\n\n foreach ($responseResults as $call) {\n $call['associations'] = [\n 'contacts' => $this->importAssociationData($call, $associationContacts),\n 'companies' => $this->importAssociationData($call, $associationCompanies),\n 'deals' => $this->importAssociationData($call, $associationDeals),\n ];\n\n yield $call;\n }\n $page++;\n } while (! empty($responseResults));\n }\n\n public function getCall(string $callId): array\n {\n $this->logger->info('[HubSpot] Get call', [\n 'call_id' => $callId,\n ]);\n\n $searchAttributes = $this->payloadBuilder->getSearchCallAttributes();\n $endpoint = sprintf(\n 'https://api.hubapi.com/crm/v3/objects/calls/%s',\n $callId,\n );\n\n try {\n $response = $this->client->getInstance()->getClient()->request(\n 'GET',\n $endpoint,\n [],\n sprintf(\n 'properties=%s&associations=contacts,companies,deals',\n implode(',', $searchAttributes),\n ),\n );\n } catch (Exception $exception) {\n $this->logger->info('[HubSpot] Get call failed', [\n 'call_id' => $callId,\n 'reason' => $exception->getMessage(),\n ]);\n $response = null;\n }\n\n return empty($response) ? [] : $response->toArray();\n }\n\n public function bulkAddPlaybackURLToDescription(array $crmUpdateData): array\n {\n $crmUpdateBatches = array_chunk($crmUpdateData, self::BATCH_UPDATE_LIMIT);\n\n $updatedCrmIds = [];\n\n foreach ($crmUpdateBatches as $crmBatch) {\n $payload = $this->payloadBuilder->generatePlaybackAddUrlBatchPayload($crmBatch);\n $updateSuccess = $this->bulkAddPlaybackURLToDescriptionRequest($payload);\n if ($updateSuccess) {\n $updatedCrmIds = array_merge($updatedCrmIds, array_column($crmBatch, 'crm_id'));\n }\n }\n\n return $updatedCrmIds;\n }\n\n private function bulkAddPlaybackURLToDescriptionRequest(array $payload, bool $retry = true): bool\n {\n try {\n $this->client->getNewInstance()->crm()->objects()->batchApi()->update('calls', $payload);\n\n return true;\n } catch (\\HubSpot\\Client\\Crm\\Objects\\ApiException $e) {\n $response = json_decode($e->getResponseBody(), true);\n $retryAfter =\n isset($response['policyName'])\n && $response['policyName'] == self::TEN_SECONDLY_ROLLING_POLICY\n ? self::TEN_SECONDLY_ROLLING_LIMIT\n : 1;\n } catch (Exception $e) {\n $retryAfter = 1;\n }\n\n $this->logger->warning('[HubSpot] Bulk add playback url to CRM failed', [\n 'reason' => $e->getMessage(),\n 'retry' => $retry,\n ]);\n\n if ($retry) {\n sleep($retryAfter);\n\n return $this->bulkAddPlaybackURLToDescriptionRequest($payload, false);\n }\n\n return false;\n }\n\n /**\n * Sometimes we have secondly rate limit error, then retry request after 1 second\n */\n public function searchCallByRecordingURLToken(string $playbackURLToken, bool $retry = true): array\n {\n $endpoint = 'https://api.hubapi.com/crm/v3/objects/calls/search';\n $payload = $this->payloadBuilder->generateSearchCallByTokenPayload($playbackURLToken);\n\n $this->logger->info('[HubSpot] CRM Search by playback URL token requested', [\n 'request' => $payload,\n ]);\n\n try {\n $response = $this->client->getInstance()->getClient()->request('POST', $endpoint, ['json' => ($payload)]);\n } catch (Exception $exception) {\n $this->logger->info('[HubSpot] Search by playback URL token failed', [\n 'playbackURLToken' => $playbackURLToken,\n 'reason' => $exception->getMessage(),\n 'retry' => $retry,\n ]);\n\n if ($retry) {\n sleep(1);\n\n return $this->searchCallByRecordingURLToken($playbackURLToken, false);\n }\n\n return [];\n }\n\n return empty($response['results']) ? [] : $response['results'][0];\n }\n\n /**\n * Generate transcription for the activity.\n */\n private function generateTranscription(Activity $activity): string\n {\n if (! $this->config->store_transcript) {\n // If sending transcription to activity toggle is disabled\n return '';\n }\n\n $transcriptionSegments = $this->transcriptionService->findTranscriptionByActivity($activity);\n\n if ($transcriptionSegments->isEmpty()) {\n return '';\n }\n\n $transcription = sprintf(\n '<p><strong>Transcript for %s</strong></p><p></p>',\n $activity->title ?? $activity->activity_title,\n );\n\n $roomOwnerParticipant = $activity->findParticipantRoomOwner();\n $roomOwnerParticipantId = $roomOwnerParticipant !== null\n ? $roomOwnerParticipant->getId()\n : null;\n\n\n $transcription .= $transcriptionSegments\n ->map(static function (array $transcriptionSegment) use ($roomOwnerParticipantId): string {\n $isOrganiser = $roomOwnerParticipantId === $transcriptionSegment['participantId']\n && $roomOwnerParticipantId !== null;\n $transcriptColor = $isOrganiser ? '#000000' : '#f0415a';\n\n return sprintf(\n '<span style=\"color: %s;\">%s | </span>%s',\n $transcriptColor,\n $transcriptionSegment['formattedStartsAt'],\n $transcriptionSegment['transcript'],\n );\n })\n ->implode('<br />');\n\n return $transcription;\n }\n\n /**\n * @param array<array{\n * id: string,\n * label: string,\n * value?: string,\n * }> $options\n *\n * @return FieldData[]\n */\n private function importOptions(Field $field, array $options): array\n {\n $fieldValues = [];\n $values = [];\n $sequence = 0;\n\n foreach ($options as $option) {\n $values[] = [\n 'value' => $option['value'] ?? $option['id'],\n 'label' => substr($option['label'], 0, 255),\n 'sequence' => $sequence++,\n ];\n }\n\n $fieldsToPurge = $field->values()->get()->pluck('value')->toArray();\n\n foreach ($values as $value) {\n $value['value'] = substr($value['value'], 0, 255);\n $fieldValues[] = $field->values()->updateOrCreate([\n 'value' => $value['value'],\n ], $value);\n\n // Remove this value from the ones we are going to purge.\n if (($key = array_search($value['value'], $fieldsToPurge, false)) !== false) {\n unset($fieldsToPurge[$key]);\n }\n }\n\n // Delete the old values that are no longer used.\n $field->values()->whereIn('value', $fieldsToPurge)->delete();\n\n return $fieldValues;\n }\n\n public function saveTranscriptionSummaryAsNote(\n ActivityContract $activity,\n string $title,\n string $body,\n ?string $objectId,\n ?NoteObject $noteObject = null,\n ): ?string {\n if ($noteObject === null || $objectId === null) {\n return null;\n }\n\n /** @var User $user */\n $user = $activity->getUser();\n\n $profile = $this->assignCrmOwner($user, $activity);\n if (! $profile instanceof Profile) {\n return null;\n }\n\n $timestamp = Carbon::now($user->getTimezone())->getTimestamp() * 1000;\n $engagement = [\n 'active' => true,\n 'ownerId' => $profile->getAttribute('crm_provider_id'),\n 'timestamp' => $timestamp,\n 'type' => 'NOTE',\n ];\n\n // Truncate Notes with max notes length because transcription text could be very long.\n $body = mb_strimwidth($body, 0, self::ENGAGEMENT_BODY_MAX_LENGTH);\n $metadata = [\n 'body' => $body,\n ];\n\n $associations = $this->convertActivityAssociations($activity);\n\n try {\n $hsActivityId = $this->client->createNote(\n body: $body,\n ownerId: $profile->getCrmProviderId(),\n timestamp: $timestamp,\n objectId: $objectId,\n noteObject: $noteObject,\n );\n\n $this->logCrmEngagementManipulation(self::ACTION_CREATE, $engagement, $metadata, $associations);\n\n $this->logger->info('[HubSpot] Saving Transcription Summary as Note', [\n 'activity' => $activity->getUuid(),\n 'crmActivity' => $hsActivityId,\n ]);\n\n return $hsActivityId;\n } catch (Exception $e) {\n Sentry::captureException($e);\n }\n\n return null;\n }\n\n public function attachSummaryToActivity(ActivityContract $activity, string $summaryTitle, string $summaryContents): bool\n {\n $this->logger->info('[HubSpot] Attaching summary to activity', [\n 'activity' => $activity->getUuid(),\n 'summary_content' => $summaryContents,\n ]);\n\n if (! $activity instanceof Activity) {\n throw new InvalidArgumentException('Expected instance of Activity');\n }\n\n $summary = '<p><strong>' . $summaryTitle . '</strong></p>';\n $summary .= '<p>' . $summaryContents . '</p>';\n $metadata = $this->buildMetadataForSummaryUpdate($activity, $summary);\n\n try {\n $type = $this->matchActivityEngagementType($activity);\n $engagement = ['type' => $type];\n\n $this->client->updateEngagement($activity->getCrmProviderId(), $engagement, $metadata);\n } catch (Exception $e) {\n $this->logger->warning('[HubSpot] Update summary failed', [\n 'activity' => $activity->getUuid(),\n 'reason' => $e->getMessage(),\n ]);\n\n return false;\n }\n\n $this->logCrmEngagementManipulation(\n self::ACTION_UPDATE,\n ['crmId' => $activity->getCrmProviderId()],\n $metadata,\n );\n\n return true;\n }\n\n private function buildMetadataForSummaryUpdate(Activity $activity, string $summary): array\n {\n $descriptionField = $activity->getType() === Activity::TYPE_CONFERENCE ? 'internalMeetingNotes' : 'body';\n $engagement = $this->client->getEngagementData($activity->getCrmProviderId());\n // Meeting without internalMeetingNotes might mean it just does not have any notes;\n $description = $engagement['metadata'][$descriptionField] ?? null;\n\n if (empty($description)) {\n $data = $summary;\n } else {\n // avoid playbook url link to Jiminny being sent twice in the activity description\n $targetUrl = PlaybackUrlBuilder::build($activity);\n\n if (str_contains($description, $targetUrl)) {\n $jiminnyUrl = '<p><a href=\"' . $targetUrl . '\" title=\"Play at Jiminny\">Play at Jiminny</a></p>';\n $summary = str_replace($jiminnyUrl, '', $summary);\n\n $this->logger->info('[HubSpot] Summary modified', [\n 'activity' => $activity->getUuid(),\n 'target_url' => $jiminnyUrl,\n 'modified_summary_content' => $summary,\n ]);\n }\n\n $data = $description . '<p></p>' . $summary;\n }\n\n return [\n $descriptionField => $data,\n ];\n }\n\n public function fetchAndAssociateRelatedActivity(Activity $activity): ?Activity\n {\n return $this->syncRelatedActivityManager->fetchAndAssociateRelatedActivity($activity);\n }\n\n public function fetchRelatedActivity(Activity $activity): array\n {\n return [];\n }\n\n public function getDealsInBulk(array $dealIds): array\n {\n $payload = $this->payloadBuilder->getDealsInBulkPayload($dealIds);\n\n return $this->client->getPaginatedData($payload, 'deals');\n }\n\n /**\n * Extract deal IDs from HubSpot search response.\n *\n * @param array $hubspotResponse The raw HubSpot search API response.\n * @param bool $includeArchived Whether to include archived deals (default: false).\n *\n * @return string[] Array of deal IDs as strings.\n */\n public function extractDealIds(array $hubspotResponse, bool $includeArchived = false): array\n {\n if (empty($hubspotResponse['results'])) {\n return [];\n }\n\n return array_values(\n array_map(\n fn ($deal) => $deal['id'],\n array_filter(\n $hubspotResponse['results'],\n fn ($deal) => $includeArchived || empty($deal['archived'])\n )\n )\n );\n }\n\n public function matchActivityEngagementType(Activity $activity): string\n {\n return match ($activity->getType()) {\n Activity::TYPE_CONFERENCE => self::TYPE_MEETING,\n Activity::TYPE_SOFTPHONE, Activity::TYPE_SOFTPHONE_INBOUND => self::TYPE_CALL,\n default => self::TYPE_NOTE,\n };\n }\n\n private function assignCrmOwner(User $user, ActivityContract $activity): ?Profile\n {\n $profile = $user->getProfile();\n if ($profile instanceof Profile) {\n return $profile;\n }\n\n $this->logger->info('[HubSpot] Unable to save summary. No profile', [\n 'activity' => $activity->getUuid(),\n ]);\n\n return null;\n }\n\n private static function getDealsPipelinesEndpoint(): string\n {\n return self::API_URL . self::ENDPOINT_PIPELINES . self::PIPELINE_OBJECT_TYPE_DEALS;\n }\n\n public function verifyTaskExists(Activity $activity): bool\n {\n $crmProviderId = $activity->getCrmProviderId();\n $cacheKey = \"crm_task_exists:{$this->config->getId()}:$crmProviderId\";\n\n return Cache::remember($cacheKey, self::TASK_VERIFICATION_CACHE_TTL, function () use ($crmProviderId) {\n try {\n $engagement = $this->client->getEngagementData($crmProviderId);\n\n return ! empty($engagement);\n } catch (HttpNotFoundException|BadRequest) {\n // Engagement not found in CRM - this is expected and permanent\n $this->logger->info('[Hubspot] Engagement not found during verification', [\n 'engagement_id' => $crmProviderId,\n 'config_id' => $this->config->getId(),\n ]);\n\n return false;\n }\n // Let other exceptions (network errors, rate limits, etc.) bubble up for retry\n });\n }\n}","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCell","text":"367","depth":6,"role_description":"cell"},{"role":"AXStaticText","text":"367","depth":7,"role_description":"text"},{"role":"AXTextArea","text":"3230","depth":8,"bounds":{"left":0.0,"top":0.0,"width":0.2048611,"height":0.024444444},"value":"3230","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCell","text":"fa0cf643-d30e-43b8-ab3d-1fe18254609c","depth":6,"role_description":"cell"},{"role":"AXStaticText","text":"fa0cf643-d30e-43b8-ab3d-1fe18254609c","depth":7,"role_description":"text"},{"role":"AXTextArea","text":"Editor","depth":8,"role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
1187659190810667004
|
-1042077963944585113
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Sync Changes
Hide This Notification
Code changed:
Hide
8
42
1
33
1
Previous Highlighted Error
Next Highlighted Error
<?php
namespace Jiminny\Services\Crm\Hubspot;
use Carbon\Carbon;
use Exception;
use Generator;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\Cache;
use InvalidArgumentException;
use Jiminny\Contracts\Repositories\TeamRepository;
use Jiminny\Contracts\Services\Crm\ClientInterface;
use Jiminny\Contracts\Services\Crm\FetchRelatedActivityInterface;
use Jiminny\Contracts\Services\Crm\LayoutManagementInterface;
use Jiminny\Contracts\Services\Crm\MatchCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\Provider\HubspotInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityLookupInterface;
use Jiminny\Contracts\Services\Crm\RemoteEntityManipulationInterface;
use Jiminny\Contracts\Services\Crm\SavePlaybackLinkToCrmInterface;
use Jiminny\Contracts\Services\Crm\SendSummaryToCrmInterface;
use Jiminny\Contracts\Services\Crm\SettingsInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmEntitiesInterface;
use Jiminny\Contracts\Services\Crm\SyncCrmMetadataInterface;
use Jiminny\Contracts\Services\Crm\VerifyTaskExistsInterface;
use Jiminny\Exceptions\CrmException;
use Jiminny\Exceptions\HttpNotFoundException;
use Jiminny\Jobs\Crm\NoteObject;
use Jiminny\Models\Account;
use Jiminny\Models\Activity;
use Jiminny\Models\Contact;
use Jiminny\Models\Contracts\ActivityContract;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Models\Crm\Field;
use Jiminny\Models\Crm\FieldData;
use Jiminny\Models\Crm\Layout;
use Jiminny\Models\Crm\Profile;
use Jiminny\Models\Lead;
use Jiminny\Models\Opportunity;
use Jiminny\Models\Participant;
use Jiminny\Models\Playbook;
use Jiminny\Models\SocialAccount;
use Jiminny\Models\Stage;
use Jiminny\Models\User;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Repositories\Crm\FieldRepository;
use Jiminny\Repositories\Crm\ProfileRepository;
use Jiminny\Repositories\ParticipantRepository;
use Jiminny\Services\Avatar\ProspectPhotoPathService;
use Jiminny\Services\Crm\BaseService;
use Jiminny\Services\Crm\Hubspot\Actions\SyncArchivedProfilesAction;
use Jiminny\Services\Crm\Hubspot\Fields\ValueNormalizer;
use Jiminny\Services\Crm\Hubspot\ServiceTraits\OpportunitySyncTrait;
use Jiminny\Services\Crm\Hubspot\ServiceTraits\SyncCrmEntitiesTrait;
use Jiminny\Services\Crm\Hubspot\ServiceTraits\SyncFieldsTrait;
use Jiminny\Services\Crm\Hubspot\ServiceTraits\WriteCrmTrait;
use Jiminny\Services\Crm\MatchDomainByEmailInterface;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Services\Crm\ResolveCompanyNameByEmailTrait;
use Jiminny\Utils\PlaybackUrlBuilder;
use Sentry;
use SevenShores\Hubspot\Exceptions\BadRequest;
use Throwable;
use UnexpectedValueException;
/**
* @phpstan-type CrmFieldDefinition array{
* name: string,
* label: string,
* description: string,
* type: string,
* fieldType: string,
* hidden: bool,
* showCurrencySymbol: bool,
* options: array<array{
* id: string,
* label: string,
* value?: string,
* }
*/
class Service extends BaseService implements
HubspotInterface,
SyncCrmEntitiesInterface,
SyncCrmMetadataInterface,
SendSummaryToCrmInterface,
MatchDomainByEmailInterface,
SavePlaybackLinkToCrmInterface,
RemoteEntityManipulationInterface,
FetchRelatedActivityInterface,
LayoutManagementInterface,
SettingsInterface,
MatchCrmEntitiesInterface,
RemoteEntityLookupInterface,
VerifyTaskExistsInterface
{
use ResolveCompanyNameByEmailTrait;
use SyncCrmEntitiesTrait;
use WriteCrmTrait;
use SyncFieldsTrait;
use OpportunitySyncTrait;
private const int ENGAGEMENT_BODY_MAX_LENGTH = 65536;
private const string LOG_DATE_FORMAT = 'Y-m-d H:i:s';
private const int BATCH_UPDATE_LIMIT = 100;
private const string TEN_SECONDLY_ROLLING_POLICY = 'TEN_SECONDLY_ROLLING';
private const int TEN_SECONDLY_ROLLING_LIMIT = 10;
private const string CALLS_SEARCH_ENDPOINT = '[URL_WITH_CREDENTIALS] ClientInterface|Client
*/
protected $client;
protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
protected CrmEntityRepository $crmEntityRepository;
protected ProspectPhotoPathService $prospectPhotoPathService;
private SyncFieldAction $syncFieldAction;
private PayloadBuilder $payloadBuilder;
private SyncRelatedActivityManager $syncRelatedActivityManager;
private SyncArchivedProfilesAction $syncArchivedProfilesAction;
private WebhookSyncBatchProcessor $batchProcessor;
public function __construct(
Client $client,
SyncFieldAction $syncFieldAction,
PayloadBuilder $payloadBuilder,
ProspectPhotoPathService $prospectPhotoPathService,
SyncArchivedProfilesAction $syncArchivedProfilesAction,
WebhookSyncBatchProcessor $batchProcessor,
) {
parent::__construct();
$this->client = $client;
$this->syncFieldAction = $syncFieldAction;
$this->prospectPhotoPathService = $prospectPhotoPathService;
$this->payloadBuilder = $payloadBuilder;
$this->syncArchivedProfilesAction = $syncArchivedProfilesAction;
$this->batchProcessor = $batchProcessor;
$this->opportunitySyncStrategyResolver = app(OpportunitySyncStrategyResolver::class, [
'client' => $this->client,
]);
$this->syncRelatedActivityManager = app(SyncRelatedActivityManager::class, [
'client' => $this->client,
'payloadBuilder' => $this->payloadBuilder,
'logger' => $this->logger,
]);
$this->crmEntityRepository = app(CrmEntityRepository::class);
$this->dealFieldsService = app(DealFieldsService::class);
}
public function getDisplayName(): string
{
return 'HubSpot';
}
protected function getOAuthAccount(User $user): ?SocialAccount
{
// In this case, the Account Owner is always the connection for any API operations.
$owner = $user->team->owner;
return $owner->getSocialAccount(SocialAccount::PROVIDER_HUBSPOT);
}
public function getClient(): Client
{
/** @var Client */
return $this->client;
}
/**
* Convert raw field data into a format compatible with CRM APIs.
*
* @param bool $internal Direction of the conversion.
* True is pulling from CRM, false normalize before sending to CRM.
*/
public function normalizeValue(string $fieldType, string $fieldValue, bool $internal = false): string
{
return ValueNormalizer::normalize(
fieldType: $fieldType,
fieldValue: $fieldValue,
isInbound: $internal,
);
}
public function getRecordTypes(string $crmObject): array
{
return [];
}
/**
* @inheritdoc
*/
public function getDefaultFields(string $activityType): array
{
$fields = [];
if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {
$defaultFields = FieldDefinitions::defaultTaskFields();
// This lazy creates these fields if not already setup.
foreach ($defaultFields as $defaultField) {
$fields[] = $this->config->fields()->firstOrCreate($defaultField);
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function getDefaultActivityField(string $activityType): Field
{
/** @var Field $activityField */
$activityField = $this->config->fields()->where([
'crm_provider_id' => 'activityType',
'object_type' => $activityType,
])->first();
return $activityField;
}
/**
* @inheritdoc
*/
public function getSupportedPlaybookTypes(): array
{
return [Playbook::ACTIVITY_TYPE_TASK];
}
/**
* @inheritdoc
*/
public function getDefaultActivityLayoutFields(string $activityType, string $layoutType): array
{
$fields = [];
if ($activityType === Playbook::ACTIVITY_TYPE_TASK) {
// Outcome should always be provided calls/meetings.
$fieldData = [
[
'crm_provider_id' => $layoutType === Layout::TYPE_SOFTPHONE_SUMMARY ? 'disposition' : 'meetingOutcome',
'object_type' => Field::OBJECT_TASK,
],
];
foreach ($fieldData as $data) {
$field = $this->config->fields()->where($data)->first();
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
}
return $fields;
}
public function getDealInsightsFields(): array
{
return FieldDefinitions::dealInsightsFields();
}
protected function getDefaultFollowupLayoutFields(string $activityType): array
{
$fields = [];
$fieldRepo = app(FieldRepository::class);
$fieldData = FieldDefinitions::followupFieldsFilter();
foreach ($fieldData as $data) {
$field = $fieldRepo->findOneConfigurationFieldByProperties($this->config, $data);
// Only add the field if it is created, which it should be.
if ($field) {
$fields[] = $field;
}
}
return $fields;
}
/**
* @inheritdoc
*/
public function syncField(Field $field): void
{
switch ($field->object_type) {
case Field::OBJECT_ACCOUNT:
$crmField = $this->client->getInstance()->companyProperties()->get($field->crm_provider_id);
break;
case Field::OBJECT_CONTACT:
$crmField = $this->client->getInstance()->contactProperties()->get($field->crm_provider_id);
break;
case Field::OBJECT_OPPORTUNITY:
$crmField = $this->client->getInstance()->dealProperties()->get($field->crm_provider_id);
break;
case Field::OBJECT_TASK:
$this->syncSingleTaskField($field);
return;
default:
return;
}
$this->syncFieldAction->execute($field, $crmField->toArray());
}
/**
* @param array<array{
* id:string,
* label:string,
* value?:string
* }> $options
*
* @throws CrmException
*
* @return FieldData[]
*
*/
public function importPicklistValues(
Field $field,
array $options = [['id' => '', 'label' => '', 'value' => '']],
): array {
if (! empty($options[0]['id']) || ! empty($options[0]['value'])) {
// We already have the options, no need to fetch them again
return $this->importOptions($field, $options);
}
$options = [];
switch ($field->getObjectType()) {
case Field::OBJECT_ACCOUNT:
$options = $this->getClient()->fetchPropertyOptions('company', $field->getCrmProviderId());
break;
case Field::OBJECT_CONTACT:
$options = $this->getClient()->fetchPropertyOptions('contact', $field->getCrmProviderId());
break;
case Field::OBJECT_OPPORTUNITY:
// Hubspot has different endpoint for stages
$options = $this->getClient()->fetchOpportunityFieldOptions($field);
break;
case Field::OBJECT_TASK:
if ($field->getCrmProviderId() === 'disposition') {
$options = $this->getClient()->fetchDispositionFieldOptions();
} elseif (in_array($field->getCrmProviderId(), ['meetingOutcome', 'activityType'])) {
$options = $this->getClient()->fetchMeetingOutcomeFieldOptions($field);
}
break;
default:
$this->logger->warning('Invalid object type', [
'object_type' => $field->getObjectType(),
'field_id' => $field->getId(),
]);
throw new CrmException('Invalid object type');
}
return $this->importOptions($field, $options);
}
/**
* Gets business processes.
*/
public function importBusinessProcesses(): void
{
// Taken care of in importStages().
}
/**
* Gets business process stages.
*/
public function importBusinessProcessStages(BusinessProcess $businessProcess): void
{
// Taken care of in importStages().
}
/**
* Gets record types.
*/
public function importRecordTypes(): void
{
// Taken care of in importStages().
}
/**
* @inheritdoc
*/
public function importStages(?array $types = null, ?string $missingStageName = null): ?Stage
{
$missingStage = null;
try {
// Use the HubSpot API client instead of the SDK crmPipelines() method
$endpoint = self::getDealsPipelinesEndpoint();
$pipelinesResponse = $this->client->getInstance()->getClient()->request('GET', $endpoint);
$pipelines = $pipelinesResponse->data->results;
} catch (RequestException|BadRequest $exception) {
throw $exception;
}
foreach ($pipelines as $pipeline) {
$stages = [];
// We create a business process to contain the pipeline, and store all stages against it.
$p = ResponseNormalize::normalizePipeline($pipeline);
// Create/update business process for this pipeline
$businessProcess = $this->config->businessProcesses()->updateOrCreate([
'crm_provider_id' => $p['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($p['label'], 0, 150),
'type' => BusinessProcess::TYPE_OPPORTUNITY,
'is_selectable' => $p['active'],
]);
// A record type is really a clone of the business process, used to store which record uses which pipeline.
// Create/update record type clone
$this->config->recordTypes()->updateOrCreate([
'crm_provider_id' => $p['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($p['label'], 0, 150),
'is_selectable' => $p['active'],
'business_process_id' => $businessProcess->id ?? null,
]);
// Stages
foreach ($p['stages'] as $dealStage) {
$s = ResponseNormalize::normalizeDealStage($dealStage);
// Upsert all stages for the team.
$stage = $this->config->stages()->updateOrCreate([
'crm_provider_id' => $s['id'],
], [
'team_id' => $this->team->id,
'name' => mb_strimwidth($s['label'], 0, 50),
'label' => mb_strimwidth($s['label'], 0, 191),
'type' => Stage::TYPE_OPPORTUNITY,
'sequence' => $s['displayOrder'],
'is_selectable' => $s['active'],
'probability' => $s['probability'] * 100,
]);
if ($missingStageName && $missingStageName === $s['id']) {
$missingStage = $stage;
}
$stages[] = $stage->id;
}
$businessProcess->stages()->sync($stages);
}
return $missingStage;
}
/**
* @inheritdoc
*/
public function syncOrganization(): void
{
try {
$endpoint = '[URL_WITH_CREDENTIALS]
*/
public function find(string $name, array $scopes): array
{
$count = $this->limit ?? 20;
$offset = $this->offset ?? 0;
/** @var array<int, array<string, mixed>> */
return Cache::remember(
key: $this->team->getId() . $name . $count . $offset,
ttl: 300,
callback: function () use ($name, $offset, $count): array {
$data = [];
// Use the new V3 API to find contacts based on additional fields.
foreach (['companies', 'contacts'] as $objectType) {
$endpoint = '[URL_WITH_CREDENTIALS]
*/
public function findOpportunities(?string $crmAccountId, ?string $crmContactId, ?int $userId = null): array
{
$data = [];
$ownerData = [];
$ownerId = null;
if ($crmAccountId === null) {
return $data;
}
if ($userId) {
$profileRepository = app(ProfileRepository::class);
$profile = $profileRepository->findProfileByUserId($this->config, $userId);
$ownerId = $profile instanceof Profile ? $profile->getCrmProviderId() : null;
}
$closedStages = $this->getClosedDealStages();
$payload = $this->payloadBuilder->generateOpportunitiesSearchPayload(
$this->config,
$crmAccountId,
$closedStages,
);
$results = $this->client->getPaginatedData($payload, 'deals');
foreach ($results['results'] as $object) {
$properties = $object['properties'];
$amount = null;
if (empty($properties['amount']) === false) {
$currency = $properties['deal_currency_code'] ?? $this->config->default_currency;
// Values can contain commas and any junk so strip them.
$value = (float) preg_replace('/[^\d.]/', '', $properties['amount']);
$amount = formatCurrency($value, $currency);
}
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', $properties['pipeline'])
->first();
if ($businessProcess === null) {
// Import it.
$stage = $this->importStages([Stage::TYPE_OPPORTUNITY], $properties['dealstage']);
$businessProcess = $this->config
->businessProcesses()
->where('crm_provider_id', $properties['pipeline'])
->first();
} else {
$stage = $businessProcess
->stages()
->where('crm_provider_id', $properties['dealstage'])
->where('type', Stage::TYPE_OPPORTUNITY)
->first();
if ($stage === null) {
// Import it.
$stage = $this->importStages(null, $properties['dealstage']);
}
}
$recordType = null;
if ($businessProcess) {
$recordType = $businessProcess->recordTypes()->first();
}
$isWon = in_array($properties['dealstage'], $closedStages['won']);
$isLost = in_array($properties['dealstage'], $closedStages['lost']);
$record = [
'crmId' => $object['id'],
'name' => $properties['dealname'] ?? 'Unknown Deal',
'value' => $amount,
'won' => $isWon,
'closed' => $isWon || $isLost,
'stage' => [
'id' => $stage?->getUuid() ?? '',
'name' => $stage?->getName() ?? '',
],
];
if ($recordType) {
$record += [
'recordType' => [
'id' => $recordType->id_string,
'name' => $recordType->name,
],
];
}
if ($ownerId && isset($properties['hubspot_owner_id']) && $properties['hubspot_owner_id'] === $ownerId) {
$ownerData[] = $record;
}
$data[] = $record;
}
if (! empty($ownerData)) {
return $ownerData;
}
return $data;
}
/**
* @inheritdoc
*/
public function getTasks(?string $objectType, string $objectId, ?string $opportunityId): array
{
$data = [];
switch ($objectType) {
case 'contact':
$hsObject = 'contact';
break;
case 'account':
$hsObject = 'company';
break;
default:
// This is a hack to prioritise and override a contact/company with a deal.
if ($opportunityId) {
$hsObject = 'deal';
$objectId = $opportunityId;
} else {
throw new InvalidArgumentException('Object type not supported.');
}
}
$engagementTypes = ['meetings', 'tasks'];
foreach ($engagementTypes as $engagementType) {
$payload = $this->payloadBuilder->getLinkToTaskPayload($hsObject, $objectId, $engagementType);
$this->logger->info('[HubSpot] CRM Search requested', [
'request' => $payload,
]);
$engagements = $this->client->getPaginatedData($payload, $engagementType);
foreach ($engagements['results'] as $engagement) {
if ($engagementType == 'meetings') {
$title = $engagement['properties']['hs_meeting_title'] ?? 'Scheduled meeting';
} elseif ($engagementType == 'tasks') {
$title = $engagement['properties']['hs_task_subject'];
} else {
$title = 'Scheduled meeting';
}
$data[] = [
'crmId' => $engagement['id'],
'subject' => $title,
'due' => $engagement['properties']['hs_timestamp'],
'type' => $engagement['properties']['hs_activity_type'] ?? null,
];
}
}
usort($data, function ($item1, $item2) {
return $item2['due'] <=> $item1['due'];
});
return $data;
}
/**
* @inheritdoc
*/
public function getEvents(string $objectType, string $objectId, ?string $opportunityId): array
{
return [];
}
/**
* Try to find CRM Objects using email address
*
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
* }
*/
public function matchExactlyByEmail(string $email, ?int $userId = null): ?array
{
$contactProperties = [
'email',
'firstname',
'lastname',
'country',
'phone',
'mobilephone',
'jobtitle',
'hubspot_owner_id',
'associatedcompanyid',
'photo',
];
$contact = null;
$account = null;
try {
$hsContact = $this->getClient()->getContactByEmail($email, $contactProperties);
if ($hsContact) {
$contact = $this->importContact($hsContact);
$account = $contact->account;
}
$data = $this->convertCrmData($contact, $account, $userId);
return ! empty(array_filter($data)) ? $data : null;
} catch (BadRequest $e) {
$this->logger->warning('[HubSpot] Search failed', [
'team_id' => $this->team->getId(),
'search_identifier' => $email,
'reason' => $e->getMessage(),
]);
}
return null;
}
public function getDomain(string $email): ?string
{
return $this->getDomainFromEmail($email);
}
/**
* Try to find CRM objects using domain name of the email address
*
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
* }
*/
public function matchByDomain(string $domain, ?int $userId = null): ?array
{
$companyName = $domain;
// Try to find a company matching their email domain.
$companyProperties = [
'country',
'phone',
'name',
'hs_avatar_filemanager_key',
'industry',
'hubspot_owner_id',
'domain',
];
try {
$hsAccounts = $this->client
->getInstance()
->companies()
->searchByDomain($companyName, $companyProperties);
} catch (Throwable $e) {
$this->logger->info('[HubSpot] Search failed', [
'error' => $e->getMessage(),
'domain' => $domain,
]);
return null;
}
$account = null;
// If there are multiple accounts, don't guess, we'll ask later.
if (\count($hsAccounts->data->results) === 1) {
// Persist this remote object.
$account = $this->syncAccount($hsAccounts->data->results[0]->companyId);
}
$data = $this->convertCrmData(null, $account, $userId);
return ! empty(array_filter($data)) ? $data : null;
}
/**
* @return array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
* }
*/
protected function convertCrmData(?Contact $contact, ?Account $account, ?int $userId = null): array
{
$countryCode = null;
if ($contact && $contact->country_code) {
$countryCode = $contact->country_code;
} elseif ($account && $account->country_code) {
$countryCode = $account->country_code;
}
try {
$hsOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact ? $contact->crm_provider_id : null,
$userId
);
} catch (Exception $e) {
$hsOpportunities = [];
}
// If there are multiple opportunities, don't guess, we'll ask later.
$opportunity = null;
$stage = null;
if (! empty($hsOpportunities)) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($hsOpportunities[0]['crmId']);
$stage = $opportunity?->getStage();
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
protected function getCacheKey(string $object, ?int $userId = null): ?string
{
$key = $this->team->getId() . $object;
$keySuffix = $this->getOwnerKeySuffix($userId);
return $key . $keySuffix;
}
private function getOwnerKeySuffix(?int $userId = null): string
{
return $userId === null ? '' : (string) $userId;
}
/**
* @return null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
*}
*/
public function matchByPhone(string $phone, ?string $rawPhoneNumber = null, ?int $userId = null): ?array
{
if (str_contains($phone, '**')) {
return null;
}
// trim all whitespaces if present so the lookup doesn't fail
$phone = str_replace(' ', '', $phone);
// Check if the user is internal.
if ($this->isPhoneNumberOfTeamMember($phone)) {
return null;
}
$response = $this->searchForPhoneNumber($phone);
if (empty($response)) {
return null;
}
// This would ideally importContact instead but the response type differs.
$contact = $this->findAndSyncContact($response['results'][0]['id']);
if (! $contact instanceof Contact) {
return null;
}
$account = $contact->account;
$countryCode = $contact->country_code ?? $account->country_code ?? null;
try {
$hsOpportunities = $this->findOpportunities(
$account?->crm_provider_id,
$contact->crm_provider_id,
$userId
);
} catch (Exception $e) {
$hsOpportunities = [];
}
$opportunity = null;
$stage = null;
try {
if (! empty($hsOpportunities)) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($hsOpportunities[0]['crmId']);
$stage = $opportunity?->getStage();
}
} catch (Exception $e) {
$this->logger->debug('[HubSpot] Opportunity failed to sync.', [
'reason' => $e->getMessage(),
]);
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
}
private function isPhoneNumberOfTeamMember(string $phone): bool
{
$teamRepository = app(TeamRepository::class);
$user = $teamRepository->findTeamMemberByPhone($this->team, $phone);
if ($user instanceof User) {
return true;
}
return false;
}
private function findAndSyncContact(string $crmId): ?Contact
{
try {
return $this->syncContact($crmId);
} catch (Exception $exception) {
$this->logger->info('[HubSpot] Phone match failed', [
'reason' => $exception->getMessage(),
]);
return null;
}
}
private function hasResults(array $response): bool
{
return isset($response['total']) && is_numeric($response['total']) && $response['total'] > 0;
}
private function searchForPhoneNumber(string $phone): array
{
// Normalizes the provided phone number for the API search.
$normalizedPhone = $this->normalizePhoneNumber($phone);
$payload = $this->payloadBuilder->generatePhoneSearchPayload($normalizedPhone);
$this->logger->info('[HubSpot] Phone match search triggered', [
'phone' => $phone,
'normalizedPhone' => $normalizedPhone,
'payload' => $payload,
]);
$response = $this->handlePhoneSearchRequest($normalizedPhone, $payload);
if (! $this->hasResults($response)) {
$nationalPhone = preg_replace('/\D/', '', phone_national(null, $phone));
$payload = $this->payloadBuilder->generatePhoneSearchPayload($nationalPhone);
$this->logger->info('[HubSpot] Phone match national number search triggered', [
'phone' => $phone,
'nationalPhone' => $nationalPhone,
'payload' => $payload,
]);
$response = $this->handlePhoneSearchRequest($phone, $payload);
}
if (! $this->hasResults($response)) {
$payload = $this->payloadBuilder->generatePhoneSearchPayload($normalizedPhone, true);
$this->logger->info('[HubSpot] Phone match alternative search triggered', [
'phone' => $phone,
'normalizedPhone' => $normalizedPhone,
'payload' => $payload,
]);
$response = $this->handlePhoneSearchRequest($phone, $payload);
}
return $this->hasResults($response) ? $response : [];
}
private function handlePhoneSearchRequest(string $phone, array $payload): array
{
$endpoint = '[URL_WITH_CREDENTIALS] null|array{
* Lead|null,
* Account|null,
* Opportunity|null,
* Contact|null,
* Stage|null,
* string|null
* }
*/
public function matchByName(string $name, ?int $userId = null): ?array
{
// Don't waste time searching for single character strings.
if (\strlen($name) <= 1) {
return null;
}
$cacheKey = $this->getCacheKey($name, $userId);
$result = Cache::remember($cacheKey, 60, function () use ($name, $userId) {
$payload = $this->payloadBuilder->generateSearchContactsByNamePayload(
$name,
$this->getContactFields()
);
$hsContacts = $this->client->getPaginatedData($payload, 'contact');
if (empty($hsContacts['results'])) {
return false;
}
$contact = $this->importContact($hsContacts['results'][0]);
if ($contact === null) {
return false;
}
$account = $contact->account;
$countryCode = $contact->country_code ?? $account->country_code ?? null;
try {
$hsOpportunities = $this->findOpportunities(
$account ? $account->crm_provider_id : null,
$contact->crm_provider_id,
$userId
);
} catch (Exception $e) {
$hsOpportunities = [];
}
$opportunity = null;
$stage = null;
if (! empty($hsOpportunities)) {
// Persist this remote object.
$opportunity = $this->syncOpportunity($hsOpportunities[0]['crmId']);
$stage = $opportunity?->getStage();
}
return [
null,
$account,
$opportunity,
$contact,
$stage,
$countryCode,
];
});
return is_array($result) ? $result : null;
}
private function convertActivityAssociations(Activity $activity): array
{
return [
'contactIds' => $this->getParticipantsIds($activity),
'companyIds' => $activity->hasAccount() ? [$activity->account->crm_provider_id] : [],
'dealIds' => $activity->hasOpportunity() ? [$activity->opportunity->crm_provider_id] : [],
'ownerIds' => [],
];
}
private function getParticipantsIds(Activity $activity): array
{
$attendees = [];
$participantRepository = app(ParticipantRepository::class);
$participants = $participantRepository->getParticipantsWhoEnteredMeeting($activity);
foreach ($participants as $participant) {
if ($participant->user_id || $participant->isCoach()) {
continue;
}
$contact = $participant->contact()->first();
if ($contact && $contact->crm_provider_id) {
$attendees[] = $contact->crm_provider_id;
} else {
if (! empty($participant->name)) {
$attendeeData = $this->fetchMissingAttendeeInfo($participant);
}
if (! empty($attendeeData['id'])) {
$attendees[] = $attendeeData['id'];
}
}
}
if ($activity->hasContact()) {
$attendees[] = $activity->contact->crm_provider_id;
}
return array_unique($attendees);
}
private function fetchMissingAttendeeInfo(Participant $participant): array
{
// Check if we need to look inside an account context.
$activity = $participant->getActivity();
$companyId = $activity->hasAccount() ? $activity->getAccount()->crm_provider_id : null;
// First check the local data.
/** @var Contact[] $contacts */
$contacts = $this->team->contacts()
->with('account')
->where('name', $participant->name)
->whereNotNull('email')
->get();
foreach ($contacts as $contact) {
// If we have a company in scope, check the contact is associated to it.
if (
$companyId !== null
&& ($contact->account_id === null || $companyId !== $contact->account->crm_provider_id)
) {
continue;
}
return [
'id' => $contact->crm_provider_id,
'email' => $contact->email,
];
}
$payload = $this->generateNameSearchPayload($participant->name, 0, 20);
try {
$response = $this->client->getNewInstance()->crm()->contacts()->searchApi()->doSearch($payload);
// TODO add some logic to choose the most suitable contact if multiple
foreach ($response['results'] as $object) {
$properties = $object['properties'];
if (empty($object['properties']) === false) {
// Check the company matches the contact.
// Todo: Move this check inside the API search.
if ($companyId !== null && $companyId !== $properties['associatedcompanyid']) {
continue;
}
return [
'id' => $object['id'],
'email' => $properties['email'],
];
}
}
} catch (Exception $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Search failed', [
'teamId' => $this->team->id_string,
'request' => $payload,
'reason' => $e->getMessage(),
]);
}
return [];
}
/**
* Store transcripts as note engagement.
*
* @throws Exception
*/
public function createTranscriptNotes(Activity $activity): void
{
// For HS no need to check if Crm profile - Log Notes field is enabled
// We only check if store_transcript toggle is enabled on crm profile.
$engagement = [
'active' => true,
'ownerId' => $this->profile->crm_provider_id,
'timestamp' => $activity->created_at->tz($activity->user->timezone)->getTimestamp() * 1000,
'type' => 'NOTE',
];
// Generate activity transcription.
$transcriptionData = $this->generateTranscription($activity);
// Truncate Notes with max notes length because transcription text could be very long.
$transcripts = mb_strimwidth($transcriptionData, 0, static::ENGAGEMENT_BODY_MAX_LENGTH);
$metadata = [
'body' => $transcripts,
];
$associations = $this->convertActivityAssociations($activity);
try {
$hsEngagement = $this->client
->getInstance()
->engagements()
->create($engagement, $associations, $metadata);
$this->logCrmEngagementManipulation(self::ACTION_CREATE, $engagement, $metadata, $associations);
$noteId = $hsEngagement->data->engagement->id;
// Store crm logged id in transcription.
$transcription = $activity->getTranscription();
$transcription->crm_activity_id = $noteId;
$transcription->save();
} catch (Exception $e) {
Sentry::captureException($e);
}
}
/*
* @inheritdoc
*/
public function updateRecord(string $objectType, string $objectId, array $data, array $headers = []): void
{
$payload = [
'properties' => $data,
];
try {
switch ($objectType) {
case FieldData::OBJECT_OPPORTUNITY:
$this->client->getNewInstance()->crm()->deals()->basicApi()->update($objectId, $payload);
break;
case FieldData::OBJECT_CONTACT:
$this->client->getNewInstance()->crm()->contacts()->basicApi()->update($objectId, $payload);
break;
case FieldData::OBJECT_ACCOUNT:
$this->client->getNewInstance()->crm()->companies()->basicApi()->update($objectId, $payload);
break;
case FieldData::OBJECT_TASK:
// Endpoint for Engagements not ready
$engagements = [
'type' => 'TASK',
];
$metadata = $data;
$this->client->getInstance()->engagements()->update($objectId, $engagements, $metadata);
$this->logCrmEngagementManipulation(
self::ACTION_UPDATE,
['crmId' => $objectId],
$metadata,
);
break;
default:
throw new UnexpectedValueException('Unsupported object type "' . $objectType . '"');
}
} catch (\HubSpot\Client\Crm\Deals\ApiException $apiException) {
$errorMessage = $apiException->getMessage();
if ($apiException->getResponseBody()) {
$responseBody = json_decode($apiException->getResponseBody(), true, 512, JSON_THROW_ON_ERROR);
$errorMessage = $responseBody['message'] ?? $apiException->getMessage();
}
$this->logger->error(
'[HubSpot] Update record failed',
[
'objectType' => $objectT...
|
44744
|
|
44818
|
NULL
|
0
|
2026-04-17T09:07:54.950135+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776416874950_m2.jpg...
|
PhpStorm
|
faVsco.js – OpportunitySyncTrait.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
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.03046875,"top":0.017361112,"width":0.0453125,"height":0.022222223},"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#11894 on JY-18909-automated-reports-ask-jiminny, menu","depth":5,"bounds":{"left":0.07578125,"top":0.017361112,"width":0.14960937,"height":0.022222223},"help_text":"Pull request #11894 exists for current branch JY-18909-automated-reports-ask-jiminny, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.78515625,"top":0.017361112,"width":0.01328125,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AutomatedReportsCommandTest","depth":6,"bounds":{"left":0.803125,"top":0.017361112,"width":0.09765625,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AutomatedReportsCommandTest'","depth":6,"bounds":{"left":0.9007813,"top":0.017361112,"width":0.01328125,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AutomatedReportsCommandTest'","depth":6,"bounds":{"left":0.9140625,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9273437,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.96015626,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9734375,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9867188,"top":0.017361112,"width":0.013281226,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
4434561267597224148
|
-7988188602108755006
|
click
|
hybrid
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
PhpStormFileEditViewNavigateCodeLaravelRefactorFV faVsco.s v#11894 on JY-18909-automated-reports-ask-iminny kProjectvToolsWindowHelp> D Redisv D ServiceTraits€ OpportunitySync& SyncCrmEntities© SyncFieldsTrait.g© WriteCrmTrait.pr→IUTIS→Weshook© BatchSyncCollector© BatchSyncRedisSer(c) Client.php(C) ClosedDealStagesS@ DealFieldsService.pl© DecorateActivity.ph© FieldDefinitions.php© FieldTypeConverter© HubspotClientInterf.© HubspotTokenMana© PayloadBuilder.php© RemoteCrmObjectN(C) ResponseNormalize© Service.php© SyncFieldAction.php© SyncRelatedActivity© WebhookSyncBatchv D IntegrationApp> D Accessors~ D Api© ActionUrl.php• EnumUrllnterface© FlowUrl.php© PageResult.php© ProxyUrl.php© RequestBuilder.p6 RequestExecute.• RequestExecutelSystemEvents.pt© SystemUrl.phpC TokenBuilder.phy• TokenBuilderInte© UrlBuilder.phpu contigM FiltersM.JobsProspectSearchStraServiceTraits© DataClient.php© DecorateActivity.ph© LocalSearch.php© LocalSearchlnterfac© RemoteSearch.php© Service.php_ ListenersM MetadataD Migration• PipedriveD SalesforceD Traits© AutomatedReportsService.php© SendReportJob.php© SendReportMailJob.php© ReportController.phpTokenBuilder.php• TeamSetupController.phpphp api.php© Team.php© CreateHeldActivityEvent.php© TrackProviderInstalledEvent.php• Filesystem.php© ActivityLogged.php© AutomatedReportsCallbackService.php© RequestGenerateAskJiminnyReportJob.phpC RequestGenerateReportJob.phgC SyncOpportunity.php+ OpportunitySyncTrait.php X© Opportunity.php© EventServiceProvider.phpC RunOpportunityAiAnalysis.php© OpportunityUpdated.php© OpportunityStageUpdated.php© OpportunityPendingAiAnalysisAfterStageChanged.php© ProcessAiAutomationAnalysisResults.php© ImportOpportunityBatch.phpT, HasAttributes.phpImportBatchJobTrait.php"podcast_audio_url"X3Cc Wtrait OpportunitySyncTrait© Service.php© AutomatedReportResult.phpO resultsW332VZV19= custom.log= laravel.logA SF [jiminny@localhost]C* scratch_1.jsonV connect.vueV Onboard.vueA HS_local [jiminny@localhost]L console [EU] Xc crmenutykeposilory.onofii crm_configurations (EU]A console [PROD]A console [STAGING]X: Auto vPlayground~Gajiminny~select * from accounts where crm_configuration_id = 319 and C m026 49 A22 X3X 1031560select * from contacts where crm_configuration_id = 319 and crm_proviaer_1a IN (*66558/441850*1561# owner 13236 5257850801562# contact 116779180 665587441856 - activity - Alex Hoves [EMAIL] created 2026-J1563# contact 219247563 742723347700 - [EMAIL] 2026-03-241564# company 4176133 471506505691565* deal 4400955 41015012474715661567CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE "' END) AS user_id,1568972975988Y07100610071017101811O48102210301031103210331034103510481104%105210531070107110771078157010/11 usageprivate function resolveAmount(array $properties): ?stringf...}E15721573-1574private function parseCleanDatetime(string $datetime): ?Carbonf...}1575—10/= 1577Tusageprivate function resolveDealProbability(?string $stageProbability): int{...}1578—15791580pnivate function resol veForecastCategory(?string SfonecastCategory) : stringl..= 158115832 usagesprivate function importExternalFieldData(array $properties, int $opportunityId):15841585=1586$crmFields = $this->get0pportunitySyncableFields();$this->import0pportunityChe_rmFieldData($properties, $crmFields, $opportunity15871588158915902 usagesselect * from opportunities where id = 7594349;private function import0pportunityContacts(Opportunity $opportunity, array $assoc]1592select * from opportunity_stages where opportunity_id = 7594349;Iselect * from business processes where id = 6024:select * fromprocess_stages where stage_id = 16352;* oyne opporconaty concacts using aifrerencial approach1074* This comoares current vs new associations and onlu makes necessaru chanaes15951596select * from business_process_stages where business_process_id = 6024;select * from stages where team_id = 459;select * from teams where id = 459;SELECTprivate function syncOpportunityContactsDifferential (Opportunity Sopportunity, ar 1598CONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' ELSE "'END) AS user_id,v.email,sa.*,Tusdgeprivate function getCurrentContactCrmIds(Opportunity $opportunity): arrayf...}1601t.owner_id FROM social_accounts sa1602vulr users u on u.l = sa.sociaole 1o1 usage1605vul reans t l.h<->l.on t.10 = U.tean 1oonivate tuncrion Loccontactassociamonunanoesu-1604WHERE U.team_ id = 459 and sa.provider = 'hubspat':1605Opportunity Sopportunity,1606SELECT crm_provider_id, COUNT(*) as cnt, GROUP_CONCAT(id ORDER BY id) as idsarray scurrenceoncaccermas,1607array sconcaccassoclatlons.array $contactsToAdd,1608array $contactsToRemove16091610): void {...}FROM stagesWHERE team_id = 459 AND type = 'opportunity'GROUP BY crm_provider_idHAVING cnt > 1;Tusaueprivate function removeContactAssociations(Opportunity $opportunity, array $contaHelper code will nelp IDt lo understand vour Laravel apo code. Generale Don't snow Anymore loday 8.09u.email,sarxt.owner id FROM social accounts saJOIN users u on u.id = sa.sociable_idJOIN teams t 1..n‹->1: on t.id = u.team_ idWHERE U.team_id = 400 and sa.provider = 'hubspot':select * from features;select * from team_features where feature_id = 40;select * from teams where id = 556; # owner: 18101, crm: 477select * tron crn contlourarions where 1o = 4SELECT * FROM users WHERE id = 18101;SELECTCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' ELSE " END) AS user_id,U.emall,sa.*,t.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable_idJOIN teams t 1..n<->1: on t.id = u.team_idWHERE u.team_id = 556 and sa.provider = 'integration-app';Support Daily • in 2h 53mAL AutomatedReportsCommandTestv100% C•8 • Fri 17 Apr 12:07:54CascadeAutomated Report Retimivesugdtig orvortul+0 .sth1s→> logger->warningLHubspot lDEBUG resolvestage: missing stage, calling imports"stageId"→ $stageId,"businessProcessid = $businessProcess->getid),w1);$stage = $this->importStages(null, $stageId);3. DB query to understand the opportunity stages pattern betterKun tnis lo see tne exact secuence or stace chanees ane timine caps.0 sạlSELECTOS.10,os.stage_id,s.crm_provider_id AS stage_crm_id,s.name As stage name.os.created_at,LAG (os.stage_id) OVER (ORDER BY os.id) AS prev_stage_id,LAG(os.created at) OVER (ORDER BY os.id) AS prev created atTIMESTAMPDIFF(SECOND, LAG(os.created at) OVER (ORDER BY os.id), os.created at) AS secFkor opportunary staoes osJOIN stages s ON s.id = oS-stage_idWHERE os.opportunity_1d = 7594349ORDER BY os.id DESCLIMIT 50;This will reveal if the 5 stage IDs are cycling in a fixed order (suggests a loop) or random (suggests racecondition between obs.4. Check Redis for queued deal IDsRun in the container to see if this deal ID is stuck in the Redis batch queue:i bashdocker exec docker_lamp_1 php artisan tinker —execute="\$redis = app('redis');I$keys = \$redis->keys('*batch_sync_opportunities*459*');foreach(\$keys as \$k) { echo \$k . ' => "• oreats-escarouoky • Phr cuL, &If the deal CRM provider ID keeps reappearing in Redis batches, something is continuously re-enqueuingit — likely the retry mechanism replaying talled jobs.5. Check the crm_provider_id of opportunity 7594349SELECT id, crm_provider_id, stage_id, account_id, crm_configuration_idFROM opportunitiesWHERE id = 7594349;Then check opportunity_stages count:D salSELEC COUNIc. M[ created at. MAXcreated atFROM opportunity_stagesWHERE opportunity_id = 7594349;Ine total count and time range will contirm now long this nas been running and at what rate.Oal *ok lels lenore It loeeine now ane use wnat we nave. wnat coule polentlaly call syne ceporunity or imponortunity. If there are logs only use what we have already and I can check in cla<> Code Claude Sonnet 4.6W Windsurf TeamsUlr-o( 4 spaces...
|
NULL
|
|
44819
|
NULL
|
0
|
2026-04-17T09:07:59.403912+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776416879403_m1.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
+FirefoxFileEditViewHistoryBookmarksProfilesToolsW +FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelp→Q.meet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)PhpStorm© Opportunity |Help© DeseoreneUpuar© UposteCrm TarpetDroWeohookavertProotsto© DopceruntyStagsupauten© Decu@ JmenyDebugContrand0445 420 A1class Opportunity extends Model inplenentsres tnyreeeyenre178236%MAMNRNstatic::created(static function (Opportunity Sopportunity): void {Sopportunity-›stages()-›attach(Sopportunity->stage_1d):static::updating(static function (Opportunity Soppontunity): void 4gune (Sopportunity->stage.1d);11 (Sopportunity->isDirty( atributes: 'stage_1d')) {sopportunaty"ostage.upoated.ar caroon..noat).033010040300008D05C0s8DoppomUndySTe0wT0F):Stauac..opodteo stacic tuncczon lopcortunaty soppor tonty. voloevent(oew OpportunityUpdated(Sopportunity)):1f (Sopportunity-›wasChanged( attributes:"stage_id')) (dunef -vars: "nas, chensed, afßec vedated'):201 210./** edracecated */no usages & George Tulev|public function deleteExistingAjPrompt(): voidLJiminnylModeis > Opportunity » bootO » X0[EA) Piease ensure this is not a forgotten debug statement.SI12:07 PM Daily - ProcessingCascadeNew Cascadela6lSupport Daily • in 2h 53 m100% <78 • Fri 17 Apr 12:07:59Suomt AudioflieStrvice Tett@ • Q 8• Fi17 Apr 12:07.D Ollian KyuchukovNikolay NikolovMWCascade Code Xo4X1 07800e coo cote0e Oh0Vasil VasilevMihail MihaylovUTF-8 G 4 spocesNmater @VNORLIALLukas Kovalik...
|
NULL
|
8005658831397917929
|
NULL
|
visual_change
|
ocr
|
NULL
|
+FirefoxFileEditViewHistoryBookmarksProfilesToolsW +FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelp→Q.meet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)PhpStorm© Opportunity |Help© DeseoreneUpuar© UposteCrm TarpetDroWeohookavertProotsto© DopceruntyStagsupauten© Decu@ JmenyDebugContrand0445 420 A1class Opportunity extends Model inplenentsres tnyreeeyenre178236%MAMNRNstatic::created(static function (Opportunity Sopportunity): void {Sopportunity-›stages()-›attach(Sopportunity->stage_1d):static::updating(static function (Opportunity Soppontunity): void 4gune (Sopportunity->stage.1d);11 (Sopportunity->isDirty( atributes: 'stage_1d')) {sopportunaty"ostage.upoated.ar caroon..noat).033010040300008D05C0s8DoppomUndySTe0wT0F):Stauac..opodteo stacic tuncczon lopcortunaty soppor tonty. voloevent(oew OpportunityUpdated(Sopportunity)):1f (Sopportunity-›wasChanged( attributes:"stage_id')) (dunef -vars: "nas, chensed, afßec vedated'):201 210./** edracecated */no usages & George Tulev|public function deleteExistingAjPrompt(): voidLJiminnylModeis > Opportunity » bootO » X0[EA) Piease ensure this is not a forgotten debug statement.SI12:07 PM Daily - ProcessingCascadeNew Cascadela6lSupport Daily • in 2h 53 m100% <78 • Fri 17 Apr 12:07:59Suomt AudioflieStrvice Tett@ • Q 8• Fi17 Apr 12:07.D Ollian KyuchukovNikolay NikolovMWCascade Code Xo4X1 07800e coo cote0e Oh0Vasil VasilevMihail MihaylovUTF-8 G 4 spocesNmater @VNORLIALLukas Kovalik...
|
NULL
|
|
44820
|
947
|
0
|
2026-04-17T09:08:01.417443+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776416881417_m1.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
+FirefoxFileEditViewHistoryBookmarksProfilesToolsW +FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelp→Cmeet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)PhpStorm$•.(aolSupport Daily • in 2h 52 m100% <78 • Fri 17 Apr 12:08:0118HelpnyDebugCommand > © dindle© DetermineUpdateOperationAction© UpdateCruiTargetDtoWeohooktvert/rooesson© OpportuntyStageUpdated© DebugComme© JmineyDebugCommandSutnit AudioflleService Test@ • Q 8• Fri17Apr 12:08.D 0CascadeNew Cascade© Opportunity1.22«?php221declare(strict_types=1):5 1991418 1312 1113 1814 915 SD16 2112 60018 $YNNHNN M© OpportunityPendingAlAnalysisAfterStageChangedllian KyuchukovNikolay Nikolov* @nackase Jininog|Console)Coneands |1 usago & Nikola Petkansló • 1class Jtetnorocous coccand exceods concanaprotected Ssignatore • "Jiminny:debug";Sopportunity = \Jininng|Models\Opportunity:: find( ld: 115):Sopportunáty->stage_id = 100:"Lopen IpsundWCascade Code X°Kick off a new project. Make changeVasil VasilevMihail Mihaylov1anes70 Cenatesзонte кoopor emeecegce• ©Vy: Windsurt Teams (Pre-Reioase) Symfony23.43 LFUTF-8 C 4 spacesIsmaster @ VNORMALLukas Kovalik12:08 PM |Daily - Processing...
|
NULL
|
-8322046015479573385
|
NULL
|
click
|
ocr
|
NULL
|
+FirefoxFileEditViewHistoryBookmarksProfilesToolsW +FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelp→Cmeet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)PhpStorm$•.(aolSupport Daily • in 2h 52 m100% <78 • Fri 17 Apr 12:08:0118HelpnyDebugCommand > © dindle© DetermineUpdateOperationAction© UpdateCruiTargetDtoWeohooktvert/rooesson© OpportuntyStageUpdated© DebugComme© JmineyDebugCommandSutnit AudioflleService Test@ • Q 8• Fri17Apr 12:08.D 0CascadeNew Cascade© Opportunity1.22«?php221declare(strict_types=1):5 1991418 1312 1113 1814 915 SD16 2112 60018 $YNNHNN M© OpportunityPendingAlAnalysisAfterStageChangedllian KyuchukovNikolay Nikolov* @nackase Jininog|Console)Coneands |1 usago & Nikola Petkansló • 1class Jtetnorocous coccand exceods concanaprotected Ssignatore • "Jiminny:debug";Sopportunity = \Jininng|Models\Opportunity:: find( ld: 115):Sopportunáty->stage_id = 100:"Lopen IpsundWCascade Code X°Kick off a new project. Make changeVasil VasilevMihail Mihaylov1anes70 Cenatesзонte кoopor emeecegce• ©Vy: Windsurt Teams (Pre-Reioase) Symfony23.43 LFUTF-8 C 4 spacesIsmaster @ VNORMALLukas Kovalik12:08 PM |Daily - Processing...
|
44819
|
|
44821
|
948
|
0
|
2026-04-17T09:08:01.440284+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776416881440_m2.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorToo PhpStormFileEditViewNavigateCodeLaravelRefactorToolsWindowHelpFV faVsco.s v#11894 on JY-18909-automated-reports-ask-jiminny k ~Projectv© AutomatedReportsService.php© SendReportJob.php© SendReportMailJob.php= custom.log= laravel.logA SF [jiminny@localhost]C* scratch_1.jsonV connect.vueV Onboard.vue> D Redis© ReportController.phpTokenBuilder.php• TeamSetupController.phpphp api.php• Filesystem.phpA HS_local [jiminny@localhost]L console [EU] Xc crmenutykeposilory.onofii crm_configurations (EU]v D ServiceTraits€ OpportunitySync© Team.php© CreateHeldActivityEvent.php© TrackProviderInstalledEvent.php© ActivityLogged.phpA console [PROD]A console [STAGING]& SyncCrmEntities© AutomatedReportsCallbackService.php© RequestGenerateAskJiminnyReportJob.phpX: Auto vPlayground ~Gajiminny~© SyncFieldsTrait.gC RequestGenerateReportJob.phgC SyncOpportunity.phpt OpportunitySyncTrait.php xselect x trom accounts where cri_conriguration ta - oay and om026 49 A22 X3x 103© WriteCrmTrait.pr1560select * from contacts where crm_configuration_id = 319 and crm_proviaer_1a IN (•66558/441850*→IUTIS© Opportunity.php© OpportunityUpdated.php© OpportunityStageUpdated.php1561# owner 13236 525785080→Weshook© EventServiceProvider.php© OpportunityPendingAiAnalysisAfterStageChanged.php1562# contact 116779180 665587441856 - activity - Alex Hoves [EMAIL] created 2026-J© BatchSyncCollector1563# contact 219247563 742723347700 - [EMAIL] 2026-03-24© BatchSyncRedisSerRunOpportunityAiAnalyshr-php x ProcessAiAutomationAnalysisResults.php© ImportOpportunityBatch.php1564# company 4176133 47150650569(c) Client.phpwImportBatchJoblrait.phpT, HasAttributes.php© Service.php© AutomatedReportResult.php1565* deal 4400955 410150124747© ClosedDealStagesS@ DealFieldsService.pl"podcast_audio_url"X3CcW1566O results1567CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE "' END) AS user_id,© DecorateActivity.phtrait OpportunitySyncTrait1568A32 X2 X 19u.email,© FieldDefinitions.phpsarx972© FieldTypeConverter1570975t.owner id FROM social accounts sa© HubspotClientInterf.10/1JOIN users u on u.id = sa.sociable_id1 usage© HubspotTokenManaprivate function resolveAmount(array $properties): ?stringf...}E1572JOIN teams t 1..n‹->1: on t.id = u.team_ id© PayloadBuilder.php9881573WHERE U.team_id = 400 and sa.provider = 'hubspot':© RemoteCrmObjectN-1574lusaee(C) ResponseNormalizeY07private function parseCleanDatetime(string $datetime): ?Carbonf...}1575select * from features;© Service.php1006—10/select * from team_features where feature_id = 40;© SyncFieldAction.php= 1577Tusaye© SyncRelatedActivity1007private function resolveDealProbability(?string $stageProbability): int{...}1578© WebhookSyncBatch—1579v D IntegrationApp10171580> D Accessors1018pnivate function resol veForecastCategory(?string SfonecastCategory) : stringl..= 1581~ D Api11O48© ActionUrl.php15832 usages• EnumUrllnterface1584© FlowUrl.php© PageResult.php© ProxyUrl.php© RequestBuilder.p102210301031103210331034private function importExternalFieldData(array $properties, int $opportunityId):1585=1586$crmFields = $this->get0pportunitySyncableFields();$this->importOpportunitycrmFieldData(Sproperties, $crmFields, SopportunityId)15871588select * from teams where id = 556; # owner: 18101, crm: 477select * tron crn contlourarions where 1o = 4SELECT * FROM users WHERE id = 18101;SELECTCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' ELSE "' END) AS user_id,U.emall,sa.*,t.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable_idJOIN teams t 1..n<->1: on t.id = u.team_idWHERE u.team_id = 556 and sa.provider = 'integration-app';6 RequestExecute.1589• RequestExecutel15902 usagesselect * from opportunities where id = 7594349;SystemEvents.ptselect * from opportunity_stages where opportunity_id = 7594349;© SystemUrl.phpC TokenBuilder.phy103510481104%private function import0pportunityContacts(Opportunity $opportunity, array $assoc]1592Iselect * from business processes where id = 6024:select * fromprocess_stages where stage_id = 16352;**• TokenBuilderInte© UrlBuilder.phpucontig1074* Sync opportunity contacts using differential approach* This comoares current vs new associations and onlu makes necessaru chanaes15951596select * from business_process_stages where business_process_id = 6024;select * from stages where team_id = 459;ODTOM FiltersM.Jobs› ProspectSearchStraServiceTraits© DataClient.php© DecorateActivity.ph10521053107010711077select * from teams where id = 459;SELECTprivate function syncOpportunityContactsDifferential (Opportunity Sopportunity, ar 1598CONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' ELSE "'END) AS user_id,v.email,sa.*,Tusdgeprivate function getCurrentContactCrmIds(Opportunity $opportunity): arrayf...}1601t.owner_id FROM social_accounts sa1602vulr users u on u.l = sa.sociaole 1o1 usage1605vul reans t l.h<->l.on t.10 = U.tean 1o© LocalSearch.php1078onivate tuncrion Loccontactassociamonunanoesu-1604WHERE U.team_ id = 459 and sa.provider = 'hubspat':© LocalSearchlnterfac1605Opportunity Sopportunity,© RemoteSearch.php1606SELECT crm_provider_id, COUNT(*) as cnt, GROUP_CONCAT(id ORDER BY id) as idsarray scurrenccontacccrmlas,© Service.php1607array sconcaccassoclatlons._ Listenersarray $contactsToAdd,1608> M Metadataarray $contactsToRemove1609D Migration1610): void {...}FROM stagesWHERE team_id = 459 AND type = 'opportunity'GROUP BY crm_provider_idHAVING cnt > 1;• PipedriveD SalesforceTusaueD Traitsprivate function removeContactAssociations(Opportunity $opportunity, array $contaHelper code will nelp IDt lo understand vour Laravel apo code. Generale Don't snow Anymore loday 8.09Support Daily • in 2h 53mAL AutomatedReportsCommandTestv100% C•8 • Fri 17 Apr 12:08:00CascadeAutomated Report Retimivesugdtig orvortusth1s→> logger->warningLHubspot lDEBUG resolvestage: missing stage, calling imports"stageId"→ $stageId,"businessProcessid = $businessProcess->getid),w1);$stage = $this->importStages(null, $stageId);3. DB query to understand the opportunity stages pattern betterKun tnis lo see tne exact secuence or stace chanees ane timine caps.0 sạlSELECTOS.10,os.stage_id,s.crm_provider_id AS stage_crm_id,s.name As stage name.os.created_at,LAG (os.stage_id) OVER (ORDER BY os.id) AS prev_stage_id,LAG(os.created at) OVER (ORDER BY os.id) AS prev created atTIMESTAMPDIFF(SECOND, LAG(os.created at) OVER (ORDER BY os.id), os.created at) AS secFkor opportunary staoes osJOIN stages s ON s.id = oS-stage_idWHERE os.opportunity_1d = 7594349ORDER BY os.id DESCLIMIT 50;This will reveal if the 5 stage IDs are cycling in a fixed order (suggests a loop) or random (suggests racecondition between obs.4. Check Redis for queued deal IDsRun in the container to see if this deal ID is stuck in the Redis batch queue:i bashdocker exec docker_lamp_1 php artisan tinker —execute="\$redis = app('redis');I$keys = \$redis->keys('*batch_sync_opportunities*459*');foreach(\$keys as \$k) { echo \$k . ' => "• oreats-escarouoky • Phr cuL, &If the deal CRM provider ID keeps reappearing in Redis batches, something is continuously re-enqueuingit — likely the retry mechanism replaying talled jobs.5. Check the crm_provider_id of opportunity 7594349SELECT id, crm_provider_id, stage_id, account_id, crm_configuration_idFROM opportunitiesWHERE id = 7594349;Then check opportunity_stages count:D salSELEC COUNIc. M[ created at. MAXcreated atFROM opportunity_stagesWHERE opportunity_id = 7594349;Ine total count and time range will contirm now long this nas been running and at what rate.Oal *ok lels lenore It loeeine now ane use wnat we nave. wnat coule polentlaly call syne ceporunity or imponortunity. If there are logs only use what we have already and I can check in cla<> Code Claude Sonnet 4.6winasun leams1032:34( 4 spaces...
|
NULL
|
-5220782760507487918
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorToo PhpStormFileEditViewNavigateCodeLaravelRefactorToolsWindowHelpFV faVsco.s v#11894 on JY-18909-automated-reports-ask-jiminny k ~Projectv© AutomatedReportsService.php© SendReportJob.php© SendReportMailJob.php= custom.log= laravel.logA SF [jiminny@localhost]C* scratch_1.jsonV connect.vueV Onboard.vue> D Redis© ReportController.phpTokenBuilder.php• TeamSetupController.phpphp api.php• Filesystem.phpA HS_local [jiminny@localhost]L console [EU] Xc crmenutykeposilory.onofii crm_configurations (EU]v D ServiceTraits€ OpportunitySync© Team.php© CreateHeldActivityEvent.php© TrackProviderInstalledEvent.php© ActivityLogged.phpA console [PROD]A console [STAGING]& SyncCrmEntities© AutomatedReportsCallbackService.php© RequestGenerateAskJiminnyReportJob.phpX: Auto vPlayground ~Gajiminny~© SyncFieldsTrait.gC RequestGenerateReportJob.phgC SyncOpportunity.phpt OpportunitySyncTrait.php xselect x trom accounts where cri_conriguration ta - oay and om026 49 A22 X3x 103© WriteCrmTrait.pr1560select * from contacts where crm_configuration_id = 319 and crm_proviaer_1a IN (•66558/441850*→IUTIS© Opportunity.php© OpportunityUpdated.php© OpportunityStageUpdated.php1561# owner 13236 525785080→Weshook© EventServiceProvider.php© OpportunityPendingAiAnalysisAfterStageChanged.php1562# contact 116779180 665587441856 - activity - Alex Hoves [EMAIL] created 2026-J© BatchSyncCollector1563# contact 219247563 742723347700 - [EMAIL] 2026-03-24© BatchSyncRedisSerRunOpportunityAiAnalyshr-php x ProcessAiAutomationAnalysisResults.php© ImportOpportunityBatch.php1564# company 4176133 47150650569(c) Client.phpwImportBatchJoblrait.phpT, HasAttributes.php© Service.php© AutomatedReportResult.php1565* deal 4400955 410150124747© ClosedDealStagesS@ DealFieldsService.pl"podcast_audio_url"X3CcW1566O results1567CONCAT(u.id, CASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE "' END) AS user_id,© DecorateActivity.phtrait OpportunitySyncTrait1568A32 X2 X 19u.email,© FieldDefinitions.phpsarx972© FieldTypeConverter1570975t.owner id FROM social accounts sa© HubspotClientInterf.10/1JOIN users u on u.id = sa.sociable_id1 usage© HubspotTokenManaprivate function resolveAmount(array $properties): ?stringf...}E1572JOIN teams t 1..n‹->1: on t.id = u.team_ id© PayloadBuilder.php9881573WHERE U.team_id = 400 and sa.provider = 'hubspot':© RemoteCrmObjectN-1574lusaee(C) ResponseNormalizeY07private function parseCleanDatetime(string $datetime): ?Carbonf...}1575select * from features;© Service.php1006—10/select * from team_features where feature_id = 40;© SyncFieldAction.php= 1577Tusaye© SyncRelatedActivity1007private function resolveDealProbability(?string $stageProbability): int{...}1578© WebhookSyncBatch—1579v D IntegrationApp10171580> D Accessors1018pnivate function resol veForecastCategory(?string SfonecastCategory) : stringl..= 1581~ D Api11O48© ActionUrl.php15832 usages• EnumUrllnterface1584© FlowUrl.php© PageResult.php© ProxyUrl.php© RequestBuilder.p102210301031103210331034private function importExternalFieldData(array $properties, int $opportunityId):1585=1586$crmFields = $this->get0pportunitySyncableFields();$this->importOpportunitycrmFieldData(Sproperties, $crmFields, SopportunityId)15871588select * from teams where id = 556; # owner: 18101, crm: 477select * tron crn contlourarions where 1o = 4SELECT * FROM users WHERE id = 18101;SELECTCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' ELSE "' END) AS user_id,U.emall,sa.*,t.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable_idJOIN teams t 1..n<->1: on t.id = u.team_idWHERE u.team_id = 556 and sa.provider = 'integration-app';6 RequestExecute.1589• RequestExecutel15902 usagesselect * from opportunities where id = 7594349;SystemEvents.ptselect * from opportunity_stages where opportunity_id = 7594349;© SystemUrl.phpC TokenBuilder.phy103510481104%private function import0pportunityContacts(Opportunity $opportunity, array $assoc]1592Iselect * from business processes where id = 6024:select * fromprocess_stages where stage_id = 16352;**• TokenBuilderInte© UrlBuilder.phpucontig1074* Sync opportunity contacts using differential approach* This comoares current vs new associations and onlu makes necessaru chanaes15951596select * from business_process_stages where business_process_id = 6024;select * from stages where team_id = 459;ODTOM FiltersM.Jobs› ProspectSearchStraServiceTraits© DataClient.php© DecorateActivity.ph10521053107010711077select * from teams where id = 459;SELECTprivate function syncOpportunityContactsDifferential (Opportunity Sopportunity, ar 1598CONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' ELSE "'END) AS user_id,v.email,sa.*,Tusdgeprivate function getCurrentContactCrmIds(Opportunity $opportunity): arrayf...}1601t.owner_id FROM social_accounts sa1602vulr users u on u.l = sa.sociaole 1o1 usage1605vul reans t l.h<->l.on t.10 = U.tean 1o© LocalSearch.php1078onivate tuncrion Loccontactassociamonunanoesu-1604WHERE U.team_ id = 459 and sa.provider = 'hubspat':© LocalSearchlnterfac1605Opportunity Sopportunity,© RemoteSearch.php1606SELECT crm_provider_id, COUNT(*) as cnt, GROUP_CONCAT(id ORDER BY id) as idsarray scurrenccontacccrmlas,© Service.php1607array sconcaccassoclatlons._ Listenersarray $contactsToAdd,1608> M Metadataarray $contactsToRemove1609D Migration1610): void {...}FROM stagesWHERE team_id = 459 AND type = 'opportunity'GROUP BY crm_provider_idHAVING cnt > 1;• PipedriveD SalesforceTusaueD Traitsprivate function removeContactAssociations(Opportunity $opportunity, array $contaHelper code will nelp IDt lo understand vour Laravel apo code. Generale Don't snow Anymore loday 8.09Support Daily • in 2h 53mAL AutomatedReportsCommandTestv100% C•8 • Fri 17 Apr 12:08:00CascadeAutomated Report Retimivesugdtig orvortusth1s→> logger->warningLHubspot lDEBUG resolvestage: missing stage, calling imports"stageId"→ $stageId,"businessProcessid = $businessProcess->getid),w1);$stage = $this->importStages(null, $stageId);3. DB query to understand the opportunity stages pattern betterKun tnis lo see tne exact secuence or stace chanees ane timine caps.0 sạlSELECTOS.10,os.stage_id,s.crm_provider_id AS stage_crm_id,s.name As stage name.os.created_at,LAG (os.stage_id) OVER (ORDER BY os.id) AS prev_stage_id,LAG(os.created at) OVER (ORDER BY os.id) AS prev created atTIMESTAMPDIFF(SECOND, LAG(os.created at) OVER (ORDER BY os.id), os.created at) AS secFkor opportunary staoes osJOIN stages s ON s.id = oS-stage_idWHERE os.opportunity_1d = 7594349ORDER BY os.id DESCLIMIT 50;This will reveal if the 5 stage IDs are cycling in a fixed order (suggests a loop) or random (suggests racecondition between obs.4. Check Redis for queued deal IDsRun in the container to see if this deal ID is stuck in the Redis batch queue:i bashdocker exec docker_lamp_1 php artisan tinker —execute="\$redis = app('redis');I$keys = \$redis->keys('*batch_sync_opportunities*459*');foreach(\$keys as \$k) { echo \$k . ' => "• oreats-escarouoky • Phr cuL, &If the deal CRM provider ID keeps reappearing in Redis batches, something is continuously re-enqueuingit — likely the retry mechanism replaying talled jobs.5. Check the crm_provider_id of opportunity 7594349SELECT id, crm_provider_id, stage_id, account_id, crm_configuration_idFROM opportunitiesWHERE id = 7594349;Then check opportunity_stages count:D salSELEC COUNIc. M[ created at. MAXcreated atFROM opportunity_stagesWHERE opportunity_id = 7594349;Ine total count and time range will contirm now long this nas been running and at what rate.Oal *ok lels lenore It loeeine now ane use wnat we nave. wnat coule polentlaly call syne ceporunity or imponortunity. If there are logs only use what we have already and I can check in cla<> Code Claude Sonnet 4.6winasun leams1032:34( 4 spaces...
|
44818
|
|
44923
|
NULL
|
0
|
2026-04-17T09:13:16.140759+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776417196140_m2.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewFV faVsco.js~NavigateCodeLarav PhpStormFileEditViewFV faVsco.js~NavigateCodeLaravelRefactor#11894 on JY-18909-automated-reports-ask-jiminnyToolsWindowHelpProjectvyratupanIuLaIonEyosItuly puy© PlaybookCategoryRepository.php© PlaybookRepository.php© PlaylistActivityRepository.php© PlaylistRepository.php© PlaylistShareRepository.php© AutomatedReportsService.php© TeamSetupController.png© RequestGenerateReportJob.php© OpportunityStageUpdated.phpC RunOpportunityAiAnalysis.phg© SendReportJob.phpphp api.php• Filesystem.php© OpportunitySyncTrait.php© SendReportMailJob.phpC Team.php© ReportController.php© CreateHeldActivityEvent.php© Opportunity.php© InteractsWithPivotTable.php© OpportunityPendingAiAnalysisAfterStageChanged.phpC ImportOpportunityBatch.php© TokenBuilder.phpTrackProviderInstalledEvent.php© OpportunityUpdated.phpT ImportBatchJobTrait.php© QuestionRepository.php© Service.php© RoleChangeEventRepository.php© RoleRepository.php"podcast aualo unlX3Co W .*O resultsTIT:© SearchRepository.php© SnapshotRepository.php© SocialAccountRepository.phptrait OpportunitySyncTraitprivate function createOpportunity(string $crmId,HSVEVIAV$associations): ?Opportunity© StageRepository.php© SubscriptionSetRepository.php© TaskRepository.php© TeamAiContextRepository.php© TeamDomainsRepository.php© TeamInsightsRepository.php7857867877881891$this->importExternalFieldData($properties, $opportunity->getId()):$this->import0pportunityContacts($opportunity, $associations['contacts']);if ($opportunity->wasRecentlyCreated) {MarchAcavimes orewuoportunry. usourch opportunity->detloo.© TeamRepository.phpc nemere.ostov.onoc) TimezoneRepositorv.php© TopicRepository.php© TopicTriggerRepository.php© TrackRepository.php© TranscriptionModelLocaleRepositc© TranscriptionRepository.php791792793794795796797recurn sopporcunlty/*** Update existing opportunity© TranscriptionSummaryRepository.1 usage© UserRepository.php798private function update0pportunity(string $crmId, array $properties, array $associations): Opportunity© VocabularyRepository.php• Rules• Services> D Activity804$accountId = $this->resolveAccountId(Sassociations);$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);$stage = $businessProcess ? $this->resolveStage($businessProcess,$properties['dealstage'] ?? null): null;> D AjReports> DJ Avatar804$data = $this->buildOpportunfyData($properties, $accountId, $businessProcess, $stage);> D CalendarConferenceD CrmD Bullhorn→ IClose•_ copper> D CrmObjects> M DecorateActivity› D Dummy> _ Helpersv D HubspotD AccountSyncStrategy> D ActionsContactSyncStrategy> ODTO806807808809810811814813814815816817818819$attributes = ['crm_configuration_id' => $this->config->getid(),'crm_provider_id' = $crmId,$values = array_merge($attributes, $data);$opportunity = $this->crmEntityRepository->upsert0pportunity($attributes, $values);$this->importExternalFieldData($properties, $opportunity->getId());$this->update0pportunityAssociations($opportunity, $associations);return $opportunity;→ Irields2 usages> D JournalMeradara820857private function resolveAccountId(array $associations): ?int{...}MOpportunitvSyncStrateay> MPaginationProspectSearchStrateayD RedisServiceTraits€ OpportunitySyncTrait.ph858854840841842& SyncCrmEntities Trait.php© SyncFieldsTrait.php2 usagesprivate function buildOpportunityDatadarray soropercles.?int $accountId,?BusinessProcess $businessProcess,?Stage $stage): array €$ownerId = null;Helper code will nelp IDe to understand your Laravel app code. |/ Generate // Don't snow Anymore (today 8:59)= custom.logV connect.vue= laravel.logVOnboard.vueA SF [jiminny@localhost](° scratch_1.json4 HS_local [jiminny@localhost]A console [EU] >nun crm confiourations iFUllA console [PROD]CrmEntityRepository.php4 console [STAGING]1560156115041563156415651566E15671568-15691570.1571=[CREDIT_CARD]=[CREDIT_CARD]—158115851580|158715881589159115921593159415951570159715981608100%1O10Tx: Auto vPlaygroundSa jiminny vselect * from accounts where026 A9 A22 X 3 X 103select * tron contacts where.crn contlourarion 1o = 51y ano* owner 15250 525705080* contactlolo O0h0 441000 - aCENLTYAlex Howes ale* concact 419247563 742723347700 - [EMAIL] 2026-# company 4176133 47150650569# deal 7100953 410150124747SELECTCONCAT(u.id, LASE WHEN u.id = t.owner_id THEN(owner)' Eu.email,sa.*,t.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable_idJUIN ceams t n→>l on t.1d = U.ceam_1dWreke U.teanl_ld - 400 and sa.provider - guosposaselect * from features;select * from team_features where feature_id = 40;select * from teams where id = 556; # owner: 18101, crm: 477_select * from crm_configurations where id = 477;SELECT * FROM users WHERE id = 18101;DELEEITCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' EU.emall,sarxt.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable idJOIN teams t 1.n<->1: on t.id = u.team_idWHERE u.team_id = 556 and sa.provider = 'integration-app';select * from opportunities where id = 7594349;select * from opportunity_stages where opportunity_id = 759431select * from business_processes where id = 6024;select * from business_process_stages where stage_id = 16352;select * from business_process_stages where business_process_iselect * tron stades were cean 10 = 4521select * fromteams where id = 459SELECTCONCAT(u.id,CASE WHEN u.id = t.owner_id THENu.email,sa.*,t.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable_idJOIN teams t 1.n<->1: on t.id = u.team_idWHERE u.team_id = 459 and sa.provider ='hubspot';SELECT crm_provider_id, COUNT(*) as cnt, GROUP_CONCAT(id ORDEFFROM stagesWHERE team_id = 459 AND type = 'opportunity'GROUP BY crm_provider_idHAVING cnt > 1;Support Daily • in 2h 47 mAAutomatedRenortsCommandTest100% C•8 • Fri 17 Apr 12:13:15CascadeAutomated Report RetrInvestigating Opportur+D ...1. User logs an activity in the Ul with a different stage → ActivityController dispatches UpdateStagewole calls criberviepdateStage() → pushes the stage change to HubSpot3. HubSpot receives the update and fires a deal.propertyChange webhook back to Jiminny4. Webhook is collected in Redis → SyncObjects cycle processes it → import0pportunityBatch() → upsertOpportunity() with the stage HubSpot now has5. But HubSpot might return the previous stage if the update hasn't propagated, or if HubSpot rejectsthe change - writing a different stage id backcloudwatch loas to look for."opportunity stage nas changed""[HubSpot] User changing opportunity stage from"2. SyncObjects job + HubspotWebhookBatchSyncStrategy draining Redis (second most likely)The SyncObiects job runs on a schedule and drains the Redis batch queue. If deal 7594349 's CRMvrovcerD keeos reaovearino in the reels seroecause the talledy nano er in moortbarchobiraltrequeues it after failures), then it gets reprocessed on every cycle.CloudWatch logs to look for:"[WebhookSyncBatchProcessor] Batch processing completed"- with config_id for team 459"[ImportOpportunityBatch]" or "[HubSpot] Failed to import opportunity""(HubSpot) Syncing opportunities using strateqy"Check if the same deal CRM ID appears in multiple consecutive [WebhookSyncBatchProcessor] runs.3. importExternalFieldData SyncCrmField writing back and triggering re-syncFrocessALaucomaclonAnalysiskesults calls servicsyncOpportunity before writing Al field valuesSince Al Automation is enabled for this team (you're seeing the OpportunityPendingAiAnalysisAfterStageChanged logs), even though this specific opportunity has no templates, other opportunities do - and their syncupporcunity calls ao through 1mporturu:ncy → which can atrect the keals queuestate.What to search in CloudWatchFor opportunity 7594349, search for these in order:"opportunity stage has changed""opportunityId":<UUID of 7594349>"[ImportOpportunityBatch]""failed() requeue"# Was a user manually changing stage?# Any UpdateStage dispatches# Is it being reprocessed by batch job?# Is batch job failing and requeueing?Also get the crm_provider_id of opportunity 7594349 from DB, then search:"<crm_provider_id>"# All mentions across logs - will show every sync triggerThat last one will definitively tell you which code path is writing it.C1l -Ask anything (24L)+ <> Code Claude Sonnet 4.6Winasun leamsuir-o( 4 spaces...
|
NULL
|
-8196613775378673811
|
NULL
|
visual_change
|
ocr
|
NULL
|
PhpStormFileEditViewFV faVsco.js~NavigateCodeLarav PhpStormFileEditViewFV faVsco.js~NavigateCodeLaravelRefactor#11894 on JY-18909-automated-reports-ask-jiminnyToolsWindowHelpProjectvyratupanIuLaIonEyosItuly puy© PlaybookCategoryRepository.php© PlaybookRepository.php© PlaylistActivityRepository.php© PlaylistRepository.php© PlaylistShareRepository.php© AutomatedReportsService.php© TeamSetupController.png© RequestGenerateReportJob.php© OpportunityStageUpdated.phpC RunOpportunityAiAnalysis.phg© SendReportJob.phpphp api.php• Filesystem.php© OpportunitySyncTrait.php© SendReportMailJob.phpC Team.php© ReportController.php© CreateHeldActivityEvent.php© Opportunity.php© InteractsWithPivotTable.php© OpportunityPendingAiAnalysisAfterStageChanged.phpC ImportOpportunityBatch.php© TokenBuilder.phpTrackProviderInstalledEvent.php© OpportunityUpdated.phpT ImportBatchJobTrait.php© QuestionRepository.php© Service.php© RoleChangeEventRepository.php© RoleRepository.php"podcast aualo unlX3Co W .*O resultsTIT:© SearchRepository.php© SnapshotRepository.php© SocialAccountRepository.phptrait OpportunitySyncTraitprivate function createOpportunity(string $crmId,HSVEVIAV$associations): ?Opportunity© StageRepository.php© SubscriptionSetRepository.php© TaskRepository.php© TeamAiContextRepository.php© TeamDomainsRepository.php© TeamInsightsRepository.php7857867877881891$this->importExternalFieldData($properties, $opportunity->getId()):$this->import0pportunityContacts($opportunity, $associations['contacts']);if ($opportunity->wasRecentlyCreated) {MarchAcavimes orewuoportunry. usourch opportunity->detloo.© TeamRepository.phpc nemere.ostov.onoc) TimezoneRepositorv.php© TopicRepository.php© TopicTriggerRepository.php© TrackRepository.php© TranscriptionModelLocaleRepositc© TranscriptionRepository.php791792793794795796797recurn sopporcunlty/*** Update existing opportunity© TranscriptionSummaryRepository.1 usage© UserRepository.php798private function update0pportunity(string $crmId, array $properties, array $associations): Opportunity© VocabularyRepository.php• Rules• Services> D Activity804$accountId = $this->resolveAccountId(Sassociations);$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);$stage = $businessProcess ? $this->resolveStage($businessProcess,$properties['dealstage'] ?? null): null;> D AjReports> DJ Avatar804$data = $this->buildOpportunfyData($properties, $accountId, $businessProcess, $stage);> D CalendarConferenceD CrmD Bullhorn→ IClose•_ copper> D CrmObjects> M DecorateActivity› D Dummy> _ Helpersv D HubspotD AccountSyncStrategy> D ActionsContactSyncStrategy> ODTO806807808809810811814813814815816817818819$attributes = ['crm_configuration_id' => $this->config->getid(),'crm_provider_id' = $crmId,$values = array_merge($attributes, $data);$opportunity = $this->crmEntityRepository->upsert0pportunity($attributes, $values);$this->importExternalFieldData($properties, $opportunity->getId());$this->update0pportunityAssociations($opportunity, $associations);return $opportunity;→ Irields2 usages> D JournalMeradara820857private function resolveAccountId(array $associations): ?int{...}MOpportunitvSyncStrateay> MPaginationProspectSearchStrateayD RedisServiceTraits€ OpportunitySyncTrait.ph858854840841842& SyncCrmEntities Trait.php© SyncFieldsTrait.php2 usagesprivate function buildOpportunityDatadarray soropercles.?int $accountId,?BusinessProcess $businessProcess,?Stage $stage): array €$ownerId = null;Helper code will nelp IDe to understand your Laravel app code. |/ Generate // Don't snow Anymore (today 8:59)= custom.logV connect.vue= laravel.logVOnboard.vueA SF [jiminny@localhost](° scratch_1.json4 HS_local [jiminny@localhost]A console [EU] >nun crm confiourations iFUllA console [PROD]CrmEntityRepository.php4 console [STAGING]1560156115041563156415651566E15671568-15691570.1571=[CREDIT_CARD]=[CREDIT_CARD]—158115851580|158715881589159115921593159415951570159715981608100%1O10Tx: Auto vPlaygroundSa jiminny vselect * from accounts where026 A9 A22 X 3 X 103select * tron contacts where.crn contlourarion 1o = 51y ano* owner 15250 525705080* contactlolo O0h0 441000 - aCENLTYAlex Howes ale* concact 419247563 742723347700 - [EMAIL] 2026-# company 4176133 47150650569# deal 7100953 410150124747SELECTCONCAT(u.id, LASE WHEN u.id = t.owner_id THEN(owner)' Eu.email,sa.*,t.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable_idJUIN ceams t n→>l on t.1d = U.ceam_1dWreke U.teanl_ld - 400 and sa.provider - guosposaselect * from features;select * from team_features where feature_id = 40;select * from teams where id = 556; # owner: 18101, crm: 477_select * from crm_configurations where id = 477;SELECT * FROM users WHERE id = 18101;DELEEITCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' EU.emall,sarxt.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable idJOIN teams t 1.n<->1: on t.id = u.team_idWHERE u.team_id = 556 and sa.provider = 'integration-app';select * from opportunities where id = 7594349;select * from opportunity_stages where opportunity_id = 759431select * from business_processes where id = 6024;select * from business_process_stages where stage_id = 16352;select * from business_process_stages where business_process_iselect * tron stades were cean 10 = 4521select * fromteams where id = 459SELECTCONCAT(u.id,CASE WHEN u.id = t.owner_id THENu.email,sa.*,t.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable_idJOIN teams t 1.n<->1: on t.id = u.team_idWHERE u.team_id = 459 and sa.provider ='hubspot';SELECT crm_provider_id, COUNT(*) as cnt, GROUP_CONCAT(id ORDEFFROM stagesWHERE team_id = 459 AND type = 'opportunity'GROUP BY crm_provider_idHAVING cnt > 1;Support Daily • in 2h 47 mAAutomatedRenortsCommandTest100% C•8 • Fri 17 Apr 12:13:15CascadeAutomated Report RetrInvestigating Opportur+D ...1. User logs an activity in the Ul with a different stage → ActivityController dispatches UpdateStagewole calls criberviepdateStage() → pushes the stage change to HubSpot3. HubSpot receives the update and fires a deal.propertyChange webhook back to Jiminny4. Webhook is collected in Redis → SyncObjects cycle processes it → import0pportunityBatch() → upsertOpportunity() with the stage HubSpot now has5. But HubSpot might return the previous stage if the update hasn't propagated, or if HubSpot rejectsthe change - writing a different stage id backcloudwatch loas to look for."opportunity stage nas changed""[HubSpot] User changing opportunity stage from"2. SyncObjects job + HubspotWebhookBatchSyncStrategy draining Redis (second most likely)The SyncObiects job runs on a schedule and drains the Redis batch queue. If deal 7594349 's CRMvrovcerD keeos reaovearino in the reels seroecause the talledy nano er in moortbarchobiraltrequeues it after failures), then it gets reprocessed on every cycle.CloudWatch logs to look for:"[WebhookSyncBatchProcessor] Batch processing completed"- with config_id for team 459"[ImportOpportunityBatch]" or "[HubSpot] Failed to import opportunity""(HubSpot) Syncing opportunities using strateqy"Check if the same deal CRM ID appears in multiple consecutive [WebhookSyncBatchProcessor] runs.3. importExternalFieldData SyncCrmField writing back and triggering re-syncFrocessALaucomaclonAnalysiskesults calls servicsyncOpportunity before writing Al field valuesSince Al Automation is enabled for this team (you're seeing the OpportunityPendingAiAnalysisAfterStageChanged logs), even though this specific opportunity has no templates, other opportunities do - and their syncupporcunity calls ao through 1mporturu:ncy → which can atrect the keals queuestate.What to search in CloudWatchFor opportunity 7594349, search for these in order:"opportunity stage has changed""opportunityId":<UUID of 7594349>"[ImportOpportunityBatch]""failed() requeue"# Was a user manually changing stage?# Any UpdateStage dispatches# Is it being reprocessed by batch job?# Is batch job failing and requeueing?Also get the crm_provider_id of opportunity 7594349 from DB, then search:"<crm_provider_id>"# All mentions across logs - will show every sync triggerThat last one will definitively tell you which code path is writing it.C1l -Ask anything (24L)+ <> Code Claude Sonnet 4.6Winasun leamsuir-o( 4 spaces...
|
44921
|
|
44924
|
NULL
|
0
|
2026-04-17T09:13:16.594295+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776417196594_m1.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
+FirefoxFileEditViewHistoryBookmarksProfilesToolsW +FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelp→meet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)BraveProfilesHelpError during deal CRM auto p883 DEV SimineyPROO Smhttps://jiminny.sentry.lo/fssues/6914839403/events/52918e1/182949e3a910a3e587d1d0c1/?project=[CREDIT_CARD]&sta…PROD EU Jiminey@ My PRs|• Assigned• To Review• Jiminny Prophet W...Pipelines - jminey.-O JRA© OpenAl PlatfoemIssuesE3 PROPHET-118Error during deal CRM auto populate extraction: All endpoints failed to generate a response1 /orm/deal/extract-feld-values08Errors & OutagesBreached MetricsWarningsUser FeedbackResolveArchiveAll EnvsvQ Fiter events...Cycot3.7KUsersConfigureAlerts2091100Apr 16 9,00 PM|Apr 17 3.00 AMEvents v in this issueD: 52918e1f|3.hours.agoJSON@ CPython 3.14.3• prod-eu~ HighlightsACrCaKrantirczonДКТЕЕОСЗАКСХКОВКОТАСАЯ-УЗАUК~ MessageError during deal CRM auto populate extraction: All endpoints failed to generate a responsev Breadcrumbs©) Message - This event errorError during deal CRM auto populate extraction: All endpoints fasled to generate a response« app erfolAll endpoints fasled to generate a responsePS1712:13 PMDaily - Processing‹ >040x Confiuencelv) Service-Desk - Qu.Apr 17 9%runtimenamruntimeView all tags and feature flags100%_tract-feid-values79% prod-eu96X CPython 3.114.3FirstRecommendedView More EventsO Copy as ~Jumpto: HighlightsBreadcrumbsconttr/ Edithttp://proohet.J1m100y.ew/scn/deal/ext.casALALAIZARCO Copyas~AOTT ORLOOUOS AMUIGIAрC1202005.065 AMU1Ca Support Daily - in 2h 47 m100% <478 • Fri 17 Apr 12:13:166• Q 8• Fri17 Apr 12:13@ AWSD Al BookmarkeEvents (totaDUsers (9od)|4.2KPriority al~AssigneeLast seen 2 hours agoFirst seen 7 months ago~ Seer Autofx @Have Seer.1. Determine the rootcause of your issue2. Outine a plan3. Create a code fox$ Start Analysisissue wracking• синьо4 Эira> ActivityPop out this videoSimilar IssuesMerged Issuesllian KyuchukovNikolay NikolovVasil VasilevMihail MihaylovLukas Kovalik...
|
NULL
|
-1515664724008045738
|
NULL
|
visual_change
|
ocr
|
NULL
|
+FirefoxFileEditViewHistoryBookmarksProfilesToolsW +FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelp→meet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)BraveProfilesHelpError during deal CRM auto p883 DEV SimineyPROO Smhttps://jiminny.sentry.lo/fssues/6914839403/events/52918e1/182949e3a910a3e587d1d0c1/?project=[CREDIT_CARD]&sta…PROD EU Jiminey@ My PRs|• Assigned• To Review• Jiminny Prophet W...Pipelines - jminey.-O JRA© OpenAl PlatfoemIssuesE3 PROPHET-118Error during deal CRM auto populate extraction: All endpoints failed to generate a response1 /orm/deal/extract-feld-values08Errors & OutagesBreached MetricsWarningsUser FeedbackResolveArchiveAll EnvsvQ Fiter events...Cycot3.7KUsersConfigureAlerts2091100Apr 16 9,00 PM|Apr 17 3.00 AMEvents v in this issueD: 52918e1f|3.hours.agoJSON@ CPython 3.14.3• prod-eu~ HighlightsACrCaKrantirczonДКТЕЕОСЗАКСХКОВКОТАСАЯ-УЗАUК~ MessageError during deal CRM auto populate extraction: All endpoints failed to generate a responsev Breadcrumbs©) Message - This event errorError during deal CRM auto populate extraction: All endpoints fasled to generate a response« app erfolAll endpoints fasled to generate a responsePS1712:13 PMDaily - Processing‹ >040x Confiuencelv) Service-Desk - Qu.Apr 17 9%runtimenamruntimeView all tags and feature flags100%_tract-feid-values79% prod-eu96X CPython 3.114.3FirstRecommendedView More EventsO Copy as ~Jumpto: HighlightsBreadcrumbsconttr/ Edithttp://proohet.J1m100y.ew/scn/deal/ext.casALALAIZARCO Copyas~AOTT ORLOOUOS AMUIGIAрC1202005.065 AMU1Ca Support Daily - in 2h 47 m100% <478 • Fri 17 Apr 12:13:166• Q 8• Fri17 Apr 12:13@ AWSD Al BookmarkeEvents (totaDUsers (9od)|4.2KPriority al~AssigneeLast seen 2 hours agoFirst seen 7 months ago~ Seer Autofx @Have Seer.1. Determine the rootcause of your issue2. Outine a plan3. Create a code fox$ Start Analysisissue wracking• синьо4 Эira> ActivityPop out this videoSimilar IssuesMerged Issuesllian KyuchukovNikolay NikolovVasil VasilevMihail MihaylovLukas Kovalik...
|
NULL
|
|
44925
|
950
|
0
|
2026-04-17T09:13:19.138016+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776417199138_m2.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorToo PhpStormFileEditViewNavigateCodeLaravelRefactorToolsWindowHelpFV faVsco.js v#11894 on JY-18909-automated-reports-ask-iminny kProject v© AutomatedReportsService.php© SendReportJob.php© SendReportMailJob.php© ReportController.php© TokenBuilder.php= custom.log= laravel.logA SF ljiminny@localhost](° scratch_1.jsonyratupanIuLaIonEyosItuly puy© PlaybookCategoryRepository.php© TeamSetupController.pngphp api.php• Filesystem.phpC Team.php© CreateHeldActivityEvent.phpTrackProviderInstalledEvent.phpV connect.vueVOnboard.vue4 HS_local [jiminny@localhost]A console [EU] >© PlaybookRepository.php© RequestGenerateReportJob.php& OpportunitySyncTrait.php x© Opportunity.php© InteractsWithPivotTable.php© OpportunityUpdated.phpCrmEntityRepository.phpfii crm_configurations [EU]A console [(PROD]© PlaylistActivityRepository.php© PlaylistRepository.php© OpportunityStageUpdated.php© OpportunityPendingAiAnalysisAfterStageChanged.php4 console [STAGING]© PlaylistShareRepository.phpC RunOpportunityAiAnalysis.phgC ImportOpportunityBatch.phpT ImportBatchJobTrait.phpTx: Auto vPlaygroundSa jiminny v© QuestionRepository.phpselect * from accounts where© Service.php© RoleChangeEventRepository.php1560026 A9 A22 X 3 X 103select * from contacts wherecrn contlourarion 1o = 51y anoC RoleRepository.php"podcast aualo unl"Co W .*O resultsTIT:1561* owner 15250 525705080© SearchRepository.php1504* contactlolol o0h0/441000 - CCEVLEyAlex Howes aletrait OpportunitySyncTrait© SnapshotRepository.phpBSZMZMI9 AY1563* concact 419247563 742723347700 - [EMAIL] 2026-© SocialAccountRepository.phpprivate function createOpportunity(string $crmId,$associations): ?Opportunity1564# company 4176133 47150650569© StageRepository.php1565# deal 7100953 410150124747© SubscriptionSetRepository.php$this->importExternalFieldData($properties, $opportunity->getId()):1566© TaskRepository.php785786$this->import0pportunityContacts($opportunity, $associations['contacts']);E1567SELECTCONCAT(u.id, LASE WHEN u.id = t.owner_id THEN(owner)' E© TeamAiContextRepository.php7871568u.email,© TeamDomainsRepository.php788if ($opportunity->wasRecentlyCreated) {-1569sa.*,© TeamInsightsRepository.php1891MarchAcavimes orewuoportunry. usourch opportunity->detloo.1570t.owner_id FROM social_accounts sa© TeamRepository.php.1571JOIN users u on u.id = sa.sociable_idc nemere.ostov.ono791=1572JUIN ceams t n→>l on t.1d = U.ceam_1dc) TimezoneRepositorv.php792recurn sopporcunity,1573Wreke U.teanl_ld- 400 and sa.provider - nupspota© TopicRepository.php793© TopicTriggerRepository.php794select * from features;© TrackRepository.php795/**-1576select * from team_features where feature_id = 40;© TranscriptionModelLocaleRepositc796* Update existing opportunity=1577© TranscriptionRepository.php7971578© TranscriptionSummaryRepository.1 usage1579select * from teams where id = 556; # owner: 18101, crm: 477_select * from crm_configurations where id = 477;© UserRepository.php798private function update0pportunity(string $crmId, array $properties, array $associations): Opportunity1580SELECT * FROM users WHERE id = 18101;© VocabularyRepository.php—1581SELECT• RulesSaccountid = $this->resolveAccountld(sassoclatzons..=1582CONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' E• Services$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);1585U.emall,> D Activity$stage = $businessProcess ? $this->re> D AjReports803Choose Declaration@ a resolveBusinessProcess (OpportunitySyncTrait .../app/Services/Crm/Hubspot/ServiceTraits)> D Avatar804$data = $this->build0pportunityData($@ o resolveBusinessProcess(OpportunitySyncTraitMatchActivitiesTest•/tests/Unit/Services/Crm/Hubspot/ServiceTrait> D Calendar805h_id› D Conference806$attributes = [1588WHERE u.team_id = 556 and sa.provider = 'integration-app';D Crm807'crm_configuration_id' => $this->config->getid(),1589D Bullhorn808'crm_provider_id' => $crmId,1590select * from opportunities where id = 7594349;Close8091591select * from opportunity_stages where opportunity_id = 759431Wcopper8101592select * from business_processes where id = 6024;> D CrmObjects811$values = array_merge($attributes, $data);1593select * from business_process_stages where stage_id = 16352;> M7 DecorateActivity814$opportunity = $this->crmEntityRepository->upsert0pportunity($attributes, $values);1594selert * +ronbusiness_process_stages where business_process_j> Dummy8131595select * fromStades were rean 10 = 4571> _ Helpers814v D Hubspot815$this->importExternalFieldData($properties, $opportunity->getId());1596select * fromteams where id = 459$this->update0pportunityAssociations($opportunity, $associations);1597SELECTD AccountSyncStrategy8161598CONCAT(u.id,CASE WHEN u.id = t.owner_id THEN[ Actions817return $opportunity;u.email,ContactSyncStrategy818sa.*,> DDTO819t.owner_id FROM social_accounts sa→ Irields2 usagesJOIN users u on u.id = sa.sociable_id> D Journal820private function resolveAccountId(array $associations): ?int{...}JOIN teams t 1.n<->1: on t.id = u.team_idMeradara857WHERE u.team_id = 459 and sa.provider ='hubspot';MOpportunitvSyncStrateay2 usages> MPagination858private function buildOpportunityDatadSELECT crm_provider_id, COUNT(*) as cnt, GROUP_CONCAT(id ORDEFProspectSearchStrateay854array soropercles.FROM stagesD Redis840?int $accountId,1008WHERE team_id = 459 AND type = 'opportunity'D ServiceTraits841?BusinessProcess $businessProcess,100%GROUP BY crm_provider_id€ OpportunitySyncTrait.ph842?Stage $stage1610HAVING cnt > 1;& SyncCrmEntities Trait.php): array €© SyncFieldsTrait.php$ownerId = null;Helper Code will help IDE to understand your Laravel app code. // Generate // Don't Show Anymore (today 8:59)Support Daily • in 2h 47 mAAutomatedRenortsCommandTest100% C•8 • Fri 17 Apr 12:13:18CascadeAutomated Report RetrInvestigating Opportur+D ...1. User logs an activity in the Ul with a different stage → ActivityController dispatches UpdateStagewole calls criberviepdateStage() → pushes the stage change to HubSpot3. HubSpot receives the update and fires a deal.propertyChange webhook back to Jiminny4. Webhook is collected in Redis → SyncObjects cycle processes it → import0pportunityBatch() → upsertOpportunity() with the stage HubSpot now has5. But HubSpot might return the previous stage if the update hasn't propagated, or if HubSpot rejectsthe change - writing a different stage id backcloudwatch loas to look for."opportunity stage has changed""[HubSpot] User changing opportunity stage from"2. SyncObjects job + HubspotWebhookBatchSyncStrategy draining Redis (second most likely)The SyncObiects job runs on a schedule and drains the Redis batch queue. If deal 7594349 's CRMvrovcerD keeos reaovearino in the reels seroecause the talledy nano er in moortbarchobiraltrequeues it after failures), then it gets reprocessed on every cycle.CloudWatch logs to look for:"[WebhookSyncBatchProcessor] Batch processing completed"- with config_id for team 459"[ImportOpportunityBatch]" or "[HubSpot] Failed to import opportunity""(HubSpot) Syncing opportunities using strateqy"Check if the same deal CRM ID appears in multiple consecutive [WebhookSyncBatchProcessor] runs.3. importExternalFieldData SyncCrmField writing back and triggering re-syncFrocessALaucomaclonAnalysiskesults calls servicsyncOpportunity before writing Al field valuesSince Al Automation is enabled for this team (you're seeing the OpportunityPendingAiAnalysisAfterStageChanged logs), even though this specific opportunity has no templates, other opportunities do - and their syncupporcunity calls ao through 1mporturu.ncy → which can atrect the keals queuestate.What to search in CloudWatchFor opportunity 7594349, search for these in order:"opportunity stage has changed""opportunityId":<UUID of 7594349>"[ImportOpportunityBatch]""failed() requeue"# Was a user manually changing stage?# Any UpdateStage dispatches# Is it being reprocessed by batch job?# Is batch job failing and requeueing?Also get the crm_provider_id of opportunity 7594349 from DB, then search:"<crm_provider_id>"# All mentions across logs - will show every sync triggerThat last one will definitively tell you which code path is writing it.C1l -Ask anything (24L)+ <>Code Claude Sonnet 4.6Winasun leams801:40uir-o( 4 spaces...
|
NULL
|
-527715655357738894
|
NULL
|
visual_change
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorToo PhpStormFileEditViewNavigateCodeLaravelRefactorToolsWindowHelpFV faVsco.js v#11894 on JY-18909-automated-reports-ask-iminny kProject v© AutomatedReportsService.php© SendReportJob.php© SendReportMailJob.php© ReportController.php© TokenBuilder.php= custom.log= laravel.logA SF ljiminny@localhost](° scratch_1.jsonyratupanIuLaIonEyosItuly puy© PlaybookCategoryRepository.php© TeamSetupController.pngphp api.php• Filesystem.phpC Team.php© CreateHeldActivityEvent.phpTrackProviderInstalledEvent.phpV connect.vueVOnboard.vue4 HS_local [jiminny@localhost]A console [EU] >© PlaybookRepository.php© RequestGenerateReportJob.php& OpportunitySyncTrait.php x© Opportunity.php© InteractsWithPivotTable.php© OpportunityUpdated.phpCrmEntityRepository.phpfii crm_configurations [EU]A console [(PROD]© PlaylistActivityRepository.php© PlaylistRepository.php© OpportunityStageUpdated.php© OpportunityPendingAiAnalysisAfterStageChanged.php4 console [STAGING]© PlaylistShareRepository.phpC RunOpportunityAiAnalysis.phgC ImportOpportunityBatch.phpT ImportBatchJobTrait.phpTx: Auto vPlaygroundSa jiminny v© QuestionRepository.phpselect * from accounts where© Service.php© RoleChangeEventRepository.php1560026 A9 A22 X 3 X 103select * from contacts wherecrn contlourarion 1o = 51y anoC RoleRepository.php"podcast aualo unl"Co W .*O resultsTIT:1561* owner 15250 525705080© SearchRepository.php1504* contactlolol o0h0/441000 - CCEVLEyAlex Howes aletrait OpportunitySyncTrait© SnapshotRepository.phpBSZMZMI9 AY1563* concact 419247563 742723347700 - [EMAIL] 2026-© SocialAccountRepository.phpprivate function createOpportunity(string $crmId,$associations): ?Opportunity1564# company 4176133 47150650569© StageRepository.php1565# deal 7100953 410150124747© SubscriptionSetRepository.php$this->importExternalFieldData($properties, $opportunity->getId()):1566© TaskRepository.php785786$this->import0pportunityContacts($opportunity, $associations['contacts']);E1567SELECTCONCAT(u.id, LASE WHEN u.id = t.owner_id THEN(owner)' E© TeamAiContextRepository.php7871568u.email,© TeamDomainsRepository.php788if ($opportunity->wasRecentlyCreated) {-1569sa.*,© TeamInsightsRepository.php1891MarchAcavimes orewuoportunry. usourch opportunity->detloo.1570t.owner_id FROM social_accounts sa© TeamRepository.php.1571JOIN users u on u.id = sa.sociable_idc nemere.ostov.ono791=1572JUIN ceams t n→>l on t.1d = U.ceam_1dc) TimezoneRepositorv.php792recurn sopporcunity,1573Wreke U.teanl_ld- 400 and sa.provider - nupspota© TopicRepository.php793© TopicTriggerRepository.php794select * from features;© TrackRepository.php795/**-1576select * from team_features where feature_id = 40;© TranscriptionModelLocaleRepositc796* Update existing opportunity=1577© TranscriptionRepository.php7971578© TranscriptionSummaryRepository.1 usage1579select * from teams where id = 556; # owner: 18101, crm: 477_select * from crm_configurations where id = 477;© UserRepository.php798private function update0pportunity(string $crmId, array $properties, array $associations): Opportunity1580SELECT * FROM users WHERE id = 18101;© VocabularyRepository.php—1581SELECT• RulesSaccountid = $this->resolveAccountld(sassoclatzons..=1582CONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' E• Services$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);1585U.emall,> D Activity$stage = $businessProcess ? $this->re> D AjReports803Choose Declaration@ a resolveBusinessProcess (OpportunitySyncTrait .../app/Services/Crm/Hubspot/ServiceTraits)> D Avatar804$data = $this->build0pportunityData($@ o resolveBusinessProcess(OpportunitySyncTraitMatchActivitiesTest•/tests/Unit/Services/Crm/Hubspot/ServiceTrait> D Calendar805h_id› D Conference806$attributes = [1588WHERE u.team_id = 556 and sa.provider = 'integration-app';D Crm807'crm_configuration_id' => $this->config->getid(),1589D Bullhorn808'crm_provider_id' => $crmId,1590select * from opportunities where id = 7594349;Close8091591select * from opportunity_stages where opportunity_id = 759431Wcopper8101592select * from business_processes where id = 6024;> D CrmObjects811$values = array_merge($attributes, $data);1593select * from business_process_stages where stage_id = 16352;> M7 DecorateActivity814$opportunity = $this->crmEntityRepository->upsert0pportunity($attributes, $values);1594selert * +ronbusiness_process_stages where business_process_j> Dummy8131595select * fromStades were rean 10 = 4571> _ Helpers814v D Hubspot815$this->importExternalFieldData($properties, $opportunity->getId());1596select * fromteams where id = 459$this->update0pportunityAssociations($opportunity, $associations);1597SELECTD AccountSyncStrategy8161598CONCAT(u.id,CASE WHEN u.id = t.owner_id THEN[ Actions817return $opportunity;u.email,ContactSyncStrategy818sa.*,> DDTO819t.owner_id FROM social_accounts sa→ Irields2 usagesJOIN users u on u.id = sa.sociable_id> D Journal820private function resolveAccountId(array $associations): ?int{...}JOIN teams t 1.n<->1: on t.id = u.team_idMeradara857WHERE u.team_id = 459 and sa.provider ='hubspot';MOpportunitvSyncStrateay2 usages> MPagination858private function buildOpportunityDatadSELECT crm_provider_id, COUNT(*) as cnt, GROUP_CONCAT(id ORDEFProspectSearchStrateay854array soropercles.FROM stagesD Redis840?int $accountId,1008WHERE team_id = 459 AND type = 'opportunity'D ServiceTraits841?BusinessProcess $businessProcess,100%GROUP BY crm_provider_id€ OpportunitySyncTrait.ph842?Stage $stage1610HAVING cnt > 1;& SyncCrmEntities Trait.php): array €© SyncFieldsTrait.php$ownerId = null;Helper Code will help IDE to understand your Laravel app code. // Generate // Don't Show Anymore (today 8:59)Support Daily • in 2h 47 mAAutomatedRenortsCommandTest100% C•8 • Fri 17 Apr 12:13:18CascadeAutomated Report RetrInvestigating Opportur+D ...1. User logs an activity in the Ul with a different stage → ActivityController dispatches UpdateStagewole calls criberviepdateStage() → pushes the stage change to HubSpot3. HubSpot receives the update and fires a deal.propertyChange webhook back to Jiminny4. Webhook is collected in Redis → SyncObjects cycle processes it → import0pportunityBatch() → upsertOpportunity() with the stage HubSpot now has5. But HubSpot might return the previous stage if the update hasn't propagated, or if HubSpot rejectsthe change - writing a different stage id backcloudwatch loas to look for."opportunity stage has changed""[HubSpot] User changing opportunity stage from"2. SyncObjects job + HubspotWebhookBatchSyncStrategy draining Redis (second most likely)The SyncObiects job runs on a schedule and drains the Redis batch queue. If deal 7594349 's CRMvrovcerD keeos reaovearino in the reels seroecause the talledy nano er in moortbarchobiraltrequeues it after failures), then it gets reprocessed on every cycle.CloudWatch logs to look for:"[WebhookSyncBatchProcessor] Batch processing completed"- with config_id for team 459"[ImportOpportunityBatch]" or "[HubSpot] Failed to import opportunity""(HubSpot) Syncing opportunities using strateqy"Check if the same deal CRM ID appears in multiple consecutive [WebhookSyncBatchProcessor] runs.3. importExternalFieldData SyncCrmField writing back and triggering re-syncFrocessALaucomaclonAnalysiskesults calls servicsyncOpportunity before writing Al field valuesSince Al Automation is enabled for this team (you're seeing the OpportunityPendingAiAnalysisAfterStageChanged logs), even though this specific opportunity has no templates, other opportunities do - and their syncupporcunity calls ao through 1mporturu.ncy → which can atrect the keals queuestate.What to search in CloudWatchFor opportunity 7594349, search for these in order:"opportunity stage has changed""opportunityId":<UUID of 7594349>"[ImportOpportunityBatch]""failed() requeue"# Was a user manually changing stage?# Any UpdateStage dispatches# Is it being reprocessed by batch job?# Is batch job failing and requeueing?Also get the crm_provider_id of opportunity 7594349 from DB, then search:"<crm_provider_id>"# All mentions across logs - will show every sync triggerThat last one will definitively tell you which code path is writing it.C1l -Ask anything (24L)+ <>Code Claude Sonnet 4.6Winasun leams801:40uir-o( 4 spaces...
|
NULL
|
|
44926
|
949
|
0
|
2026-04-17T09:13:21.867667+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776417201867_m1.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
+FirefoxFileEditViewHistoryBookmarksProfilesToolsW +FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelp→meet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)BraveHelpError during desl CRM auto pi883 DEV SimineyPROO SEhttps://jiminny.sentry.io/fssues/6914839403/events/52918e1/182949e3a910a3e587d1d0c1/?projectz4507587754131456&sta…PROD EU Siminey@ My PRs• Assigned• To Review• Jiminny Prophet W...Pipelines - jminey.-7 JRIssuesE3 PROPHET-118Error during deal CRM auto populate extraction: All endpoints failed to generate a response1 /orm/deal/extract-feld-valuesU8Errors & OutagesBreached MetricsWarningsUser FeedbackResolveArchiveAll Envs24H ~Q Filter events..Cycot3.7KUsersConfigureAlerts300209100Apr 17 2:20 AM - 2:40 AM (UTC) |AoVWANApr 16 9,00 PM|Apr 17 3.00 AMEvents v in this issueID: 52918e1f|3.hours.agoJSON2 CPython 3.14.3• prod-eu~ Highlights4CrCaTrantirtzonCrroLsrm/deal/extract-field-values~ MessageError during deal CRN auto populate extraction: All endpoints failed to generate a responsev Breadcrumbs© Message - This event errorError during deal CRX auto populate extraction: All endpoints fasled to generate a response« app erfolA1l endpoints fasled to generate a responsePS17‹ >040x Confiuencelv) Service-Desk - Qu.Apr 17 9%runtimenamruntimeView all tags and feature flags100%_tract-feid-values79% prod-eu96X CPython 3.114.3FirstRecommendedView More EventsO CopyasJumpto: HighlightsBreadcrumbscontt/ Edithttp://prophet.J1m1noy.eu/scm/deal/extrasALACANILANTO Copy as~AO1. O20DSJ0S AMUTGAрC1402105.065 A901912:13 PMDaily - Processinga Support Daily - in 2h 47 m100% 1978 • Fri 17 Apr 12:13:216=• Q 88• Fri17 Apr 12:13@ AWSD All BookmarkeEvents.(totaD)Users (90d)4.2KPriority al~AssigneeLast seen 2 hours agoFirst seen 7 months ago~ Seer Autofx @Have Seer1. Determine the rootcause of your issue2. Outine a plan3. Create a code fox$ Start Analysisissue wracking• сеньоЭira> ActivityPop out this videoSimilar IssuesMerged Issuesllian KyuchukovNikolay NikolovVasil VasilevMihail MihaylovLukas Kovalik...
|
NULL
|
2665209983997442665
|
NULL
|
click
|
ocr
|
NULL
|
+FirefoxFileEditViewHistoryBookmarksProfilesToolsW +FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelp→meet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)BraveHelpError during desl CRM auto pi883 DEV SimineyPROO SEhttps://jiminny.sentry.io/fssues/6914839403/events/52918e1/182949e3a910a3e587d1d0c1/?projectz4507587754131456&sta…PROD EU Siminey@ My PRs• Assigned• To Review• Jiminny Prophet W...Pipelines - jminey.-7 JRIssuesE3 PROPHET-118Error during deal CRM auto populate extraction: All endpoints failed to generate a response1 /orm/deal/extract-feld-valuesU8Errors & OutagesBreached MetricsWarningsUser FeedbackResolveArchiveAll Envs24H ~Q Filter events..Cycot3.7KUsersConfigureAlerts300209100Apr 17 2:20 AM - 2:40 AM (UTC) |AoVWANApr 16 9,00 PM|Apr 17 3.00 AMEvents v in this issueID: 52918e1f|3.hours.agoJSON2 CPython 3.14.3• prod-eu~ Highlights4CrCaTrantirtzonCrroLsrm/deal/extract-field-values~ MessageError during deal CRN auto populate extraction: All endpoints failed to generate a responsev Breadcrumbs© Message - This event errorError during deal CRX auto populate extraction: All endpoints fasled to generate a response« app erfolA1l endpoints fasled to generate a responsePS17‹ >040x Confiuencelv) Service-Desk - Qu.Apr 17 9%runtimenamruntimeView all tags and feature flags100%_tract-feid-values79% prod-eu96X CPython 3.114.3FirstRecommendedView More EventsO CopyasJumpto: HighlightsBreadcrumbscontt/ Edithttp://prophet.J1m1noy.eu/scm/deal/extrasALACANILANTO Copy as~AO1. O20DSJ0S AMUTGAрC1402105.065 A901912:13 PMDaily - Processinga Support Daily - in 2h 47 m100% 1978 • Fri 17 Apr 12:13:216=• Q 88• Fri17 Apr 12:13@ AWSD All BookmarkeEvents.(totaD)Users (90d)4.2KPriority al~AssigneeLast seen 2 hours agoFirst seen 7 months ago~ Seer Autofx @Have Seer1. Determine the rootcause of your issue2. Outine a plan3. Create a code fox$ Start Analysisissue wracking• сеньоЭira> ActivityPop out this videoSimilar IssuesMerged Issuesllian KyuchukovNikolay NikolovVasil VasilevMihail MihaylovLukas Kovalik...
|
44924
|
|
45051
|
NULL
|
0
|
2026-04-17T09:18:20.296305+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776417500296_m1.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
FirefoxFileEditViewHistoryBookmarksProfilesToolsWi FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelpmeet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)‹$0Support Daily • in 2h 42 m100% 1978 • Fri 17 Apr 12:18:206=+CowewateheuraetenCloudWatch |eu-west-1CloudWatch | eu-west-1CloudWatch | eu-west-1togs insights | CloudWatcheu-west-1.console.aws.amazon.com/cloudwatch/home?region=eu-west-1#logsV2:logs-insightsS3FqueryDetailS3D-(end-*2026-04-17T04*3a12*3a59.000Z-start-'2026-04-17T04*3a09*3a00.000...Q Searo(Option+S) © Ask Amazon QCurope Greland)CloudWatchLogs Insights generalQuery definition infoQueries2026-04-17T04:09:002026-04-17T04:12:59a unified observabllity platform for a smoother experience, now in preview mode. Click here to try it out!UTC timezone2 Start tailingSaved queries• Fniter tw query nomdQuery scopeLog group nameProperty selectorSelect up to 50 log groupsBrowse: Log GroupsFacetsLookup tablesCreate queryClear all765720199711Show more chosen log groups (+29)fields @tinestarp, @nessape, elogstrean, elog| filter @nessage Like ^2110972e-0ef7-405f-bcd8-cbfc44198465*|1 linit 10000Coetnsion% Query generatorQ Fields• Saved and sample queriesQuery commandsRun queryFetching resultsUowesyeoouLogs (-)Patterns (-)VisualizationLogs (-)|• Summarize results)# Investigate +Share resultsExport resultsAdd to dashboardFetching data88898'E CloudShell• Calendar (1)• CleandDB (20)|• CRM (12)• Dialers (19)|• Emo (Activity Logs) (1)• Maits (1) |• Notetaker (31) |• Nudge (1)• Ogi (2)• Pipedrive (4)• Processing (4)• Prophet (1)• Recall (1)• Summary (15)• Tomov (4)-general - CWLI • +|_Social Account Status logs - CWU +|OB Errors - CWL +|Ouplicated track event - CWU +© 2026, Amazon Web Services, Inc, or its affilates.PivacyTerms• Q 8• Fri17 Apr 12:18.Finish update :nt ID: 7657-2019-9711EU.View_Only_©765720199711Leamn more tllian KyuchukovNikolay NikolovVasil VasilevMihail MihaylovCookie preferencesLukas Kovalik12:18 PM | Daily - Processing→...
|
NULL
|
-228846911853546535
|
NULL
|
click
|
ocr
|
NULL
|
FirefoxFileEditViewHistoryBookmarksProfilesToolsWi FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelpmeet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)‹$0Support Daily • in 2h 42 m100% 1978 • Fri 17 Apr 12:18:206=+CowewateheuraetenCloudWatch |eu-west-1CloudWatch | eu-west-1CloudWatch | eu-west-1togs insights | CloudWatcheu-west-1.console.aws.amazon.com/cloudwatch/home?region=eu-west-1#logsV2:logs-insightsS3FqueryDetailS3D-(end-*2026-04-17T04*3a12*3a59.000Z-start-'2026-04-17T04*3a09*3a00.000...Q Searo(Option+S) © Ask Amazon QCurope Greland)CloudWatchLogs Insights generalQuery definition infoQueries2026-04-17T04:09:002026-04-17T04:12:59a unified observabllity platform for a smoother experience, now in preview mode. Click here to try it out!UTC timezone2 Start tailingSaved queries• Fniter tw query nomdQuery scopeLog group nameProperty selectorSelect up to 50 log groupsBrowse: Log GroupsFacetsLookup tablesCreate queryClear all765720199711Show more chosen log groups (+29)fields @tinestarp, @nessape, elogstrean, elog| filter @nessage Like ^2110972e-0ef7-405f-bcd8-cbfc44198465*|1 linit 10000Coetnsion% Query generatorQ Fields• Saved and sample queriesQuery commandsRun queryFetching resultsUowesyeoouLogs (-)Patterns (-)VisualizationLogs (-)|• Summarize results)# Investigate +Share resultsExport resultsAdd to dashboardFetching data88898'E CloudShell• Calendar (1)• CleandDB (20)|• CRM (12)• Dialers (19)|• Emo (Activity Logs) (1)• Maits (1) |• Notetaker (31) |• Nudge (1)• Ogi (2)• Pipedrive (4)• Processing (4)• Prophet (1)• Recall (1)• Summary (15)• Tomov (4)-general - CWLI • +|_Social Account Status logs - CWU +|OB Errors - CWL +|Ouplicated track event - CWU +© 2026, Amazon Web Services, Inc, or its affilates.PivacyTerms• Q 8• Fri17 Apr 12:18.Finish update :nt ID: 7657-2019-9711EU.View_Only_©765720199711Leamn more tllian KyuchukovNikolay NikolovVasil VasilevMihail MihaylovCookie preferencesLukas Kovalik12:18 PM | Daily - Processing→...
|
NULL
|
|
45052
|
NULL
|
0
|
2026-04-17T09:18:21.203419+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776417501203_m2.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorToo PhpStormFileEditViewNavigateCodeLaravelRefactorToolsWindowHelpFV faVsco.js v#11894 on JY-18909-automated-reports-ask-jiminny kProjectv© AutomatedReportsService.php© SendReportJob.php© SendReportMailJob.php© ReportController.php© TokenBuilder.phpyratupanIuLaIonEyosItuly puy© PlaybookCategoryRepository.php© TeamSetupController.phpphp api.php• Filesystem.php© Team.php© CreateHeldActivityEvent.phpTrackProviderInstalledEvent.php© PlaybookRepository.php© RequestGenerateReportJob.php& OpportunitySyncTrait.php© Opportunity.php€ InteractsWithPivotTable.php© OpportunityUpdated.php© PlaylistActivityRepository.php© PlaylistRepository.php© OpportunityStageUpdated.php© OpportunityPendingAiAnalysisAfterStageChanged.php© PlaylistShareRepository.phpC RunOpportunityAiAnalysis.phpC ProcessAiAutomationAnalysisResults.phpC ImportOpportunityBatch.phpT ImportBatchJobTrait.php© QuestionRepository.php© Service.php© RoleChangeEventRepository.php© RoleRepository.phpQ-$stageX3Cc W .*13/29© SearchRepository.phptrait OpportunitySyncTrait© SnapshotRepository.phpA32 X2 X19 A Y104757private function createOpportunity(string $crmId, array $properties, array $associations): ?Opportunity© SocialAccountRepository.php172© StageRepository.phpYodif ($opportunity->wasRecentlyCreated) {© SubscriptionSetRepository.php789MatchActivitiesToNew0pportunity::dispatch($opportunity->getId());© TaskRepository.php790=180© TeamAiContextRepository.php791© TeamDomainsRepository.php792return Sopportunity;—181© TeamInsightsRepository.php182793© TeamRepository.php© ThemeRepository.php795/**E 185c) TimezoneRepositorv.php*Uooure exscino oodorcuncu180© TopicRepository.php© TopicTriggerRepository.php1871 usage© TrackRepository.phpprivate function updateOpportunity(string $crmId, array $properties, array $associations): Opportunity© TranscriptionModelLocaleRepositc799=188© TranscriptionRepository.php189800$accountId = $this->resolveAccountId($associations);© TranscriptionSummaryRepository.190801$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);191© UserRepository.php802$stage = $businessProcess ? $this->resolveStage($businessProcess, $properties[ 'dealstage'] ?? null) : null;© VocabularyRepository.php803192• Rules804$data = $this->buildOpporftunityData($properties, $accountId, $businessProcess, $stage);• Services805=193> D Activity806$attributes = [201> D AjReports807'crm_configuration_id' > $this->config->getId(),> D Avatar808809]:'crm_provider_id' => $crmId,225> D Calendar226250› D Conference810251D Crm811$values = array_merge($attributes, $data);D BullhornE275812$opportunity = $this->crmEntityRepository->upsert0pportunity($attributes, $values);276→ IClose813277> D Copper814$this->importExternalFieldData($properties, $opportunity->getId());=278> D CrmObjects815$this->update0pportunityAssociations(Sopportunity, $associations);279> D DecorateActivity816> Dummy817return Sopportunity;280> _ Helpers527v D Hubspot817D AccountSyncStrategy330› D Actions040private function resolveAccountId(array $associations): ?int{...}ContactSyncStrategy-331332> DDTOLusagesD Fields333838private function buildOpportunityData(334> D Journal839array $properties,Meradara840Pint $accountId,> 7 OpportunitySyncStrategy841?BusinessProcess $businessProcess,> MPagination842?Stage EsProspectSearchStrateay845D Redis844): array {nownerlo = nuuurv D ServiceTraits845$profile = null;€ OpportunitySyncTrait.ph846if (! empty($properties['hubspot_owner_id'])) {& SyncCrmEntities Trait.php847$ownerId = $properties['hubspot_owner_id'];=343© SyncFieldsTrait.php848$profile = $this->crmEntityRepository->findProfileByExternalId($this->config,(string) $ownerId);= custom.log= laravel.logA SF ljiminny@localhost](° scratch_1.jsonV connect.vueV Onboard.vueHs local liminnyalocalnostA console (EU]© CrmEntityRepository.php xfii crm_configurations [EU]A console [(PROD]Al console [STAGING]class crichclcyrepostcory4632AV120public function getInternalAccountToContactMap(ConfigurationHelper Code will help IDE to understand your Laravel app code. // Generate // Don't Show Anymore (today 8:59)4 usagespublic function getExternalStageMap(Configuration $configurato usagespublic function getStageForName(Configuration $configuratioTusdgepublic function getPipelineStageByConditions(BusinessProcess:return $businessProcess->stages()->Wnerecsconcurlons)->T/ST1 usagepublic function getBusinessProcessRecordType(BusinessProcessreturn $businessProcess->recordTypes()->first();16 usagespubuic tunccion gecupporzunityclosedscages(contiguracton conpublic function importAccount(Configuration $configuration, apublic function importContact(Configuration $configuration, apublic function importLead(Configuration $configuration, arrapublic function importOpportunity(Configuration $configuration,array$opportunityData,$matchFrom0therCrm = false,onarchvane = nuuu?string: Opportunityz usagespublic function upsertOpportunity(array $attributes, array $d** @var ?Opportunity $opportunity */$opportunity = Opportunity: :withTrashed() ->where($attribuif ($opportunity === null) {$opportunity = Opportunity::create($data);relse *ireturn $opportunity;public function importStage(Configuration $configuration, strSupport Daily • in 2h 42mAL AutomatedReportsCommandTestv100% z8 • Fri 17 Apr 12:18:20CascadeAutomated Report Retr> Investigating Oppori+D..Looking at reso lvestage() at line 961-963:• OpportunitySyncTrait.php:961-969if ($stage === null) {$this->importStages(null, $stageld);wif ($stage == null) ‹$this→>logger->info('[HubSpot] Stage does not exist = ' . $stageld);$this->cachedStages [$cacheKey] = $stage;return $stage;The bug is right here. importStages() return value is discarded - $stage stays null even after theImpont. Inen null cers cached in sthis->cachedstages scachekey .Tracing the full consequence with your dataYour pipeline: crm provider id = "default", business process id = 6024Its stages: IDs 16349, 16351, 16352, 16353, 16354, 16355, 16356, 20243Now if HubSpot sends dealstage = "20243_crm_provider_id" (some stage added on 2025-09-22), andthat stage's crm provider id is not in the DB yet (or the batch job runs before importStages has run forthe new stage):1. resolveStage() queries DB → not found → $stage = null2. Calls importStages (null, $stageId) → return value ignored → $stage still null3. Caches null for that cachekey4. Returns nullBack in buildOpportunityData):OpportunitySyncTrait.php:893-895if ($stage) {$data['stage_id'] = $stage->id;stage_id is NOT included in Sdata — it's simply omitted.Then in upsertOpportundty():• CrmEntityRepository.php:334-338if ($opportunity === null) {sondoruniry = U0oortuniry creare soarae1 else (Sopportunity->update($data):$opportunity→>update($data) is called without stage_id in $data . Eloquent's update() only setswhat's in the array — so the existing stage id on the opportunity is preserved. No dirty flag, no OpportunityStageUpdated event.So stage_id oscillation is NOT caused by a missing stageA missine/null stage simoly sklps the stace lo write — it won t cause osclllation.The actual oscillation cause given your dataYour oloeline nas stace 25243 a0oe: 220-05-7— monuns ater tne otnersAsk anything (24L)+ <>Code Claude Sonnet 4.6winasur leamsuir-o( 4 spaces...
|
NULL
|
2751341149230509581
|
NULL
|
visual_change
|
ocr
|
NULL
|
PhpStormFileEditViewNavigateCodeLaravelRefactorToo PhpStormFileEditViewNavigateCodeLaravelRefactorToolsWindowHelpFV faVsco.js v#11894 on JY-18909-automated-reports-ask-jiminny kProjectv© AutomatedReportsService.php© SendReportJob.php© SendReportMailJob.php© ReportController.php© TokenBuilder.phpyratupanIuLaIonEyosItuly puy© PlaybookCategoryRepository.php© TeamSetupController.phpphp api.php• Filesystem.php© Team.php© CreateHeldActivityEvent.phpTrackProviderInstalledEvent.php© PlaybookRepository.php© RequestGenerateReportJob.php& OpportunitySyncTrait.php© Opportunity.php€ InteractsWithPivotTable.php© OpportunityUpdated.php© PlaylistActivityRepository.php© PlaylistRepository.php© OpportunityStageUpdated.php© OpportunityPendingAiAnalysisAfterStageChanged.php© PlaylistShareRepository.phpC RunOpportunityAiAnalysis.phpC ProcessAiAutomationAnalysisResults.phpC ImportOpportunityBatch.phpT ImportBatchJobTrait.php© QuestionRepository.php© Service.php© RoleChangeEventRepository.php© RoleRepository.phpQ-$stageX3Cc W .*13/29© SearchRepository.phptrait OpportunitySyncTrait© SnapshotRepository.phpA32 X2 X19 A Y104757private function createOpportunity(string $crmId, array $properties, array $associations): ?Opportunity© SocialAccountRepository.php172© StageRepository.phpYodif ($opportunity->wasRecentlyCreated) {© SubscriptionSetRepository.php789MatchActivitiesToNew0pportunity::dispatch($opportunity->getId());© TaskRepository.php790=180© TeamAiContextRepository.php791© TeamDomainsRepository.php792return Sopportunity;—181© TeamInsightsRepository.php182793© TeamRepository.php© ThemeRepository.php795/**E 185c) TimezoneRepositorv.php*Uooure exscino oodorcuncu180© TopicRepository.php© TopicTriggerRepository.php1871 usage© TrackRepository.phpprivate function updateOpportunity(string $crmId, array $properties, array $associations): Opportunity© TranscriptionModelLocaleRepositc799=188© TranscriptionRepository.php189800$accountId = $this->resolveAccountId($associations);© TranscriptionSummaryRepository.190801$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);191© UserRepository.php802$stage = $businessProcess ? $this->resolveStage($businessProcess, $properties[ 'dealstage'] ?? null) : null;© VocabularyRepository.php803192• Rules804$data = $this->buildOpporftunityData($properties, $accountId, $businessProcess, $stage);• Services805=193> D Activity806$attributes = [201> D AjReports807'crm_configuration_id' > $this->config->getId(),> D Avatar808809]:'crm_provider_id' => $crmId,225> D Calendar226250› D Conference810251D Crm811$values = array_merge($attributes, $data);D BullhornE275812$opportunity = $this->crmEntityRepository->upsert0pportunity($attributes, $values);276→ IClose813277> D Copper814$this->importExternalFieldData($properties, $opportunity->getId());=278> D CrmObjects815$this->update0pportunityAssociations(Sopportunity, $associations);279> D DecorateActivity816> Dummy817return Sopportunity;280> _ Helpers527v D Hubspot817D AccountSyncStrategy330› D Actions040private function resolveAccountId(array $associations): ?int{...}ContactSyncStrategy-331332> DDTOLusagesD Fields333838private function buildOpportunityData(334> D Journal839array $properties,Meradara840Pint $accountId,> 7 OpportunitySyncStrategy841?BusinessProcess $businessProcess,> MPagination842?Stage EsProspectSearchStrateay845D Redis844): array {nownerlo = nuuurv D ServiceTraits845$profile = null;€ OpportunitySyncTrait.ph846if (! empty($properties['hubspot_owner_id'])) {& SyncCrmEntities Trait.php847$ownerId = $properties['hubspot_owner_id'];=343© SyncFieldsTrait.php848$profile = $this->crmEntityRepository->findProfileByExternalId($this->config,(string) $ownerId);= custom.log= laravel.logA SF ljiminny@localhost](° scratch_1.jsonV connect.vueV Onboard.vueHs local liminnyalocalnostA console (EU]© CrmEntityRepository.php xfii crm_configurations [EU]A console [(PROD]Al console [STAGING]class crichclcyrepostcory4632AV120public function getInternalAccountToContactMap(ConfigurationHelper Code will help IDE to understand your Laravel app code. // Generate // Don't Show Anymore (today 8:59)4 usagespublic function getExternalStageMap(Configuration $configurato usagespublic function getStageForName(Configuration $configuratioTusdgepublic function getPipelineStageByConditions(BusinessProcess:return $businessProcess->stages()->Wnerecsconcurlons)->T/ST1 usagepublic function getBusinessProcessRecordType(BusinessProcessreturn $businessProcess->recordTypes()->first();16 usagespubuic tunccion gecupporzunityclosedscages(contiguracton conpublic function importAccount(Configuration $configuration, apublic function importContact(Configuration $configuration, apublic function importLead(Configuration $configuration, arrapublic function importOpportunity(Configuration $configuration,array$opportunityData,$matchFrom0therCrm = false,onarchvane = nuuu?string: Opportunityz usagespublic function upsertOpportunity(array $attributes, array $d** @var ?Opportunity $opportunity */$opportunity = Opportunity: :withTrashed() ->where($attribuif ($opportunity === null) {$opportunity = Opportunity::create($data);relse *ireturn $opportunity;public function importStage(Configuration $configuration, strSupport Daily • in 2h 42mAL AutomatedReportsCommandTestv100% z8 • Fri 17 Apr 12:18:20CascadeAutomated Report Retr> Investigating Oppori+D..Looking at reso lvestage() at line 961-963:• OpportunitySyncTrait.php:961-969if ($stage === null) {$this->importStages(null, $stageld);wif ($stage == null) ‹$this→>logger->info('[HubSpot] Stage does not exist = ' . $stageld);$this->cachedStages [$cacheKey] = $stage;return $stage;The bug is right here. importStages() return value is discarded - $stage stays null even after theImpont. Inen null cers cached in sthis->cachedstages scachekey .Tracing the full consequence with your dataYour pipeline: crm provider id = "default", business process id = 6024Its stages: IDs 16349, 16351, 16352, 16353, 16354, 16355, 16356, 20243Now if HubSpot sends dealstage = "20243_crm_provider_id" (some stage added on 2025-09-22), andthat stage's crm provider id is not in the DB yet (or the batch job runs before importStages has run forthe new stage):1. resolveStage() queries DB → not found → $stage = null2. Calls importStages (null, $stageId) → return value ignored → $stage still null3. Caches null for that cachekey4. Returns nullBack in buildOpportunityData):OpportunitySyncTrait.php:893-895if ($stage) {$data['stage_id'] = $stage->id;stage_id is NOT included in Sdata — it's simply omitted.Then in upsertOpportundty():• CrmEntityRepository.php:334-338if ($opportunity === null) {sondoruniry = U0oortuniry creare soarae1 else (Sopportunity->update($data):$opportunity→>update($data) is called without stage_id in $data . Eloquent's update() only setswhat's in the array — so the existing stage id on the opportunity is preserved. No dirty flag, no OpportunityStageUpdated event.So stage_id oscillation is NOT caused by a missing stageA missine/null stage simoly sklps the stace lo write — it won t cause osclllation.The actual oscillation cause given your dataYour oloeline nas stace 25243 a0oe: 220-05-7— monuns ater tne otnersAsk anything (24L)+ <>Code Claude Sonnet 4.6winasur leamsuir-o( 4 spaces...
|
45050
|
|
45053
|
951
|
0
|
2026-04-17T09:18:40.745582+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776417520745_m1.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
FirefoxFileEditViewHistoryBookmarksProfilesToolsWi FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelpmeet.google.com/xpx-omah-rkn+‹$0Support Daily • in 2h 42 m100% <478 • Fri 17 Apr 12:18:40•••6=llian Kyuchukov (Presenting, annotating)40• Q 8• Fri17 Apr 12:18.CowewateheuraetenCloudWatch |eu-west-1CloudWatch | eu-west-1CloudWatch | eu-west-1eu-west-1.console.aws.amazon.com/cloudwatch/home?region=eu-west-1#logsV2:logs-insightsS3FqueryDetailS3D-(end-*2026-04-17T07*3a12*3a59.000Z-start-'2026-04-17T07*3a09*3a00.000...Finish update :Q Searo(Option+S) © Ask Amazon QCurope Greland)nt ID: 7657-2019-9711EU.View_Only@765720199711CloudWatchLogs Insights > _generalQuery definition infoQueries2026-04-17707:09:002026-04-17707:12:59a unified observabllity platform for a smoother experience, now in preview mode. Click here to try it out!UTC timezone2 Start tailingSaved queries• Fniter tw query nomdLeamn more tQuery scopeLog group nameTUUYCIlY SEICSIOSelect up to 50 log groupsBrowse: Log GroupsFacetsLookup tablesCreate queryClear all765720199711Show more chosen log groups (+29)fields @tinestap, @nessage, @logstrean, elog| filter @nessage Like *2110972e-Đef7-405f-bcd8-cbfc44198465*|1 linit 10000oetnsionDZ Query generatorQ Fields• Saved and sample queriesQuery commandsRun queryFetching resultsWowyeoouLogs (-)Patterns (-)VisualizationLogs (-)|• Summarize results)• Investigate Y[ Share resultsExport resultsAdd to dashboardFetching data88898'E CloudShell• Calendar (1)• CleandDB (20)• CRM (12)• Dialers (19)|• Emo (Activity Logs) (1)• Maits (1) |• Notetaker (31) |• Nudge (1)• Ogi (2)• Pipedrive (4)• Processing (4)• Prophet (1)• Recall (1)• Summary (15)• Tomov (4)-general - CWLI • +|_Social Account Status logs - CWU +OB Errors - CWL +|Ouplicated track event - CWU +© 2026, Amazon Web Services, Inc, or its affllates.PivacyTermsCookie preferencesllian KyuchukovNikolay NikolovVasil VasilevMihail MihaylovLukas Kovalik12:18 PM | Daily - Processing→...
|
NULL
|
-4418574330357038042
|
NULL
|
visual_change
|
ocr
|
NULL
|
FirefoxFileEditViewHistoryBookmarksProfilesToolsWi FirefoxFileEditViewHistoryBookmarksProfilesToolsWindowHelpmeet.google.com/xpx-omah-rkn+‹$0Support Daily • in 2h 42 m100% <478 • Fri 17 Apr 12:18:40•••6=llian Kyuchukov (Presenting, annotating)40• Q 8• Fri17 Apr 12:18.CowewateheuraetenCloudWatch |eu-west-1CloudWatch | eu-west-1CloudWatch | eu-west-1eu-west-1.console.aws.amazon.com/cloudwatch/home?region=eu-west-1#logsV2:logs-insightsS3FqueryDetailS3D-(end-*2026-04-17T07*3a12*3a59.000Z-start-'2026-04-17T07*3a09*3a00.000...Finish update :Q Searo(Option+S) © Ask Amazon QCurope Greland)nt ID: 7657-2019-9711EU.View_Only@765720199711CloudWatchLogs Insights > _generalQuery definition infoQueries2026-04-17707:09:002026-04-17707:12:59a unified observabllity platform for a smoother experience, now in preview mode. Click here to try it out!UTC timezone2 Start tailingSaved queries• Fniter tw query nomdLeamn more tQuery scopeLog group nameTUUYCIlY SEICSIOSelect up to 50 log groupsBrowse: Log GroupsFacetsLookup tablesCreate queryClear all765720199711Show more chosen log groups (+29)fields @tinestap, @nessage, @logstrean, elog| filter @nessage Like *2110972e-Đef7-405f-bcd8-cbfc44198465*|1 linit 10000oetnsionDZ Query generatorQ Fields• Saved and sample queriesQuery commandsRun queryFetching resultsWowyeoouLogs (-)Patterns (-)VisualizationLogs (-)|• Summarize results)• Investigate Y[ Share resultsExport resultsAdd to dashboardFetching data88898'E CloudShell• Calendar (1)• CleandDB (20)• CRM (12)• Dialers (19)|• Emo (Activity Logs) (1)• Maits (1) |• Notetaker (31) |• Nudge (1)• Ogi (2)• Pipedrive (4)• Processing (4)• Prophet (1)• Recall (1)• Summary (15)• Tomov (4)-general - CWLI • +|_Social Account Status logs - CWU +OB Errors - CWL +|Ouplicated track event - CWU +© 2026, Amazon Web Services, Inc, or its affllates.PivacyTermsCookie preferencesllian KyuchukovNikolay NikolovVasil VasilevMihail MihaylovLukas Kovalik12:18 PM | Daily - Processing→...
|
45051
|
|
45054
|
952
|
0
|
2026-04-17T09:18:43.720117+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776417523720_m2.jpg...
|
PhpStorm
|
faVsco.js – OpportunitySyncTrait.php
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
$stage
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
13/29
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Code changed:
Hide
Sync Changes
Hide This Notification
32
2
19
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\ServiceTraits;
use Carbon\Carbon;
use HubSpot\Client\Crm\Deals\Model\CollectionResponseAssociatedId;
use Jiminny\Exceptions\InvalidArgumentException;
use Jiminny\Models\Account;
use Exception;
use Jiminny\Component\DealInsights\Forecast\Forecast;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Exceptions\CrmException;
use Jiminny\Models\Opportunity;
use Illuminate\Support\Collection;
use Jiminny\Models\Stage;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Services\Crm\Hubspot\DealFieldsService;
use Jiminny\Services\Crm\Hubspot\OpportunitySyncStrategy\HubspotSingleSyncStrategy;
use Jiminny\Services\Crm\Hubspot\WebhookSyncBatchProcessor;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
/**
* Optimized sync methods for better performance
* These methods can be integrated into SyncCrmEntitiesTrait for significant performance gains
*/
trait OpportunitySyncTrait
{
private const int BATCH_SIZE = 100;
private const int BATCH_PROCESS_SIZE = 800;
protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
protected CrmEntityRepository $crmEntityRepository;
protected DealFieldsService $dealFieldsService;
private ?array $cachedClosedDealStages = null;
private array $cachedBusinessProcesses = [];
private array $cachedStages = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' .
$strategyName
);
$total = 0;
$lastId = null;
$buffer = [];
// HubspotWebhookBatchSyncStrategy returns empty generator, this is for other strategies
foreach ($syncStrategy->fetchOpportunities($parameters, $total, $lastId) as $hsOpportunity) {
$buffer[] = $hsOpportunity;
// process every 800 rows (fits < 1 000 association limit)
if (\count($buffer) >= self::BATCH_PROCESS_SIZE) {
$syncCount += $this->processOpportunityBatch($buffer);
$buffer = [];
}
}
// leftovers
if ($buffer) {
$syncCount += $this->processOpportunityBatch($buffer);
}
$reportedTotal += $total;
$lastSyncedId = $lastId;
}
} catch (\HubSpot\Client\Crm\Deals\ApiException | CrmException $e) {
$this->handleSyncException($e, $parameters);
}
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
]
);
return $reportedTotal;
}
private function handleSyncException(\Throwable $e, array $parameters): void
{
if (($parameters['since'] ?? null) instanceof Carbon) {
$parameters['since'] = $parameters['since']->toDateTimeString();
}
$parameters['config'] = $this->config->getId();
$this->logger->warning('[' . $this->getDisplayName() . '] Sync opportunities failed', [
'teamId' => $this->team->getUuid(),
'parameters' => $parameters,
'reason' => $e->getMessage(),
]);
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,
);
$parameters = [
'config' => $this->config,
'crm_id' => $crmId,
];
try {
if (! $strategy instanceof HubspotSingleSyncStrategy) {
throw new InvalidArgumentException('Strategy must by HubspotSingleSyncStrategy');
}
$hsOpportunity = $strategy->fetchOpportunity($parameters);
} catch (\HubSpot\Client\Crm\Deals\ApiException $e) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [
'teamId' => $this->team->getUuid(),
'crmId' => $crmId,
'reason' => $e->getMessage(),
]);
return null;
}
$hsOpportunity['associations'] = $this->convertDealAssociations($hsOpportunity['associations'] ?? []);
return $this->importOrUpdateOpportunity($hsOpportunity);
}
/**
* Process webhook-collected opportunity batches.
*
* Drains Redis sets containing company CRM IDs collected from webhook events
* and dispatches ImportOpportunityBatch jobs for batch processing.
*
* @return int Number of opportunity IDs dispatched to jobs
*/
public function batchSyncOpportunities(): int
{
$configId = $this->team->getCrmConfiguration()->getId();
return $this->batchProcessor->processBatchesForObjectType(
WebhookSyncBatchProcessor::OBJECT_TYPE_DEAL,
$configId
);
}
/**
* Import a batch of opportunities by their CRM IDs.
* Fetches opportunity data from HubSpot API and delegates to importOpportunityBatch().
*
* @param array<string> $crmIds HubSpot deal CRM IDs
*
* @return array{success: array, failed_ids: array, errors?: array<string, string>}
*/
public function importOpportunityBatchByIds(array $crmIds): array
{
$fields = $this->dealFieldsService->getFieldsForConfiguration($this->config);
$allDeals = [];
foreach (array_chunk($crmIds, self::BATCH_SIZE) as $chunk) {
$deals = $this->client->getOpportunitiesByIds($chunk, $fields);
foreach ($deals as $deal) {
$allDeals[] = $deal;
}
}
// IDs not returned by HubSpot are likely deleted or inaccessible deals.
// These are not failures — retrying won't bring them back.
$fetchedIds = array_map('strval', array_column($allDeals, 'id'));
$notFoundIds = array_values(array_diff(array_map('strval', $crmIds), $fetchedIds));
if (! empty($notFoundIds)) {
$this->logger->info('[' . $this->getDisplayName() . '] CRM IDs not found in HubSpot (likely deleted)', [
'teamId' => $this->team->getId(),
'notFoundCount' => \count($notFoundIds),
'notFoundIds' => $notFoundIds,
'requestedCount' => \count($crmIds),
'fetchedCount' => \count($allDeals),
]);
}
if (empty($allDeals)) {
return ['success' => [], 'failed_ids' => []];
}
return $this->importOpportunityBatch($allDeals);
}
private function getClosedDealStages(): array
{
if ($this->cachedClosedDealStages !== null) {
return $this->cachedClosedDealStages;
}
$stages = $this->crmEntityRepository->getOpportunityClosedStages($this->config);
$data = [
'lost' => [],
'won' => [],
];
foreach ($stages as $stage) {
if ($stage->probability == 0.00) {
$data['lost'][] = $stage->crm_provider_id;
}
if ($stage->probability == 100.00) {
$data['won'][] = $stage->crm_provider_id;
}
}
$this->cachedClosedDealStages = $data;
return $data;
}
/**
* Import deals into the database with pre-fetched associations.
*
* API calls here (getAssociationsData, getExistingOpportunityCrmIds) are NOT
* caught — if they throw, the exception propagates to ImportOpportunityBatch::handle()
* where Laravel retries the whole job with backoff. After all retries exhausted,
* failed() requeues all IDs to Redis.
*
* The per-deal loop catches exceptions individually. A deal can end up in three states:
* - success: imported/updated successfully
* - failed_ids: exception thrown (DB constraint violation, corrupt data, etc.)
* These are permanent issues — retrying won't fix them.
* - skipped (null): missing dependencies (no account, unknown pipeline/stage).
* This is acceptable — the deal cannot be imported until those exist.
*/
private function importOpportunityBatch(array $deals): array
{
$syncedOpportunities = [
'success' => [],
'failed_ids' => [],
];
$dealIds = array_column($deals, 'id');
// Shared association/existing-ID preparation is batch-level state. If it fails, rethrow so the
// queue job retries the whole batch and eventually requeues all deal IDs back to Redis.
try {
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$associationsData = $this->prepareAssociatedEntities($companyAssociations, $contactAssociations);
$existingCrmIds = $this->crmEntityRepository->getExistingOpportunityCrmIds(
$this->config,
array_map('strval', $dealIds)
);
$existingCrmIdSet = array_flip($existingCrmIds);
} catch (\Throwable $e) {
$this->logger->error('[' . $this->getDisplayName() . '] Failed to fetch associations or existing IDs', [
'teamId' => $this->team->getId(),
'dealCount' => count($dealIds),
'error' => $e->getMessage(),
]);
throw $e;
}
foreach ($deals as $deal) {
try {
$deal['associations'] = $this->prepareAssociationsForOpportunity(
$deal['id'],
$companyAssociations,
$contactAssociations,
$associationsData
);
$syncedOpportunity = $this->importOrUpdateOpportunity(
$deal,
isset($existingCrmIdSet[(string) $deal['id']])
);
if ($syncedOpportunity) {
$syncedOpportunities['success'][] = $syncedOpportunity;
}
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to import opportunity', [
'teamId' => $this->team->getId(),
'crmId' => $deal['id'],
'error' => $e->getMessage(),
]);
$syncedOpportunities['failed_ids'][] = $deal['id'];
$syncedOpportunities['errors'][$deal['id']] = $e->getMessage();
}
}
return $syncedOpportunities;
}
/**
* Prepare associated entities for opportunities with optimized batch processing
* Returns structured data with CRM ID to DB ID mappings for each opportunity
*/
private function prepareAssociatedEntities(array $companyAssociations, array $contactAssociations): array
{
// Step 1: Collect all unique company and contact IDs from associations
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
// Step 2: Batch sync missing entities and get CRM ID to DB ID mappings
$companyIdMappings = [];
$contactIdMappings = [];
if (! empty($allCompanyIds)) {
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
}
if (! empty($allContactIds)) {
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
}
return [
'company_id_mappings' => $companyIdMappings,
'contact_id_mappings' => $contactIdMappings,
];
}
/**
* Flatten association data to get unique IDs
*/
private function flattenAssociationIds(array $associations): array
{
$ids = [];
foreach ($associations as $dealAssociations) {
if (is_array($dealAssociations)) {
foreach ($dealAssociations as $id) {
$ids[$id] = true;
}
}
}
return array_keys($ids);
}
/**
* Batch sync missing accounts
*/
private function prepareAssociatedAccounts(array $companyIds): array
{
// Find which accounts already exist
$existingAccounts = $this->crmEntityRepository
->findAccountsByExternalIds($this->config, $companyIds);
$existingCompanyIds = $existingAccounts->pluck('crm_provider_id')->toArray();
$existingAccountsData = $existingAccounts->mapWithKeys(function ($account) {
return [$account->getCrmProviderId() => $account->getId()];
})->toArray();
$missingCompanyIds = array_diff($companyIds, $existingCompanyIds);
if (empty($missingCompanyIds)) {
return $existingAccountsData;
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing accounts', [
'teamId' => $this->team->getUuid(),
'total_companies' => count($companyIds),
'existing_companies' => count($existingCompanyIds),
'missing_companies' => count($missingCompanyIds),
]);
// we already have limit on opportunity ids count
// Initialize variable before try block
$syncedAccountsData = [];
try {
$syncedAccountsData = $this->batchSyncCrmObjects('companies', $missingCompanyIds);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing accounts', [
'size' => count($missingCompanyIds),
'error' => $e->getMessage(),
]);
$syncedAccountsData = [];
}
return $existingAccountsData + $syncedAccountsData;
}
/**
* Prepare associated contacts - find existing and sync missing ones
* Returns mapping of CRM ID to DB ID
*/
private function prepareAssociatedContacts(array $contactIds): array
{
// Find which contacts already exist
$existingContacts = $this->crmEntityRepository
->findContactsByExternalIds($this->config, $contactIds);
$existingContactIds = $existingContacts->pluck('crm_provider_id')->toArray();
// Create mapping for existing contacts
$existingContactsData = $existingContacts->mapWithKeys(function ($contact) {
return [$contact->getCrmProviderId() => $contact->getId()];
})->toArray();
$missingContactIds = array_diff($contactIds, $existingContactIds);
if (empty($missingContactIds)) {
return $existingContactsData;
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing contacts', [
'teamId' => $this->team->getUuid(),
'total_contacts' => count($contactIds),
'existing_contacts' => count($existingContactIds),
'missing_contacts' => count($missingContactIds),
]);
// Sync missing contacts using batch API
try {
$syncedContactsData = $this->batchSyncCrmObjects('contacts', $missingContactIds);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing contacts', [
'size' => count($missingContactIds),
'error' => $e->getMessage(),
]);
$syncedContactsData = [];
}
return $existingContactsData + $syncedContactsData;
}
private function batchSyncCrmObjects(string $objectType, array $crmIds): array
{
$syncObjects = [];
$crmObjectIds = array_values($crmIds);
foreach (array_chunk($crmObjectIds, self::BATCH_SIZE) as $chunk) {
try {
$objects = $objectType === 'companies' ?
$this->client->getCompaniesByIds($chunk, $this->getCompanyFields()) :
$this->client->getContactsByIds($chunk, $this->getContactFields());
foreach ($objects as $objectId => $objectData) {
$this->importCrmObject($objectType, (string) $objectId, $objectData, $syncObjects);
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch synced ' . $objectType, [
'requested_count' => count($chunk),
'synced_count' => count($objects),
]);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Batch ' . $objectType . ' sync failed', [
'ids' => $chunk,
'error' => $e->getMessage(),
]);
}
}
return $syncObjects;
}
private function importCrmObject(string $objectType, string $objectId, mixed $objectData, array &$syncObjects): void
{
try {
$object = $objectType === 'companies' ?
$this->importAccount($objectData) :
$this->importContact($objectData);
if ($object) {
$syncObjects[$object->getCrmProviderId()] = $object->getId();
}
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to import batch ' . $objectType, [
'id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
/**
* Prepare associations for a single opportunity
*
* The return value is an array with the following structure:
* [
* 'companies' => [
* $companyCrmId => $companyId,
* ...
* ],
* 'contacts' => [
* $contactCrmId => $contactId,
* ...
* ],
* 'account_id' => $accountId,
* ]
*/
private function prepareAssociationsForOpportunity(
string $oppCrmId,
array $companyAssociations,
array $contactAssociations,
array $associationsData
): array {
$associations = [
'companies' => [],
'contacts' => [],
'account_id' => null, // Primary account for opportunity
];
$oppCompanyIds = $companyAssociations[$oppCrmId] ?? [];
foreach ($oppCompanyIds as $companyCrmId) {
if (isset($associationsData['company_id_mappings'][$companyCrmId])) {
$associations['companies'][$companyCrmId] = $associationsData['company_id_mappings'][$companyCrmId];
// Set primary account (first company becomes primary account)
if ($associations['account_id'] === null) {
$associations['account_id'] = $associationsData['company_id_mappings'][$companyCrmId];
}
}
}
$oppContactIds = $contactAssociations[$oppCrmId] ?? [];
foreach ($oppContactIds as $contactCrmId) {
if (isset($associationsData['contact_id_mappings'][$contactCrmId])) {
$associations['contacts'][$contactCrmId] = $associationsData['contact_id_mappings'][$contactCrmId];
}
}
return $associations;
}
/**
* Update only associations for an opportunity
*/
private function updateOpportunityAssociations(Opportunity $opportunity, array $associations): void
{
// Update contact associations
$this->importOpportunityContacts($opportunity, $associations['contacts']);
// Update company (account) associations
$this->updateOpportunityAccount($opportunity, $associations['account_id']);
}
/**
* Remove all contact associations from an opportunity
*/
private function removeAllOpportunityContacts(Opportunity $opportunity): void
{
$currentCount = (int) $opportunity->contacts()->count();
if ($currentCount > 0) {
$opportunity->contacts()->detach();
$this->logger->info('[' . $this->getDisplayName() . '] Removed all contact associations', [
'opportunity_id' => $opportunity->getId(),
'removed_count' => $currentCount,
]);
}
}
private function updateOpportunityAccount(Opportunity $opportunity, ?int $accountId): void
{
if ($accountId === null) {
// No account ID provided - keep current account
return;
}
$currentAccountId = $opportunity->getAccountId();
// Only update if account has changed
if ($currentAccountId !== $accountId) {
$opportunity->account_id = $accountId;
$opportunity->save();
$this->logger->info('[' . $this->getDisplayName() . '] Updated opportunity account association', [
'opportunity_id' => $opportunity->getId(),
'old_account_id' => $currentAccountId,
'new_account_id' => $accountId,
]);
}
}
/**
* Find existing opportunities by external IDs (OPTIMIZED VERSION)
* Uses batch query for better performance
*/
private function findExistingOpportunities(array $crmIds): Collection
{
return $this->crmEntityRepository
->findOpportunitiesByExternalIds($this->config, $crmIds);
}
private function processOpportunityBatch(array $opportunities): int
{
$syncedOpportunities = $this->importOpportunityBatch($opportunities);
return count($syncedOpportunities['success'] ?? []);
}
/**
* Convert single deal associations from HubSpot format to internal format
* Handles both HubSpot SDK objects and array formats
*
* @param array $opportunityAssociations Raw associations from HubSpot API or pre-processed
*
* @return array Processed associations with DB IDs
*/
private function convertDealAssociations(array $opportunityAssociations): array
{
$associations = $this->initializeAssociationsStructure();
if (empty($opportunityAssociations)) {
return $associations;
}
$associationIds = $this->extractAssociationIds($opportunityAssociations);
$this->processCompanyAssociations($associationIds, $associations);
$this->processContactAssociations($associationIds, $associations);
return $associations;
}
private function initializeAssociationsStructure(): array
{
return [
'companies' => [],
'contacts' => [],
'account_id' => null, // Primary account for opportunity
];
}
private function extractAssociationIds(array $opportunityAssociations): array
{
$associationIds = [];
foreach ($opportunityAssociations as $type => $associationData) {
if (! empty($associationData)) {
$associationIds[$type] = $this->convertSingleDealAssociations($associationData);
}
}
return $associationIds;
}
private function processCompanyAssociations(array $associationIds, array &$associations): void
{
if (empty($associationIds['companies'])) {
return;
}
$companyId = $associationIds['companies'][0];
$account = $this->findOrSyncAccount($companyId);
if ($account instanceof Account) {
$associations['companies'][$companyId] = $account->getId();
$associations['account_id'] = $account->getId();
}
}
private function processContactAssociations(array $associationIds, array &$associations): void
{
if (empty($associationIds['contacts'])) {
return;
}
foreach ($associationIds['contacts'] as $contactId) {
$contact = $this->findOrSyncContact($contactId);
if ($contact instanceof Contact) {
$associations['contacts'][$contactId] = $contact->getId();
}
}
}
private function findOrSyncAccount(string $companyId): ?Account
{
$account = $this->crmEntityRepository->findAccountByExternalId($this->config, $companyId);
if (! $account instanceof Account) {
$account = $this->syncAccount($companyId);
}
return $account;
}
private function findOrSyncContact(string $contactId): ?Contact
{
$contact = $this->crmEntityRepository->findContactByExternalId($this->config, $contactId);
if (! $contact instanceof Contact) {
$contact = $this->syncContact($contactId);
}
return $contact;
}
private function convertSingleDealAssociations($opportunityAssociations = null): array
{
$associationData = [];
if ($opportunityAssociations === null) {
return $associationData;
}
// Handle array input (from extractAssociationIds)
if (is_array($opportunityAssociations)) {
return $opportunityAssociations;
}
// Handle CollectionResponseAssociatedId object
if ($opportunityAssociations instanceof CollectionResponseAssociatedId) {
foreach ($opportunityAssociations->getResults() as $association) {
$associationData[] = $association->getId();
}
}
return $associationData;
}
private function importOrUpdateOpportunity($crmData, ?bool $exists = null): ?Opportunity
{
if (empty($crmData['properties'])) {
return null;
}
$crmId = (string) $crmData['id'];
$properties = $crmData['properties'];
$associations = $crmData['associations'] ?? [];
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity($crmId, $properties, $associations);
} else {
return $this->createOpportunity($crmId, $properties, $associations);
}
}
/**
* Create new opportunity
*/
private function createOpportunity(string $crmId, array $properties, array $associations): ?Opportunity
{
$accountId = $this->resolveAccountId($associations);
if (! $accountId) {
return null;
}
$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);
if (! $businessProcess) {
return null;
}
$stage = $this->resolveStage($businessProcess, $properties['dealstage'] ?? null);
if (! $stage) {
return null;
}
$data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);
$attributes = [
'crm_configuration_id' => $this->config->getId(),
'crm_provider_id' => $crmId,
];
$values = array_merge($attributes, $data);
$opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);
$this->importExternalFieldData($properties, $opportunity->getId());
$this->importOpportunityContacts($opportunity, $associations['contacts']);
if ($opportunity->wasRecentlyCreated) {
MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());
}
return $opportunity;
}
/**
* Update existing opportunity
*/
private function updateOpportunity(string $crmId, array $properties, array $associations): Opportunity
{
$accountId = $this->resolveAccountId($associations);
$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);
$stage = $businessProcess ? $this->resolveStage($businessProcess, $properties['dealstage'] ?? null) : null;
$data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);
$attributes = [
'crm_configuration_id' => $this->config->getId(),
'crm_provider_id' => $crmId,
];
$values = array_merge($attributes, $data);
$opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);
$this->importExternalFieldData($properties, $opportunity->getId());
$this->updateOpportunityAssociations($opportunity, $associations);
return $opportunity;
}
private function resolveAccountId(array $associations): ?int
{
if (! empty($associations['accountId'])) {
return $associations['accountId'];
}
if (empty($associations)) {
return null;
}
// we can't resolve multiple account ids (currently SDK returns one company)
foreach ($associations['companies'] as $accountId) {
return $accountId;
}
return null;
}
private function buildOpportunityData(
array $properties,
?int $accountId,
?BusinessProcess $businessProcess,
?Stage $stage
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, (string) $ownerId);
}
$name = 'Unknown';
if (isset($properties['dealname'])) {
$name = mb_strimwidth($properties['dealname'], 0, 128);
}
$amount = $this->resolveAmount($properties);
$currency = $properties['deal_currency_code'] ?? null;
$closeDate = null;
if (! empty($properties['closedate'])) {
$closeDate = Carbon::parse($properties['closedate'])->format('Y-m-d');
}
$remotelyCreatedAt = null;
if (! empty($properties['createdate']) && strtotime($properties['createdate'])) {
$date = $this->parseCleanDatetime($properties['createdate']);
$remotelyCreatedAt = $date?->format('Y-m-d H:i:s');
}
$closedStages = $this->getClosedDealStages();
$isWon = in_array($properties['dealstage'], $closedStages['won']);
$isLost = in_array($properties['dealstage'], $closedStages['lost']);
$data = [
'team_id' => $this->team->getId(),
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => $name,
'value' => ! empty($amount) ? $amount : null,
'currency_code' => CurrencyFormatter::formatCode($currency),
'close_date' => $closeDate,
'is_closed' => $isWon || $isLost,
'is_won' => $isWon,
'remotely_created_at' => $remotelyCreatedAt,
'probability' => $this->resolveDealProbability($properties['hs_deal_stage_probability']),
'forecast_category' => $this->resolveForecastCategory($properties['hs_manual_forecast_category']),
];
if ($accountId) {
$data['account_id'] = $accountId;
}
if ($stage) {
$data['stage_id'] = $stage->id;
}
if ($businessProcess) {
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
if (isset($this->cachedBusinessProcesses[$pipelineId])) {
return $this->cachedBusinessProcesses[$pipelineId];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$pipelineId] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $businessProcess->getId() . ':' . $stageId;
if (isset($this->cachedStages[$cacheKey])) {
return $this->cachedStages[$cacheKey];
}
$stage = $this->crmEntityRepository->getPipelineStageByConditions(
$businessProcess,
[
'crm_provider_id' => $stageId,
'type' => Stage::TYPE_OPPORTUNITY,
]
);
if ($stage === null) {
$this->importStages(null, $stageId);
}
if ($stage === null) {
$this->logger->info('[HubSpot] Stage does not exist => ' . $stageId);
}
$this->cachedStages[$cacheKey] = $stage;
return $stage;
}
private function resolveAmount(array $properties): ?string
{
$amount = null;
if (! empty($properties['amount'])) {
$amount = str_replace(',', '', $properties['amount']);
}
if ($this->config->hasDefaultCurrencyFieldSet()) {
$valueFieldName = $this->config->getDefaultCurrencyField()->getCrmProviderId();
$amount = $properties[$valueFieldName] ?? $amount;
}
return $amount;
}
private function parseCleanDatetime(string $datetime): ?Carbon
{
// Treat pre-1980 values as invalid
$minValidDate = Carbon::parse('1980-01-01 00:00:00');
try {
$date = Carbon::parse($datetime);
if ($minValidDate->gt($date)) {
return null;
}
return $date;
} catch (Exception) {
return null; // On parse error, treat as null
}
}
private function resolveDealProbability(?string $stageProbability): int
{
if ($stageProbability === null) {
return 0;
}
$probability = (float) $stageProbability;
return $probability > 1 ? 0 : (int) ($probability * 100);
}
private function resolveForecastCategory(?string $forecastCategory): string
{
if (! $forecastCategory) {
return Forecast::FORECAST_CATEGORY_UNCATEGORIZED;
}
$forecastCategory = str_replace('_', ' ', $forecastCategory);
return ucwords(strtolower($forecastCategory));
}
private function importExternalFieldData(array $properties, int $opportunityId): void
{
$crmFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData($properties, $crmFields, $opportunityId);
}
private function importOpportunityContacts(Opportunity $opportunity, array $associations): void
{
// Handle empty or missing contact associations
if (empty($associations)) {
// Remove all existing contact associations if none provided
$this->removeAllOpportunityContacts($opportunity);
return;
}
// Use differential sync approach for better performance and accuracy
$this->syncOpportunityContactsDifferential($opportunity, $associations);
}
/**
* Sync opportunity contacts using differential approach
* This compares current vs new associations and only makes necessary changes
*/
private function syncOpportunityContactsDifferential(Opportunity $opportunity, array $contactAssociations): void
{
$currentContactCrmIds = $this->getCurrentContactCrmIds($opportunity);
$contactAssociationIds = array_keys($contactAssociations);
$contactsToAdd = array_diff($contactAssociationIds, $currentContactCrmIds);
$contactsToRemove = array_diff($currentContactCrmIds, $contactAssociationIds);
if (empty($contactsToAdd) && empty($contactsToRemove)) {
return;
}
$this->logContactAssociationChanges($opportunity, $currentContactCrmIds, $contactAssociations, $contactsToAdd, $contactsToRemove);
$this->removeContactAssociations($opportunity, $contactsToRemove);
$this->addContactAssociations($opportunity, $contactsToAdd, $contactAssociations);
}
private function getCurrentContactCrmIds(Opportunity $opportunity): array
{
return $opportunity->contacts()
->pluck('contacts.crm_provider_id')
->toArray();
}
private function logContactAssociationChanges(
Opportunity $opportunity,
array $currentContactCrmIds,
array $contactAssociations,
array $contactsToAdd,
array $contactsToRemove
): void {
$this->logger->info('[' . $this->getDisplayName() . '] Contact association changes', [
'opportunity_id' => $opportunity->getId(),
'current_contacts' => $currentContactCrmIds,
'new_contacts' => $contactAssociations,
'contacts_to_add' => $contactsToAdd,
'contacts_to_remove' => $contactsToRemove,
]);
}
private function removeContactAssociations(Opportunity $opportunity, array $contactsToRemove): void
{
if (empty($contactsToRemove)) {
return;
}
$contactsToDetach = $opportunity->contacts()
->whereIn('contacts.crm_provider_id', $contactsToRemove)
->pluck('contacts.id')
->toArray();
if (! empty($contactsToDetach)) {
$opportunity->contacts()->detach($contactsToDetach);
$this->logger->info('[' . $this->getDisplayName() . '] Removed contact associations', [
'opportunity_id' => $opportunity->getId(),
'removed_contact_crm_ids' => $contactsToRemove,
'removed_contact_count' => count($contactsToDetach),
]);
}
}
private function addContactAssociations(Opportunity $opportunity, array $contactsToAdd, array $contactAssociations): void
{
if (empty($contactsToAdd)) {
return;
}
$contactsAdded = [];
foreach ($contactsToAdd as $crmId) {
$id = $contactAssociations[$crmId];
if ($this->attachSingleContact($opportunity, (string) $crmId, $id)) {
$contactsAdded[] = $crmId;
}
}
$this->logAddedContacts($opportunity, $contactsAdded);
}
private function attachSingleContact(Opportunity $opportunity, string $crmId, int $id): bool
{
try {
$contact = $this->crmEntityRepository->findContactByConfigurationAndId($this->config, $id);
if (! $contact) {
return false;
}
return $this->performContactAttachment($opportunity, $contact, $crmId);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to add contact association', [
'opportunity_id' => $opportunity->getId(),
'contact_crm_id' => $crmId,
'error' => $e->getMessage(),
]);
return false;
}
}
private function performContactAttachment(Opportunity $opportunity, Contact $contact, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contact->getId(), [
'crm_provider_id' => $crmId,
]);
return true;
} catch (\Illuminate\Database\QueryException $e) {
if (str_contains($e->getMessage(), 'Duplicate entry')) {
$this->logger->info('[' . $this->getDisplayName() . '] Contact association already exists', [
'contact_id' => $contact->getId(),
'contact_crm_id' => $crmId,
'opportunity_id' => $opportunity->getId(),
]);
return false;
}
throw $e;
}
}
private function logAddedContacts(Opportunity $opportunity, array $contactsAdded): void
{
if (! empty($contactsAdded)) {
$this->logger->info('[' . $this->getDisplayName() . '] Added contact associations', [
'opportunity_id' => $opportunity->getId(),
'contacts_to_add_count' => count($contactsAdded),
'added_contact_crm_ids' => $contactsAdded,
'added_contacts_count' => count($contactsAdded),
]);
}
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
6
32
Previous Highlighted Error
Next Highlighted Error...
|
[{"role":"AXButton","text" [{"role":"AXButton","text":"Project: faVsco.js, menu","depth":5,"bounds":{"left":0.03046875,"top":0.017361112,"width":0.0453125,"height":0.022222223},"help_text":"~/jiminny/app","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"#11894 on JY-18909-automated-reports-ask-jiminny, menu","depth":5,"bounds":{"left":0.07578125,"top":0.017361112,"width":0.14960937,"height":0.022222223},"help_text":"Pull request #11894 exists for current branch JY-18909-automated-reports-ask-jiminny, but local branch is out of sync with remote","role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Start Listening for PHP Debug Connections","depth":5,"bounds":{"left":0.78515625,"top":0.017361112,"width":0.01328125,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"AutomatedReportsCommandTest","depth":6,"bounds":{"left":0.803125,"top":0.017361112,"width":0.09765625,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Run 'AutomatedReportsCommandTest'","depth":6,"bounds":{"left":0.9007813,"top":0.017361112,"width":0.01328125,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Debug 'AutomatedReportsCommandTest'","depth":6,"bounds":{"left":0.9140625,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9273437,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.96015626,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9734375,"top":0.017361112,"width":0.01328125,"height":0.022222223},"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.9867188,"top":0.017361112,"width":0.013281226,"height":0.022222223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Show Replace Field","depth":4,"bounds":{"left":0.12382813,"top":0.17777778,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Search History","depth":3,"bounds":{"left":0.13867188,"top":0.17708333,"width":0.00859375,"height":0.015277778},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextArea","text":"$stage","depth":4,"bounds":{"left":0.1515625,"top":0.17708333,"width":0.0515625,"height":0.013888889},"value":"$stage","role_description":"text entry area","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"New Line","depth":3,"bounds":{"left":0.21367188,"top":0.17708333,"width":0.00859375,"height":0.015277778},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Match Case","depth":3,"bounds":{"left":0.22539063,"top":0.17708333,"width":0.00859375,"height":0.015277778},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Words","depth":3,"bounds":{"left":0.23554687,"top":0.17708333,"width":0.00859375,"height":0.015277778},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Regex","depth":3,"bounds":{"left":0.24570313,"top":0.17708333,"width":0.00859375,"height":0.015277778},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Replace History","depth":3,"bounds":{"left":0.23320313,"top":1.0,"width":0.00859375,"height":0.0},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXTextField","text":"Replace","depth":4,"role_description":"text field","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"New Line","depth":3,"bounds":{"left":0.23320313,"top":1.0,"width":0.00859375,"height":0.0},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXCheckBox","text":"Preserve case","depth":3,"bounds":{"left":0.23320313,"top":1.0,"width":0.00859375,"height":0.0},"role_description":"checkbox","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"13/29","depth":4,"bounds":{"left":0.26171875,"top":0.17638889,"width":0.030078124,"height":0.015277778},"role_description":"text"},{"role":"AXButton","text":"Previous Occurrence","depth":4,"bounds":{"left":0.29179686,"top":0.17569445,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Next Occurrence","depth":4,"bounds":{"left":0.30195314,"top":0.17569445,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Filter Search Results","depth":4,"bounds":{"left":0.31210938,"top":0.17569445,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Open in Window, Multiple Cursors","depth":4,"bounds":{"left":0.32226562,"top":0.17569445,"width":0.01015625,"height":0.016666668},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXLink","text":"Click to highlight","depth":4,"role_description":"link","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Close","depth":4,"bounds":{"left":0.48828125,"top":0.17569445,"width":0.01015625,"height":0.016666668},"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.23320313,"top":1.0,"width":0.049609374,"height":0.0},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.23320313,"top":1.0,"width":0.01015625,"height":0.0},"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.23320313,"top":1.0,"width":0.01015625,"height":0.0},"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.23320313,"top":1.0,"width":0.01015625,"height":0.0},"role_description":"button","is_enabled":false,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"32","depth":4,"bounds":{"left":0.44726562,"top":0.20277777,"width":0.012109375,"height":0.013194445},"role_description":"text"},{"role":"AXStaticText","text":"2","depth":4,"bounds":{"left":0.46171874,"top":0.20277777,"width":0.009375,"height":0.013194445},"role_description":"text"},{"role":"AXStaticText","text":"19","depth":4,"bounds":{"left":0.4734375,"top":0.20277777,"width":0.011328125,"height":0.013194445},"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.48671874,"top":0.2013889,"width":0.00859375,"height":0.015972223},"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.4953125,"top":0.2013889,"width":0.008203125,"height":0.015972223},"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\\ServiceTraits;\n\nuse Carbon\\Carbon;\nuse HubSpot\\Client\\Crm\\Deals\\Model\\CollectionResponseAssociatedId;\nuse Jiminny\\Exceptions\\InvalidArgumentException;\nuse Jiminny\\Models\\Account;\nuse Exception;\nuse Jiminny\\Component\\DealInsights\\Forecast\\Forecast;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Models\\Opportunity;\nuse Illuminate\\Support\\Collection;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Services\\Crm\\Hubspot\\DealFieldsService;\nuse Jiminny\\Services\\Crm\\Hubspot\\OpportunitySyncStrategy\\HubspotSingleSyncStrategy;\nuse Jiminny\\Services\\Crm\\Hubspot\\WebhookSyncBatchProcessor;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\n\n/**\n * Optimized sync methods for better performance\n * These methods can be integrated into SyncCrmEntitiesTrait for significant performance gains\n */\ntrait OpportunitySyncTrait\n{\n private const int BATCH_SIZE = 100;\n private const int BATCH_PROCESS_SIZE = 800;\n\n protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n protected CrmEntityRepository $crmEntityRepository;\n protected DealFieldsService $dealFieldsService;\n\n private ?array $cachedClosedDealStages = null;\n private array $cachedBusinessProcesses = [];\n private array $cachedStages = [];\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n $parameters['config'] = $this->config;\n $syncCount = 0;\n $reportedTotal = 0;\n $lastSyncedId = [];\n\n try {\n foreach ($strategies as $strategyName => $syncStrategy) {\n $this->logger->info(\n '[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' .\n $strategyName\n );\n\n $total = 0;\n $lastId = null;\n $buffer = [];\n\n // HubspotWebhookBatchSyncStrategy returns empty generator, this is for other strategies\n foreach ($syncStrategy->fetchOpportunities($parameters, $total, $lastId) as $hsOpportunity) {\n $buffer[] = $hsOpportunity;\n\n // process every 800 rows (fits < 1 000 association limit)\n if (\\count($buffer) >= self::BATCH_PROCESS_SIZE) {\n $syncCount += $this->processOpportunityBatch($buffer);\n $buffer = [];\n }\n }\n\n // leftovers\n if ($buffer) {\n $syncCount += $this->processOpportunityBatch($buffer);\n }\n\n $reportedTotal += $total;\n $lastSyncedId = $lastId;\n }\n } catch (\\HubSpot\\Client\\Crm\\Deals\\ApiException | CrmException $e) {\n $this->handleSyncException($e, $parameters);\n }\n\n $this->logger->info(\n '[HubSpot] Synced opportunities',\n [\n 'team' => $this->team->getId(),\n 'sync_count' => $syncCount,\n 'total' => $reportedTotal,\n 'last_synced_id' => $lastSyncedId,\n ]\n );\n\n return $reportedTotal;\n }\n\n private function handleSyncException(\\Throwable $e, array $parameters): void\n {\n if (($parameters['since'] ?? null) instanceof Carbon) {\n $parameters['since'] = $parameters['since']->toDateTimeString();\n }\n $parameters['config'] = $this->config->getId();\n\n $this->logger->warning('[' . $this->getDisplayName() . '] Sync opportunities failed', [\n 'teamId' => $this->team->getUuid(),\n 'parameters' => $parameters,\n 'reason' => $e->getMessage(),\n ]);\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,\n );\n\n $parameters = [\n 'config' => $this->config,\n 'crm_id' => $crmId,\n ];\n\n try {\n if (! $strategy instanceof HubspotSingleSyncStrategy) {\n throw new InvalidArgumentException('Strategy must by HubspotSingleSyncStrategy');\n }\n\n $hsOpportunity = $strategy->fetchOpportunity($parameters);\n } catch (\\HubSpot\\Client\\Crm\\Deals\\ApiException $e) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [\n 'teamId' => $this->team->getUuid(),\n 'crmId' => $crmId,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n $hsOpportunity['associations'] = $this->convertDealAssociations($hsOpportunity['associations'] ?? []);\n\n return $this->importOrUpdateOpportunity($hsOpportunity);\n }\n\n /**\n * Process webhook-collected opportunity batches.\n *\n * Drains Redis sets containing company CRM IDs collected from webhook events\n * and dispatches ImportOpportunityBatch jobs for batch processing.\n *\n * @return int Number of opportunity IDs dispatched to jobs\n */\n public function batchSyncOpportunities(): int\n {\n $configId = $this->team->getCrmConfiguration()->getId();\n\n return $this->batchProcessor->processBatchesForObjectType(\n WebhookSyncBatchProcessor::OBJECT_TYPE_DEAL,\n $configId\n );\n }\n\n /**\n * Import a batch of opportunities by their CRM IDs.\n * Fetches opportunity data from HubSpot API and delegates to importOpportunityBatch().\n *\n * @param array<string> $crmIds HubSpot deal CRM IDs\n *\n * @return array{success: array, failed_ids: array, errors?: array<string, string>}\n */\n public function importOpportunityBatchByIds(array $crmIds): array\n {\n $fields = $this->dealFieldsService->getFieldsForConfiguration($this->config);\n\n $allDeals = [];\n foreach (array_chunk($crmIds, self::BATCH_SIZE) as $chunk) {\n $deals = $this->client->getOpportunitiesByIds($chunk, $fields);\n foreach ($deals as $deal) {\n $allDeals[] = $deal;\n }\n }\n\n // IDs not returned by HubSpot are likely deleted or inaccessible deals.\n // These are not failures — retrying won't bring them back.\n $fetchedIds = array_map('strval', array_column($allDeals, 'id'));\n $notFoundIds = array_values(array_diff(array_map('strval', $crmIds), $fetchedIds));\n\n if (! empty($notFoundIds)) {\n $this->logger->info('[' . $this->getDisplayName() . '] CRM IDs not found in HubSpot (likely deleted)', [\n 'teamId' => $this->team->getId(),\n 'notFoundCount' => \\count($notFoundIds),\n 'notFoundIds' => $notFoundIds,\n 'requestedCount' => \\count($crmIds),\n 'fetchedCount' => \\count($allDeals),\n ]);\n }\n\n if (empty($allDeals)) {\n return ['success' => [], 'failed_ids' => []];\n }\n\n return $this->importOpportunityBatch($allDeals);\n }\n\n private function getClosedDealStages(): array\n {\n if ($this->cachedClosedDealStages !== null) {\n return $this->cachedClosedDealStages;\n }\n\n $stages = $this->crmEntityRepository->getOpportunityClosedStages($this->config);\n $data = [\n 'lost' => [],\n 'won' => [],\n ];\n\n foreach ($stages as $stage) {\n if ($stage->probability == 0.00) {\n $data['lost'][] = $stage->crm_provider_id;\n }\n if ($stage->probability == 100.00) {\n $data['won'][] = $stage->crm_provider_id;\n }\n }\n\n $this->cachedClosedDealStages = $data;\n\n return $data;\n }\n\n /**\n * Import deals into the database with pre-fetched associations.\n *\n * API calls here (getAssociationsData, getExistingOpportunityCrmIds) are NOT\n * caught — if they throw, the exception propagates to ImportOpportunityBatch::handle()\n * where Laravel retries the whole job with backoff. After all retries exhausted,\n * failed() requeues all IDs to Redis.\n *\n * The per-deal loop catches exceptions individually. A deal can end up in three states:\n * - success: imported/updated successfully\n * - failed_ids: exception thrown (DB constraint violation, corrupt data, etc.)\n * These are permanent issues — retrying won't fix them.\n * - skipped (null): missing dependencies (no account, unknown pipeline/stage).\n * This is acceptable — the deal cannot be imported until those exist.\n */\n private function importOpportunityBatch(array $deals): array\n {\n $syncedOpportunities = [\n 'success' => [],\n 'failed_ids' => [],\n ];\n $dealIds = array_column($deals, 'id');\n\n // Shared association/existing-ID preparation is batch-level state. If it fails, rethrow so the\n // queue job retries the whole batch and eventually requeues all deal IDs back to Redis.\n try {\n $companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');\n $contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');\n\n $associationsData = $this->prepareAssociatedEntities($companyAssociations, $contactAssociations);\n\n $existingCrmIds = $this->crmEntityRepository->getExistingOpportunityCrmIds(\n $this->config,\n array_map('strval', $dealIds)\n );\n $existingCrmIdSet = array_flip($existingCrmIds);\n } catch (\\Throwable $e) {\n $this->logger->error('[' . $this->getDisplayName() . '] Failed to fetch associations or existing IDs', [\n 'teamId' => $this->team->getId(),\n 'dealCount' => count($dealIds),\n 'error' => $e->getMessage(),\n ]);\n\n throw $e;\n }\n\n foreach ($deals as $deal) {\n try {\n $deal['associations'] = $this->prepareAssociationsForOpportunity(\n $deal['id'],\n $companyAssociations,\n $contactAssociations,\n $associationsData\n );\n\n $syncedOpportunity = $this->importOrUpdateOpportunity(\n $deal,\n isset($existingCrmIdSet[(string) $deal['id']])\n );\n if ($syncedOpportunity) {\n $syncedOpportunities['success'][] = $syncedOpportunity;\n }\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to import opportunity', [\n 'teamId' => $this->team->getId(),\n 'crmId' => $deal['id'],\n 'error' => $e->getMessage(),\n ]);\n $syncedOpportunities['failed_ids'][] = $deal['id'];\n $syncedOpportunities['errors'][$deal['id']] = $e->getMessage();\n }\n }\n\n return $syncedOpportunities;\n }\n\n /**\n * Prepare associated entities for opportunities with optimized batch processing\n * Returns structured data with CRM ID to DB ID mappings for each opportunity\n */\n private function prepareAssociatedEntities(array $companyAssociations, array $contactAssociations): array\n {\n // Step 1: Collect all unique company and contact IDs from associations\n $allCompanyIds = $this->flattenAssociationIds($companyAssociations);\n $allContactIds = $this->flattenAssociationIds($contactAssociations);\n\n // Step 2: Batch sync missing entities and get CRM ID to DB ID mappings\n $companyIdMappings = [];\n $contactIdMappings = [];\n\n if (! empty($allCompanyIds)) {\n $companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);\n }\n\n if (! empty($allContactIds)) {\n $contactIdMappings = $this->prepareAssociatedContacts($allContactIds);\n }\n\n return [\n 'company_id_mappings' => $companyIdMappings,\n 'contact_id_mappings' => $contactIdMappings,\n ];\n }\n\n /**\n * Flatten association data to get unique IDs\n */\n private function flattenAssociationIds(array $associations): array\n {\n $ids = [];\n foreach ($associations as $dealAssociations) {\n if (is_array($dealAssociations)) {\n foreach ($dealAssociations as $id) {\n $ids[$id] = true;\n }\n }\n }\n\n return array_keys($ids);\n }\n\n /**\n * Batch sync missing accounts\n */\n private function prepareAssociatedAccounts(array $companyIds): array\n {\n // Find which accounts already exist\n $existingAccounts = $this->crmEntityRepository\n ->findAccountsByExternalIds($this->config, $companyIds);\n\n $existingCompanyIds = $existingAccounts->pluck('crm_provider_id')->toArray();\n\n $existingAccountsData = $existingAccounts->mapWithKeys(function ($account) {\n return [$account->getCrmProviderId() => $account->getId()];\n })->toArray();\n\n $missingCompanyIds = array_diff($companyIds, $existingCompanyIds);\n\n if (empty($missingCompanyIds)) {\n return $existingAccountsData;\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing accounts', [\n 'teamId' => $this->team->getUuid(),\n 'total_companies' => count($companyIds),\n 'existing_companies' => count($existingCompanyIds),\n 'missing_companies' => count($missingCompanyIds),\n ]);\n\n // we already have limit on opportunity ids count\n // Initialize variable before try block\n $syncedAccountsData = [];\n\n try {\n $syncedAccountsData = $this->batchSyncCrmObjects('companies', $missingCompanyIds);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing accounts', [\n 'size' => count($missingCompanyIds),\n 'error' => $e->getMessage(),\n ]);\n $syncedAccountsData = [];\n }\n\n return $existingAccountsData + $syncedAccountsData;\n }\n\n /**\n * Prepare associated contacts - find existing and sync missing ones\n * Returns mapping of CRM ID to DB ID\n */\n private function prepareAssociatedContacts(array $contactIds): array\n {\n // Find which contacts already exist\n $existingContacts = $this->crmEntityRepository\n ->findContactsByExternalIds($this->config, $contactIds);\n\n $existingContactIds = $existingContacts->pluck('crm_provider_id')->toArray();\n\n // Create mapping for existing contacts\n $existingContactsData = $existingContacts->mapWithKeys(function ($contact) {\n return [$contact->getCrmProviderId() => $contact->getId()];\n })->toArray();\n\n $missingContactIds = array_diff($contactIds, $existingContactIds);\n\n if (empty($missingContactIds)) {\n return $existingContactsData;\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing contacts', [\n 'teamId' => $this->team->getUuid(),\n 'total_contacts' => count($contactIds),\n 'existing_contacts' => count($existingContactIds),\n 'missing_contacts' => count($missingContactIds),\n ]);\n\n // Sync missing contacts using batch API\n try {\n $syncedContactsData = $this->batchSyncCrmObjects('contacts', $missingContactIds);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing contacts', [\n 'size' => count($missingContactIds),\n 'error' => $e->getMessage(),\n ]);\n $syncedContactsData = [];\n }\n\n return $existingContactsData + $syncedContactsData;\n }\n\n private function batchSyncCrmObjects(string $objectType, array $crmIds): array\n {\n $syncObjects = [];\n $crmObjectIds = array_values($crmIds);\n\n foreach (array_chunk($crmObjectIds, self::BATCH_SIZE) as $chunk) {\n try {\n $objects = $objectType === 'companies' ?\n $this->client->getCompaniesByIds($chunk, $this->getCompanyFields()) :\n $this->client->getContactsByIds($chunk, $this->getContactFields());\n\n foreach ($objects as $objectId => $objectData) {\n $this->importCrmObject($objectType, (string) $objectId, $objectData, $syncObjects);\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch synced ' . $objectType, [\n 'requested_count' => count($chunk),\n 'synced_count' => count($objects),\n ]);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Batch ' . $objectType . ' sync failed', [\n 'ids' => $chunk,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n return $syncObjects;\n }\n\n private function importCrmObject(string $objectType, string $objectId, mixed $objectData, array &$syncObjects): void\n {\n try {\n $object = $objectType === 'companies' ?\n $this->importAccount($objectData) :\n $this->importContact($objectData);\n\n if ($object) {\n $syncObjects[$object->getCrmProviderId()] = $object->getId();\n }\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to import batch ' . $objectType, [\n 'id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n /**\n * Prepare associations for a single opportunity\n *\n * The return value is an array with the following structure:\n * [\n * 'companies' => [\n * $companyCrmId => $companyId,\n * ...\n * ],\n * 'contacts' => [\n * $contactCrmId => $contactId,\n * ...\n * ],\n * 'account_id' => $accountId,\n * ]\n */\n private function prepareAssociationsForOpportunity(\n string $oppCrmId,\n array $companyAssociations,\n array $contactAssociations,\n array $associationsData\n ): array {\n $associations = [\n 'companies' => [],\n 'contacts' => [],\n 'account_id' => null, // Primary account for opportunity\n ];\n\n $oppCompanyIds = $companyAssociations[$oppCrmId] ?? [];\n foreach ($oppCompanyIds as $companyCrmId) {\n if (isset($associationsData['company_id_mappings'][$companyCrmId])) {\n $associations['companies'][$companyCrmId] = $associationsData['company_id_mappings'][$companyCrmId];\n\n // Set primary account (first company becomes primary account)\n if ($associations['account_id'] === null) {\n $associations['account_id'] = $associationsData['company_id_mappings'][$companyCrmId];\n }\n }\n }\n\n $oppContactIds = $contactAssociations[$oppCrmId] ?? [];\n foreach ($oppContactIds as $contactCrmId) {\n if (isset($associationsData['contact_id_mappings'][$contactCrmId])) {\n $associations['contacts'][$contactCrmId] = $associationsData['contact_id_mappings'][$contactCrmId];\n }\n }\n\n return $associations;\n }\n\n /**\n * Update only associations for an opportunity\n */\n private function updateOpportunityAssociations(Opportunity $opportunity, array $associations): void\n {\n // Update contact associations\n $this->importOpportunityContacts($opportunity, $associations['contacts']);\n\n // Update company (account) associations\n $this->updateOpportunityAccount($opportunity, $associations['account_id']);\n }\n\n /**\n * Remove all contact associations from an opportunity\n */\n private function removeAllOpportunityContacts(Opportunity $opportunity): void\n {\n $currentCount = (int) $opportunity->contacts()->count();\n\n if ($currentCount > 0) {\n $opportunity->contacts()->detach();\n\n $this->logger->info('[' . $this->getDisplayName() . '] Removed all contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'removed_count' => $currentCount,\n ]);\n }\n }\n\n private function updateOpportunityAccount(Opportunity $opportunity, ?int $accountId): void\n {\n if ($accountId === null) {\n // No account ID provided - keep current account\n return;\n }\n\n $currentAccountId = $opportunity->getAccountId();\n\n // Only update if account has changed\n if ($currentAccountId !== $accountId) {\n $opportunity->account_id = $accountId;\n $opportunity->save();\n\n $this->logger->info('[' . $this->getDisplayName() . '] Updated opportunity account association', [\n 'opportunity_id' => $opportunity->getId(),\n 'old_account_id' => $currentAccountId,\n 'new_account_id' => $accountId,\n ]);\n }\n }\n\n /**\n * Find existing opportunities by external IDs (OPTIMIZED VERSION)\n * Uses batch query for better performance\n */\n private function findExistingOpportunities(array $crmIds): Collection\n {\n return $this->crmEntityRepository\n ->findOpportunitiesByExternalIds($this->config, $crmIds);\n }\n\n private function processOpportunityBatch(array $opportunities): int\n {\n $syncedOpportunities = $this->importOpportunityBatch($opportunities);\n\n return count($syncedOpportunities['success'] ?? []);\n }\n\n /**\n * Convert single deal associations from HubSpot format to internal format\n * Handles both HubSpot SDK objects and array formats\n *\n * @param array $opportunityAssociations Raw associations from HubSpot API or pre-processed\n *\n * @return array Processed associations with DB IDs\n */\n private function convertDealAssociations(array $opportunityAssociations): array\n {\n $associations = $this->initializeAssociationsStructure();\n\n if (empty($opportunityAssociations)) {\n return $associations;\n }\n\n $associationIds = $this->extractAssociationIds($opportunityAssociations);\n\n $this->processCompanyAssociations($associationIds, $associations);\n $this->processContactAssociations($associationIds, $associations);\n\n return $associations;\n }\n\n private function initializeAssociationsStructure(): array\n {\n return [\n 'companies' => [],\n 'contacts' => [],\n 'account_id' => null, // Primary account for opportunity\n ];\n }\n\n private function extractAssociationIds(array $opportunityAssociations): array\n {\n $associationIds = [];\n\n foreach ($opportunityAssociations as $type => $associationData) {\n if (! empty($associationData)) {\n $associationIds[$type] = $this->convertSingleDealAssociations($associationData);\n }\n }\n\n return $associationIds;\n }\n\n private function processCompanyAssociations(array $associationIds, array &$associations): void\n {\n if (empty($associationIds['companies'])) {\n return;\n }\n\n $companyId = $associationIds['companies'][0];\n $account = $this->findOrSyncAccount($companyId);\n\n if ($account instanceof Account) {\n $associations['companies'][$companyId] = $account->getId();\n $associations['account_id'] = $account->getId();\n }\n }\n\n private function processContactAssociations(array $associationIds, array &$associations): void\n {\n if (empty($associationIds['contacts'])) {\n return;\n }\n\n foreach ($associationIds['contacts'] as $contactId) {\n $contact = $this->findOrSyncContact($contactId);\n\n if ($contact instanceof Contact) {\n $associations['contacts'][$contactId] = $contact->getId();\n }\n }\n }\n\n private function findOrSyncAccount(string $companyId): ?Account\n {\n $account = $this->crmEntityRepository->findAccountByExternalId($this->config, $companyId);\n\n if (! $account instanceof Account) {\n $account = $this->syncAccount($companyId);\n }\n\n return $account;\n }\n\n private function findOrSyncContact(string $contactId): ?Contact\n {\n $contact = $this->crmEntityRepository->findContactByExternalId($this->config, $contactId);\n\n if (! $contact instanceof Contact) {\n $contact = $this->syncContact($contactId);\n }\n\n return $contact;\n }\n\n private function convertSingleDealAssociations($opportunityAssociations = null): array\n {\n $associationData = [];\n\n if ($opportunityAssociations === null) {\n return $associationData;\n }\n\n // Handle array input (from extractAssociationIds)\n if (is_array($opportunityAssociations)) {\n return $opportunityAssociations;\n }\n\n // Handle CollectionResponseAssociatedId object\n if ($opportunityAssociations instanceof CollectionResponseAssociatedId) {\n foreach ($opportunityAssociations->getResults() as $association) {\n $associationData[] = $association->getId();\n }\n }\n\n return $associationData;\n }\n\n private function importOrUpdateOpportunity($crmData, ?bool $exists = null): ?Opportunity\n {\n if (empty($crmData['properties'])) {\n return null;\n }\n\n $crmId = (string) $crmData['id'];\n $properties = $crmData['properties'];\n $associations = $crmData['associations'] ?? [];\n\n $opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(\n $this->config,\n $crmId\n );\n\n if ($opportunityExists) {\n return $this->updateOpportunity($crmId, $properties, $associations);\n } else {\n return $this->createOpportunity($crmId, $properties, $associations);\n }\n }\n\n /**\n * Create new opportunity\n */\n private function createOpportunity(string $crmId, array $properties, array $associations): ?Opportunity\n {\n $accountId = $this->resolveAccountId($associations);\n if (! $accountId) {\n return null;\n }\n\n $businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);\n if (! $businessProcess) {\n return null;\n }\n\n $stage = $this->resolveStage($businessProcess, $properties['dealstage'] ?? null);\n if (! $stage) {\n return null;\n }\n\n $data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);\n\n $attributes = [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmId,\n ];\n\n $values = array_merge($attributes, $data);\n\n $opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);\n\n $this->importExternalFieldData($properties, $opportunity->getId());\n $this->importOpportunityContacts($opportunity, $associations['contacts']);\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n }\n\n /**\n * Update existing opportunity\n */\n private function updateOpportunity(string $crmId, array $properties, array $associations): Opportunity\n {\n $accountId = $this->resolveAccountId($associations);\n $businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);\n $stage = $businessProcess ? $this->resolveStage($businessProcess, $properties['dealstage'] ?? null) : null;\n\n $data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);\n\n $attributes = [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmId,\n ];\n\n $values = array_merge($attributes, $data);\n $opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);\n\n $this->importExternalFieldData($properties, $opportunity->getId());\n $this->updateOpportunityAssociations($opportunity, $associations);\n\n return $opportunity;\n }\n\n private function resolveAccountId(array $associations): ?int\n {\n if (! empty($associations['accountId'])) {\n return $associations['accountId'];\n }\n\n if (empty($associations)) {\n return null;\n }\n\n // we can't resolve multiple account ids (currently SDK returns one company)\n foreach ($associations['companies'] as $accountId) {\n return $accountId;\n }\n\n return null;\n }\n\n private function buildOpportunityData(\n array $properties,\n ?int $accountId,\n ?BusinessProcess $businessProcess,\n ?Stage $stage\n ): array {\n $ownerId = null;\n $profile = null;\n if (! empty($properties['hubspot_owner_id'])) {\n $ownerId = $properties['hubspot_owner_id'];\n $profile = $this->crmEntityRepository->findProfileByExternalId($this->config, (string) $ownerId);\n }\n\n $name = 'Unknown';\n if (isset($properties['dealname'])) {\n $name = mb_strimwidth($properties['dealname'], 0, 128);\n }\n\n $amount = $this->resolveAmount($properties);\n $currency = $properties['deal_currency_code'] ?? null;\n\n $closeDate = null;\n if (! empty($properties['closedate'])) {\n $closeDate = Carbon::parse($properties['closedate'])->format('Y-m-d');\n }\n\n $remotelyCreatedAt = null;\n if (! empty($properties['createdate']) && strtotime($properties['createdate'])) {\n $date = $this->parseCleanDatetime($properties['createdate']);\n $remotelyCreatedAt = $date?->format('Y-m-d H:i:s');\n }\n\n $closedStages = $this->getClosedDealStages();\n $isWon = in_array($properties['dealstage'], $closedStages['won']);\n $isLost = in_array($properties['dealstage'], $closedStages['lost']);\n\n $data = [\n 'team_id' => $this->team->getId(),\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => $name,\n 'value' => ! empty($amount) ? $amount : null,\n 'currency_code' => CurrencyFormatter::formatCode($currency),\n 'close_date' => $closeDate,\n 'is_closed' => $isWon || $isLost,\n 'is_won' => $isWon,\n 'remotely_created_at' => $remotelyCreatedAt,\n 'probability' => $this->resolveDealProbability($properties['hs_deal_stage_probability']),\n 'forecast_category' => $this->resolveForecastCategory($properties['hs_manual_forecast_category']),\n ];\n\n if ($accountId) {\n $data['account_id'] = $accountId;\n }\n\n if ($stage) {\n $data['stage_id'] = $stage->id;\n }\n\n if ($businessProcess) {\n $recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);\n if ($recordType) {\n $data['record_type_id'] = $recordType->id;\n }\n }\n\n return $data;\n }\n\n private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess\n {\n if ($pipelineId === null) {\n return null;\n }\n\n if (isset($this->cachedBusinessProcesses[$pipelineId])) {\n return $this->cachedBusinessProcesses[$pipelineId];\n }\n\n $businessProcess = $this->getBusinessProcess($pipelineId);\n\n if (! $businessProcess instanceof BusinessProcess) {\n $this->importStages();\n $businessProcess = $this->getBusinessProcess($pipelineId);\n }\n\n if (! $businessProcess instanceof BusinessProcess) {\n $this->logger->info(\n '[HubSpot] Deal is not attached to a pipeline',\n [\n 'pipeline' => $pipelineId]\n );\n }\n\n $this->cachedBusinessProcesses[$pipelineId] = $businessProcess;\n\n return $businessProcess;\n }\n\n private function getBusinessProcess(string $pipelineId): ?BusinessProcess\n {\n return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);\n }\n\n private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage\n {\n if (empty($stageId)) {\n return null;\n }\n\n $cacheKey = $businessProcess->getId() . ':' . $stageId;\n if (isset($this->cachedStages[$cacheKey])) {\n return $this->cachedStages[$cacheKey];\n }\n\n $stage = $this->crmEntityRepository->getPipelineStageByConditions(\n $businessProcess,\n [\n 'crm_provider_id' => $stageId,\n 'type' => Stage::TYPE_OPPORTUNITY,\n ]\n );\n\n if ($stage === null) {\n $this->importStages(null, $stageId);\n }\n\n if ($stage === null) {\n $this->logger->info('[HubSpot] Stage does not exist => ' . $stageId);\n }\n\n $this->cachedStages[$cacheKey] = $stage;\n\n return $stage;\n }\n\n private function resolveAmount(array $properties): ?string\n {\n $amount = null;\n if (! empty($properties['amount'])) {\n $amount = str_replace(',', '', $properties['amount']);\n }\n\n if ($this->config->hasDefaultCurrencyFieldSet()) {\n $valueFieldName = $this->config->getDefaultCurrencyField()->getCrmProviderId();\n $amount = $properties[$valueFieldName] ?? $amount;\n }\n\n return $amount;\n }\n\n private function parseCleanDatetime(string $datetime): ?Carbon\n {\n // Treat pre-1980 values as invalid\n $minValidDate = Carbon::parse('1980-01-01 00:00:00');\n\n try {\n $date = Carbon::parse($datetime);\n\n if ($minValidDate->gt($date)) {\n return null;\n }\n\n return $date;\n } catch (Exception) {\n return null; // On parse error, treat as null\n }\n }\n\n private function resolveDealProbability(?string $stageProbability): int\n {\n if ($stageProbability === null) {\n return 0;\n }\n\n $probability = (float) $stageProbability;\n\n return $probability > 1 ? 0 : (int) ($probability * 100);\n }\n\n private function resolveForecastCategory(?string $forecastCategory): string\n {\n if (! $forecastCategory) {\n return Forecast::FORECAST_CATEGORY_UNCATEGORIZED;\n }\n\n $forecastCategory = str_replace('_', ' ', $forecastCategory);\n\n return ucwords(strtolower($forecastCategory));\n }\n\n private function importExternalFieldData(array $properties, int $opportunityId): void\n {\n $crmFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData($properties, $crmFields, $opportunityId);\n }\n\n private function importOpportunityContacts(Opportunity $opportunity, array $associations): void\n {\n // Handle empty or missing contact associations\n if (empty($associations)) {\n // Remove all existing contact associations if none provided\n $this->removeAllOpportunityContacts($opportunity);\n\n return;\n }\n\n // Use differential sync approach for better performance and accuracy\n $this->syncOpportunityContactsDifferential($opportunity, $associations);\n }\n\n /**\n * Sync opportunity contacts using differential approach\n * This compares current vs new associations and only makes necessary changes\n */\n private function syncOpportunityContactsDifferential(Opportunity $opportunity, array $contactAssociations): void\n {\n $currentContactCrmIds = $this->getCurrentContactCrmIds($opportunity);\n $contactAssociationIds = array_keys($contactAssociations);\n\n $contactsToAdd = array_diff($contactAssociationIds, $currentContactCrmIds);\n $contactsToRemove = array_diff($currentContactCrmIds, $contactAssociationIds);\n\n if (empty($contactsToAdd) && empty($contactsToRemove)) {\n return;\n }\n\n $this->logContactAssociationChanges($opportunity, $currentContactCrmIds, $contactAssociations, $contactsToAdd, $contactsToRemove);\n\n $this->removeContactAssociations($opportunity, $contactsToRemove);\n $this->addContactAssociations($opportunity, $contactsToAdd, $contactAssociations);\n }\n\n private function getCurrentContactCrmIds(Opportunity $opportunity): array\n {\n return $opportunity->contacts()\n ->pluck('contacts.crm_provider_id')\n ->toArray();\n }\n\n private function logContactAssociationChanges(\n Opportunity $opportunity,\n array $currentContactCrmIds,\n array $contactAssociations,\n array $contactsToAdd,\n array $contactsToRemove\n ): void {\n $this->logger->info('[' . $this->getDisplayName() . '] Contact association changes', [\n 'opportunity_id' => $opportunity->getId(),\n 'current_contacts' => $currentContactCrmIds,\n 'new_contacts' => $contactAssociations,\n 'contacts_to_add' => $contactsToAdd,\n 'contacts_to_remove' => $contactsToRemove,\n ]);\n }\n\n private function removeContactAssociations(Opportunity $opportunity, array $contactsToRemove): void\n {\n if (empty($contactsToRemove)) {\n return;\n }\n\n $contactsToDetach = $opportunity->contacts()\n ->whereIn('contacts.crm_provider_id', $contactsToRemove)\n ->pluck('contacts.id')\n ->toArray();\n\n if (! empty($contactsToDetach)) {\n $opportunity->contacts()->detach($contactsToDetach);\n\n $this->logger->info('[' . $this->getDisplayName() . '] Removed contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'removed_contact_crm_ids' => $contactsToRemove,\n 'removed_contact_count' => count($contactsToDetach),\n ]);\n }\n }\n\n private function addContactAssociations(Opportunity $opportunity, array $contactsToAdd, array $contactAssociations): void\n {\n if (empty($contactsToAdd)) {\n return;\n }\n\n $contactsAdded = [];\n foreach ($contactsToAdd as $crmId) {\n $id = $contactAssociations[$crmId];\n\n if ($this->attachSingleContact($opportunity, (string) $crmId, $id)) {\n $contactsAdded[] = $crmId;\n }\n }\n\n $this->logAddedContacts($opportunity, $contactsAdded);\n }\n\n private function attachSingleContact(Opportunity $opportunity, string $crmId, int $id): bool\n {\n try {\n $contact = $this->crmEntityRepository->findContactByConfigurationAndId($this->config, $id);\n\n if (! $contact) {\n return false;\n }\n\n return $this->performContactAttachment($opportunity, $contact, $crmId);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to add contact association', [\n 'opportunity_id' => $opportunity->getId(),\n 'contact_crm_id' => $crmId,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n private function performContactAttachment(Opportunity $opportunity, Contact $contact, string $crmId): bool\n {\n try {\n $opportunity->contacts()->attach($contact->getId(), [\n 'crm_provider_id' => $crmId,\n ]);\n\n return true;\n } catch (\\Illuminate\\Database\\QueryException $e) {\n if (str_contains($e->getMessage(), 'Duplicate entry')) {\n $this->logger->info('[' . $this->getDisplayName() . '] Contact association already exists', [\n 'contact_id' => $contact->getId(),\n 'contact_crm_id' => $crmId,\n 'opportunity_id' => $opportunity->getId(),\n ]);\n\n return false;\n }\n\n throw $e;\n }\n }\n\n private function logAddedContacts(Opportunity $opportunity, array $contactsAdded): void\n {\n if (! empty($contactsAdded)) {\n $this->logger->info('[' . $this->getDisplayName() . '] Added contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'contacts_to_add_count' => count($contactsAdded),\n 'added_contact_crm_ids' => $contactsAdded,\n 'added_contacts_count' => count($contactsAdded),\n ]);\n }\n }\n}","depth":4,"value":"<?php\n\ndeclare(strict_types=1);\n\nnamespace Jiminny\\Services\\Crm\\Hubspot\\ServiceTraits;\n\nuse Carbon\\Carbon;\nuse HubSpot\\Client\\Crm\\Deals\\Model\\CollectionResponseAssociatedId;\nuse Jiminny\\Exceptions\\InvalidArgumentException;\nuse Jiminny\\Models\\Account;\nuse Exception;\nuse Jiminny\\Component\\DealInsights\\Forecast\\Forecast;\nuse Jiminny\\Jobs\\Crm\\MatchActivitiesToNewOpportunity;\nuse Jiminny\\Models\\Contact;\nuse Jiminny\\Models\\Crm\\BusinessProcess;\nuse Jiminny\\Exceptions\\CrmException;\nuse Jiminny\\Models\\Opportunity;\nuse Illuminate\\Support\\Collection;\nuse Jiminny\\Models\\Stage;\nuse Jiminny\\Repositories\\Crm\\CrmEntityRepository;\nuse Jiminny\\Services\\Crm\\Hubspot\\DealFieldsService;\nuse Jiminny\\Services\\Crm\\Hubspot\\OpportunitySyncStrategy\\HubspotSingleSyncStrategy;\nuse Jiminny\\Services\\Crm\\Hubspot\\WebhookSyncBatchProcessor;\nuse Jiminny\\Services\\Crm\\OpportunitySyncStrategyResolver;\nuse Jiminny\\Utils\\CurrencyFormatter;\n\n/**\n * Optimized sync methods for better performance\n * These methods can be integrated into SyncCrmEntitiesTrait for significant performance gains\n */\ntrait OpportunitySyncTrait\n{\n private const int BATCH_SIZE = 100;\n private const int BATCH_PROCESS_SIZE = 800;\n\n protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;\n protected CrmEntityRepository $crmEntityRepository;\n protected DealFieldsService $dealFieldsService;\n\n private ?array $cachedClosedDealStages = null;\n private array $cachedBusinessProcesses = [];\n private array $cachedStages = [];\n\n public function syncOpportunities(array $parameters, ?string $strategy = null): int\n {\n $strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);\n $parameters['config'] = $this->config;\n $syncCount = 0;\n $reportedTotal = 0;\n $lastSyncedId = [];\n\n try {\n foreach ($strategies as $strategyName => $syncStrategy) {\n $this->logger->info(\n '[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' .\n $strategyName\n );\n\n $total = 0;\n $lastId = null;\n $buffer = [];\n\n // HubspotWebhookBatchSyncStrategy returns empty generator, this is for other strategies\n foreach ($syncStrategy->fetchOpportunities($parameters, $total, $lastId) as $hsOpportunity) {\n $buffer[] = $hsOpportunity;\n\n // process every 800 rows (fits < 1 000 association limit)\n if (\\count($buffer) >= self::BATCH_PROCESS_SIZE) {\n $syncCount += $this->processOpportunityBatch($buffer);\n $buffer = [];\n }\n }\n\n // leftovers\n if ($buffer) {\n $syncCount += $this->processOpportunityBatch($buffer);\n }\n\n $reportedTotal += $total;\n $lastSyncedId = $lastId;\n }\n } catch (\\HubSpot\\Client\\Crm\\Deals\\ApiException | CrmException $e) {\n $this->handleSyncException($e, $parameters);\n }\n\n $this->logger->info(\n '[HubSpot] Synced opportunities',\n [\n 'team' => $this->team->getId(),\n 'sync_count' => $syncCount,\n 'total' => $reportedTotal,\n 'last_synced_id' => $lastSyncedId,\n ]\n );\n\n return $reportedTotal;\n }\n\n private function handleSyncException(\\Throwable $e, array $parameters): void\n {\n if (($parameters['since'] ?? null) instanceof Carbon) {\n $parameters['since'] = $parameters['since']->toDateTimeString();\n }\n $parameters['config'] = $this->config->getId();\n\n $this->logger->warning('[' . $this->getDisplayName() . '] Sync opportunities failed', [\n 'teamId' => $this->team->getUuid(),\n 'parameters' => $parameters,\n 'reason' => $e->getMessage(),\n ]);\n }\n\n /**\n * @inheritdoc\n */\n public function syncOpportunity(string $crmId): ?Opportunity\n {\n $strategy = $this->opportunitySyncStrategyResolver->resolve(\n $this->config,\n OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,\n );\n\n $parameters = [\n 'config' => $this->config,\n 'crm_id' => $crmId,\n ];\n\n try {\n if (! $strategy instanceof HubspotSingleSyncStrategy) {\n throw new InvalidArgumentException('Strategy must by HubspotSingleSyncStrategy');\n }\n\n $hsOpportunity = $strategy->fetchOpportunity($parameters);\n } catch (\\HubSpot\\Client\\Crm\\Deals\\ApiException $e) {\n $this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [\n 'teamId' => $this->team->getUuid(),\n 'crmId' => $crmId,\n 'reason' => $e->getMessage(),\n ]);\n\n return null;\n }\n\n $hsOpportunity['associations'] = $this->convertDealAssociations($hsOpportunity['associations'] ?? []);\n\n return $this->importOrUpdateOpportunity($hsOpportunity);\n }\n\n /**\n * Process webhook-collected opportunity batches.\n *\n * Drains Redis sets containing company CRM IDs collected from webhook events\n * and dispatches ImportOpportunityBatch jobs for batch processing.\n *\n * @return int Number of opportunity IDs dispatched to jobs\n */\n public function batchSyncOpportunities(): int\n {\n $configId = $this->team->getCrmConfiguration()->getId();\n\n return $this->batchProcessor->processBatchesForObjectType(\n WebhookSyncBatchProcessor::OBJECT_TYPE_DEAL,\n $configId\n );\n }\n\n /**\n * Import a batch of opportunities by their CRM IDs.\n * Fetches opportunity data from HubSpot API and delegates to importOpportunityBatch().\n *\n * @param array<string> $crmIds HubSpot deal CRM IDs\n *\n * @return array{success: array, failed_ids: array, errors?: array<string, string>}\n */\n public function importOpportunityBatchByIds(array $crmIds): array\n {\n $fields = $this->dealFieldsService->getFieldsForConfiguration($this->config);\n\n $allDeals = [];\n foreach (array_chunk($crmIds, self::BATCH_SIZE) as $chunk) {\n $deals = $this->client->getOpportunitiesByIds($chunk, $fields);\n foreach ($deals as $deal) {\n $allDeals[] = $deal;\n }\n }\n\n // IDs not returned by HubSpot are likely deleted or inaccessible deals.\n // These are not failures — retrying won't bring them back.\n $fetchedIds = array_map('strval', array_column($allDeals, 'id'));\n $notFoundIds = array_values(array_diff(array_map('strval', $crmIds), $fetchedIds));\n\n if (! empty($notFoundIds)) {\n $this->logger->info('[' . $this->getDisplayName() . '] CRM IDs not found in HubSpot (likely deleted)', [\n 'teamId' => $this->team->getId(),\n 'notFoundCount' => \\count($notFoundIds),\n 'notFoundIds' => $notFoundIds,\n 'requestedCount' => \\count($crmIds),\n 'fetchedCount' => \\count($allDeals),\n ]);\n }\n\n if (empty($allDeals)) {\n return ['success' => [], 'failed_ids' => []];\n }\n\n return $this->importOpportunityBatch($allDeals);\n }\n\n private function getClosedDealStages(): array\n {\n if ($this->cachedClosedDealStages !== null) {\n return $this->cachedClosedDealStages;\n }\n\n $stages = $this->crmEntityRepository->getOpportunityClosedStages($this->config);\n $data = [\n 'lost' => [],\n 'won' => [],\n ];\n\n foreach ($stages as $stage) {\n if ($stage->probability == 0.00) {\n $data['lost'][] = $stage->crm_provider_id;\n }\n if ($stage->probability == 100.00) {\n $data['won'][] = $stage->crm_provider_id;\n }\n }\n\n $this->cachedClosedDealStages = $data;\n\n return $data;\n }\n\n /**\n * Import deals into the database with pre-fetched associations.\n *\n * API calls here (getAssociationsData, getExistingOpportunityCrmIds) are NOT\n * caught — if they throw, the exception propagates to ImportOpportunityBatch::handle()\n * where Laravel retries the whole job with backoff. After all retries exhausted,\n * failed() requeues all IDs to Redis.\n *\n * The per-deal loop catches exceptions individually. A deal can end up in three states:\n * - success: imported/updated successfully\n * - failed_ids: exception thrown (DB constraint violation, corrupt data, etc.)\n * These are permanent issues — retrying won't fix them.\n * - skipped (null): missing dependencies (no account, unknown pipeline/stage).\n * This is acceptable — the deal cannot be imported until those exist.\n */\n private function importOpportunityBatch(array $deals): array\n {\n $syncedOpportunities = [\n 'success' => [],\n 'failed_ids' => [],\n ];\n $dealIds = array_column($deals, 'id');\n\n // Shared association/existing-ID preparation is batch-level state. If it fails, rethrow so the\n // queue job retries the whole batch and eventually requeues all deal IDs back to Redis.\n try {\n $companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');\n $contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');\n\n $associationsData = $this->prepareAssociatedEntities($companyAssociations, $contactAssociations);\n\n $existingCrmIds = $this->crmEntityRepository->getExistingOpportunityCrmIds(\n $this->config,\n array_map('strval', $dealIds)\n );\n $existingCrmIdSet = array_flip($existingCrmIds);\n } catch (\\Throwable $e) {\n $this->logger->error('[' . $this->getDisplayName() . '] Failed to fetch associations or existing IDs', [\n 'teamId' => $this->team->getId(),\n 'dealCount' => count($dealIds),\n 'error' => $e->getMessage(),\n ]);\n\n throw $e;\n }\n\n foreach ($deals as $deal) {\n try {\n $deal['associations'] = $this->prepareAssociationsForOpportunity(\n $deal['id'],\n $companyAssociations,\n $contactAssociations,\n $associationsData\n );\n\n $syncedOpportunity = $this->importOrUpdateOpportunity(\n $deal,\n isset($existingCrmIdSet[(string) $deal['id']])\n );\n if ($syncedOpportunity) {\n $syncedOpportunities['success'][] = $syncedOpportunity;\n }\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to import opportunity', [\n 'teamId' => $this->team->getId(),\n 'crmId' => $deal['id'],\n 'error' => $e->getMessage(),\n ]);\n $syncedOpportunities['failed_ids'][] = $deal['id'];\n $syncedOpportunities['errors'][$deal['id']] = $e->getMessage();\n }\n }\n\n return $syncedOpportunities;\n }\n\n /**\n * Prepare associated entities for opportunities with optimized batch processing\n * Returns structured data with CRM ID to DB ID mappings for each opportunity\n */\n private function prepareAssociatedEntities(array $companyAssociations, array $contactAssociations): array\n {\n // Step 1: Collect all unique company and contact IDs from associations\n $allCompanyIds = $this->flattenAssociationIds($companyAssociations);\n $allContactIds = $this->flattenAssociationIds($contactAssociations);\n\n // Step 2: Batch sync missing entities and get CRM ID to DB ID mappings\n $companyIdMappings = [];\n $contactIdMappings = [];\n\n if (! empty($allCompanyIds)) {\n $companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);\n }\n\n if (! empty($allContactIds)) {\n $contactIdMappings = $this->prepareAssociatedContacts($allContactIds);\n }\n\n return [\n 'company_id_mappings' => $companyIdMappings,\n 'contact_id_mappings' => $contactIdMappings,\n ];\n }\n\n /**\n * Flatten association data to get unique IDs\n */\n private function flattenAssociationIds(array $associations): array\n {\n $ids = [];\n foreach ($associations as $dealAssociations) {\n if (is_array($dealAssociations)) {\n foreach ($dealAssociations as $id) {\n $ids[$id] = true;\n }\n }\n }\n\n return array_keys($ids);\n }\n\n /**\n * Batch sync missing accounts\n */\n private function prepareAssociatedAccounts(array $companyIds): array\n {\n // Find which accounts already exist\n $existingAccounts = $this->crmEntityRepository\n ->findAccountsByExternalIds($this->config, $companyIds);\n\n $existingCompanyIds = $existingAccounts->pluck('crm_provider_id')->toArray();\n\n $existingAccountsData = $existingAccounts->mapWithKeys(function ($account) {\n return [$account->getCrmProviderId() => $account->getId()];\n })->toArray();\n\n $missingCompanyIds = array_diff($companyIds, $existingCompanyIds);\n\n if (empty($missingCompanyIds)) {\n return $existingAccountsData;\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing accounts', [\n 'teamId' => $this->team->getUuid(),\n 'total_companies' => count($companyIds),\n 'existing_companies' => count($existingCompanyIds),\n 'missing_companies' => count($missingCompanyIds),\n ]);\n\n // we already have limit on opportunity ids count\n // Initialize variable before try block\n $syncedAccountsData = [];\n\n try {\n $syncedAccountsData = $this->batchSyncCrmObjects('companies', $missingCompanyIds);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing accounts', [\n 'size' => count($missingCompanyIds),\n 'error' => $e->getMessage(),\n ]);\n $syncedAccountsData = [];\n }\n\n return $existingAccountsData + $syncedAccountsData;\n }\n\n /**\n * Prepare associated contacts - find existing and sync missing ones\n * Returns mapping of CRM ID to DB ID\n */\n private function prepareAssociatedContacts(array $contactIds): array\n {\n // Find which contacts already exist\n $existingContacts = $this->crmEntityRepository\n ->findContactsByExternalIds($this->config, $contactIds);\n\n $existingContactIds = $existingContacts->pluck('crm_provider_id')->toArray();\n\n // Create mapping for existing contacts\n $existingContactsData = $existingContacts->mapWithKeys(function ($contact) {\n return [$contact->getCrmProviderId() => $contact->getId()];\n })->toArray();\n\n $missingContactIds = array_diff($contactIds, $existingContactIds);\n\n if (empty($missingContactIds)) {\n return $existingContactsData;\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing contacts', [\n 'teamId' => $this->team->getUuid(),\n 'total_contacts' => count($contactIds),\n 'existing_contacts' => count($existingContactIds),\n 'missing_contacts' => count($missingContactIds),\n ]);\n\n // Sync missing contacts using batch API\n try {\n $syncedContactsData = $this->batchSyncCrmObjects('contacts', $missingContactIds);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing contacts', [\n 'size' => count($missingContactIds),\n 'error' => $e->getMessage(),\n ]);\n $syncedContactsData = [];\n }\n\n return $existingContactsData + $syncedContactsData;\n }\n\n private function batchSyncCrmObjects(string $objectType, array $crmIds): array\n {\n $syncObjects = [];\n $crmObjectIds = array_values($crmIds);\n\n foreach (array_chunk($crmObjectIds, self::BATCH_SIZE) as $chunk) {\n try {\n $objects = $objectType === 'companies' ?\n $this->client->getCompaniesByIds($chunk, $this->getCompanyFields()) :\n $this->client->getContactsByIds($chunk, $this->getContactFields());\n\n foreach ($objects as $objectId => $objectData) {\n $this->importCrmObject($objectType, (string) $objectId, $objectData, $syncObjects);\n }\n\n $this->logger->info('[' . $this->getDisplayName() . '] Batch synced ' . $objectType, [\n 'requested_count' => count($chunk),\n 'synced_count' => count($objects),\n ]);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Batch ' . $objectType . ' sync failed', [\n 'ids' => $chunk,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n return $syncObjects;\n }\n\n private function importCrmObject(string $objectType, string $objectId, mixed $objectData, array &$syncObjects): void\n {\n try {\n $object = $objectType === 'companies' ?\n $this->importAccount($objectData) :\n $this->importContact($objectData);\n\n if ($object) {\n $syncObjects[$object->getCrmProviderId()] = $object->getId();\n }\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to import batch ' . $objectType, [\n 'id' => $objectId,\n 'error' => $e->getMessage(),\n ]);\n }\n }\n\n /**\n * Prepare associations for a single opportunity\n *\n * The return value is an array with the following structure:\n * [\n * 'companies' => [\n * $companyCrmId => $companyId,\n * ...\n * ],\n * 'contacts' => [\n * $contactCrmId => $contactId,\n * ...\n * ],\n * 'account_id' => $accountId,\n * ]\n */\n private function prepareAssociationsForOpportunity(\n string $oppCrmId,\n array $companyAssociations,\n array $contactAssociations,\n array $associationsData\n ): array {\n $associations = [\n 'companies' => [],\n 'contacts' => [],\n 'account_id' => null, // Primary account for opportunity\n ];\n\n $oppCompanyIds = $companyAssociations[$oppCrmId] ?? [];\n foreach ($oppCompanyIds as $companyCrmId) {\n if (isset($associationsData['company_id_mappings'][$companyCrmId])) {\n $associations['companies'][$companyCrmId] = $associationsData['company_id_mappings'][$companyCrmId];\n\n // Set primary account (first company becomes primary account)\n if ($associations['account_id'] === null) {\n $associations['account_id'] = $associationsData['company_id_mappings'][$companyCrmId];\n }\n }\n }\n\n $oppContactIds = $contactAssociations[$oppCrmId] ?? [];\n foreach ($oppContactIds as $contactCrmId) {\n if (isset($associationsData['contact_id_mappings'][$contactCrmId])) {\n $associations['contacts'][$contactCrmId] = $associationsData['contact_id_mappings'][$contactCrmId];\n }\n }\n\n return $associations;\n }\n\n /**\n * Update only associations for an opportunity\n */\n private function updateOpportunityAssociations(Opportunity $opportunity, array $associations): void\n {\n // Update contact associations\n $this->importOpportunityContacts($opportunity, $associations['contacts']);\n\n // Update company (account) associations\n $this->updateOpportunityAccount($opportunity, $associations['account_id']);\n }\n\n /**\n * Remove all contact associations from an opportunity\n */\n private function removeAllOpportunityContacts(Opportunity $opportunity): void\n {\n $currentCount = (int) $opportunity->contacts()->count();\n\n if ($currentCount > 0) {\n $opportunity->contacts()->detach();\n\n $this->logger->info('[' . $this->getDisplayName() . '] Removed all contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'removed_count' => $currentCount,\n ]);\n }\n }\n\n private function updateOpportunityAccount(Opportunity $opportunity, ?int $accountId): void\n {\n if ($accountId === null) {\n // No account ID provided - keep current account\n return;\n }\n\n $currentAccountId = $opportunity->getAccountId();\n\n // Only update if account has changed\n if ($currentAccountId !== $accountId) {\n $opportunity->account_id = $accountId;\n $opportunity->save();\n\n $this->logger->info('[' . $this->getDisplayName() . '] Updated opportunity account association', [\n 'opportunity_id' => $opportunity->getId(),\n 'old_account_id' => $currentAccountId,\n 'new_account_id' => $accountId,\n ]);\n }\n }\n\n /**\n * Find existing opportunities by external IDs (OPTIMIZED VERSION)\n * Uses batch query for better performance\n */\n private function findExistingOpportunities(array $crmIds): Collection\n {\n return $this->crmEntityRepository\n ->findOpportunitiesByExternalIds($this->config, $crmIds);\n }\n\n private function processOpportunityBatch(array $opportunities): int\n {\n $syncedOpportunities = $this->importOpportunityBatch($opportunities);\n\n return count($syncedOpportunities['success'] ?? []);\n }\n\n /**\n * Convert single deal associations from HubSpot format to internal format\n * Handles both HubSpot SDK objects and array formats\n *\n * @param array $opportunityAssociations Raw associations from HubSpot API or pre-processed\n *\n * @return array Processed associations with DB IDs\n */\n private function convertDealAssociations(array $opportunityAssociations): array\n {\n $associations = $this->initializeAssociationsStructure();\n\n if (empty($opportunityAssociations)) {\n return $associations;\n }\n\n $associationIds = $this->extractAssociationIds($opportunityAssociations);\n\n $this->processCompanyAssociations($associationIds, $associations);\n $this->processContactAssociations($associationIds, $associations);\n\n return $associations;\n }\n\n private function initializeAssociationsStructure(): array\n {\n return [\n 'companies' => [],\n 'contacts' => [],\n 'account_id' => null, // Primary account for opportunity\n ];\n }\n\n private function extractAssociationIds(array $opportunityAssociations): array\n {\n $associationIds = [];\n\n foreach ($opportunityAssociations as $type => $associationData) {\n if (! empty($associationData)) {\n $associationIds[$type] = $this->convertSingleDealAssociations($associationData);\n }\n }\n\n return $associationIds;\n }\n\n private function processCompanyAssociations(array $associationIds, array &$associations): void\n {\n if (empty($associationIds['companies'])) {\n return;\n }\n\n $companyId = $associationIds['companies'][0];\n $account = $this->findOrSyncAccount($companyId);\n\n if ($account instanceof Account) {\n $associations['companies'][$companyId] = $account->getId();\n $associations['account_id'] = $account->getId();\n }\n }\n\n private function processContactAssociations(array $associationIds, array &$associations): void\n {\n if (empty($associationIds['contacts'])) {\n return;\n }\n\n foreach ($associationIds['contacts'] as $contactId) {\n $contact = $this->findOrSyncContact($contactId);\n\n if ($contact instanceof Contact) {\n $associations['contacts'][$contactId] = $contact->getId();\n }\n }\n }\n\n private function findOrSyncAccount(string $companyId): ?Account\n {\n $account = $this->crmEntityRepository->findAccountByExternalId($this->config, $companyId);\n\n if (! $account instanceof Account) {\n $account = $this->syncAccount($companyId);\n }\n\n return $account;\n }\n\n private function findOrSyncContact(string $contactId): ?Contact\n {\n $contact = $this->crmEntityRepository->findContactByExternalId($this->config, $contactId);\n\n if (! $contact instanceof Contact) {\n $contact = $this->syncContact($contactId);\n }\n\n return $contact;\n }\n\n private function convertSingleDealAssociations($opportunityAssociations = null): array\n {\n $associationData = [];\n\n if ($opportunityAssociations === null) {\n return $associationData;\n }\n\n // Handle array input (from extractAssociationIds)\n if (is_array($opportunityAssociations)) {\n return $opportunityAssociations;\n }\n\n // Handle CollectionResponseAssociatedId object\n if ($opportunityAssociations instanceof CollectionResponseAssociatedId) {\n foreach ($opportunityAssociations->getResults() as $association) {\n $associationData[] = $association->getId();\n }\n }\n\n return $associationData;\n }\n\n private function importOrUpdateOpportunity($crmData, ?bool $exists = null): ?Opportunity\n {\n if (empty($crmData['properties'])) {\n return null;\n }\n\n $crmId = (string) $crmData['id'];\n $properties = $crmData['properties'];\n $associations = $crmData['associations'] ?? [];\n\n $opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(\n $this->config,\n $crmId\n );\n\n if ($opportunityExists) {\n return $this->updateOpportunity($crmId, $properties, $associations);\n } else {\n return $this->createOpportunity($crmId, $properties, $associations);\n }\n }\n\n /**\n * Create new opportunity\n */\n private function createOpportunity(string $crmId, array $properties, array $associations): ?Opportunity\n {\n $accountId = $this->resolveAccountId($associations);\n if (! $accountId) {\n return null;\n }\n\n $businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);\n if (! $businessProcess) {\n return null;\n }\n\n $stage = $this->resolveStage($businessProcess, $properties['dealstage'] ?? null);\n if (! $stage) {\n return null;\n }\n\n $data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);\n\n $attributes = [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmId,\n ];\n\n $values = array_merge($attributes, $data);\n\n $opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);\n\n $this->importExternalFieldData($properties, $opportunity->getId());\n $this->importOpportunityContacts($opportunity, $associations['contacts']);\n\n if ($opportunity->wasRecentlyCreated) {\n MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());\n }\n\n return $opportunity;\n }\n\n /**\n * Update existing opportunity\n */\n private function updateOpportunity(string $crmId, array $properties, array $associations): Opportunity\n {\n $accountId = $this->resolveAccountId($associations);\n $businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);\n $stage = $businessProcess ? $this->resolveStage($businessProcess, $properties['dealstage'] ?? null) : null;\n\n $data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);\n\n $attributes = [\n 'crm_configuration_id' => $this->config->getId(),\n 'crm_provider_id' => $crmId,\n ];\n\n $values = array_merge($attributes, $data);\n $opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);\n\n $this->importExternalFieldData($properties, $opportunity->getId());\n $this->updateOpportunityAssociations($opportunity, $associations);\n\n return $opportunity;\n }\n\n private function resolveAccountId(array $associations): ?int\n {\n if (! empty($associations['accountId'])) {\n return $associations['accountId'];\n }\n\n if (empty($associations)) {\n return null;\n }\n\n // we can't resolve multiple account ids (currently SDK returns one company)\n foreach ($associations['companies'] as $accountId) {\n return $accountId;\n }\n\n return null;\n }\n\n private function buildOpportunityData(\n array $properties,\n ?int $accountId,\n ?BusinessProcess $businessProcess,\n ?Stage $stage\n ): array {\n $ownerId = null;\n $profile = null;\n if (! empty($properties['hubspot_owner_id'])) {\n $ownerId = $properties['hubspot_owner_id'];\n $profile = $this->crmEntityRepository->findProfileByExternalId($this->config, (string) $ownerId);\n }\n\n $name = 'Unknown';\n if (isset($properties['dealname'])) {\n $name = mb_strimwidth($properties['dealname'], 0, 128);\n }\n\n $amount = $this->resolveAmount($properties);\n $currency = $properties['deal_currency_code'] ?? null;\n\n $closeDate = null;\n if (! empty($properties['closedate'])) {\n $closeDate = Carbon::parse($properties['closedate'])->format('Y-m-d');\n }\n\n $remotelyCreatedAt = null;\n if (! empty($properties['createdate']) && strtotime($properties['createdate'])) {\n $date = $this->parseCleanDatetime($properties['createdate']);\n $remotelyCreatedAt = $date?->format('Y-m-d H:i:s');\n }\n\n $closedStages = $this->getClosedDealStages();\n $isWon = in_array($properties['dealstage'], $closedStages['won']);\n $isLost = in_array($properties['dealstage'], $closedStages['lost']);\n\n $data = [\n 'team_id' => $this->team->getId(),\n 'user_id' => $profile ? $profile->user_id : null,\n 'owner_id' => $ownerId,\n 'name' => $name,\n 'value' => ! empty($amount) ? $amount : null,\n 'currency_code' => CurrencyFormatter::formatCode($currency),\n 'close_date' => $closeDate,\n 'is_closed' => $isWon || $isLost,\n 'is_won' => $isWon,\n 'remotely_created_at' => $remotelyCreatedAt,\n 'probability' => $this->resolveDealProbability($properties['hs_deal_stage_probability']),\n 'forecast_category' => $this->resolveForecastCategory($properties['hs_manual_forecast_category']),\n ];\n\n if ($accountId) {\n $data['account_id'] = $accountId;\n }\n\n if ($stage) {\n $data['stage_id'] = $stage->id;\n }\n\n if ($businessProcess) {\n $recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);\n if ($recordType) {\n $data['record_type_id'] = $recordType->id;\n }\n }\n\n return $data;\n }\n\n private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess\n {\n if ($pipelineId === null) {\n return null;\n }\n\n if (isset($this->cachedBusinessProcesses[$pipelineId])) {\n return $this->cachedBusinessProcesses[$pipelineId];\n }\n\n $businessProcess = $this->getBusinessProcess($pipelineId);\n\n if (! $businessProcess instanceof BusinessProcess) {\n $this->importStages();\n $businessProcess = $this->getBusinessProcess($pipelineId);\n }\n\n if (! $businessProcess instanceof BusinessProcess) {\n $this->logger->info(\n '[HubSpot] Deal is not attached to a pipeline',\n [\n 'pipeline' => $pipelineId]\n );\n }\n\n $this->cachedBusinessProcesses[$pipelineId] = $businessProcess;\n\n return $businessProcess;\n }\n\n private function getBusinessProcess(string $pipelineId): ?BusinessProcess\n {\n return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);\n }\n\n private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage\n {\n if (empty($stageId)) {\n return null;\n }\n\n $cacheKey = $businessProcess->getId() . ':' . $stageId;\n if (isset($this->cachedStages[$cacheKey])) {\n return $this->cachedStages[$cacheKey];\n }\n\n $stage = $this->crmEntityRepository->getPipelineStageByConditions(\n $businessProcess,\n [\n 'crm_provider_id' => $stageId,\n 'type' => Stage::TYPE_OPPORTUNITY,\n ]\n );\n\n if ($stage === null) {\n $this->importStages(null, $stageId);\n }\n\n if ($stage === null) {\n $this->logger->info('[HubSpot] Stage does not exist => ' . $stageId);\n }\n\n $this->cachedStages[$cacheKey] = $stage;\n\n return $stage;\n }\n\n private function resolveAmount(array $properties): ?string\n {\n $amount = null;\n if (! empty($properties['amount'])) {\n $amount = str_replace(',', '', $properties['amount']);\n }\n\n if ($this->config->hasDefaultCurrencyFieldSet()) {\n $valueFieldName = $this->config->getDefaultCurrencyField()->getCrmProviderId();\n $amount = $properties[$valueFieldName] ?? $amount;\n }\n\n return $amount;\n }\n\n private function parseCleanDatetime(string $datetime): ?Carbon\n {\n // Treat pre-1980 values as invalid\n $minValidDate = Carbon::parse('1980-01-01 00:00:00');\n\n try {\n $date = Carbon::parse($datetime);\n\n if ($minValidDate->gt($date)) {\n return null;\n }\n\n return $date;\n } catch (Exception) {\n return null; // On parse error, treat as null\n }\n }\n\n private function resolveDealProbability(?string $stageProbability): int\n {\n if ($stageProbability === null) {\n return 0;\n }\n\n $probability = (float) $stageProbability;\n\n return $probability > 1 ? 0 : (int) ($probability * 100);\n }\n\n private function resolveForecastCategory(?string $forecastCategory): string\n {\n if (! $forecastCategory) {\n return Forecast::FORECAST_CATEGORY_UNCATEGORIZED;\n }\n\n $forecastCategory = str_replace('_', ' ', $forecastCategory);\n\n return ucwords(strtolower($forecastCategory));\n }\n\n private function importExternalFieldData(array $properties, int $opportunityId): void\n {\n $crmFields = $this->getOpportunitySyncableFields();\n $this->importOpportunityCrmFieldData($properties, $crmFields, $opportunityId);\n }\n\n private function importOpportunityContacts(Opportunity $opportunity, array $associations): void\n {\n // Handle empty or missing contact associations\n if (empty($associations)) {\n // Remove all existing contact associations if none provided\n $this->removeAllOpportunityContacts($opportunity);\n\n return;\n }\n\n // Use differential sync approach for better performance and accuracy\n $this->syncOpportunityContactsDifferential($opportunity, $associations);\n }\n\n /**\n * Sync opportunity contacts using differential approach\n * This compares current vs new associations and only makes necessary changes\n */\n private function syncOpportunityContactsDifferential(Opportunity $opportunity, array $contactAssociations): void\n {\n $currentContactCrmIds = $this->getCurrentContactCrmIds($opportunity);\n $contactAssociationIds = array_keys($contactAssociations);\n\n $contactsToAdd = array_diff($contactAssociationIds, $currentContactCrmIds);\n $contactsToRemove = array_diff($currentContactCrmIds, $contactAssociationIds);\n\n if (empty($contactsToAdd) && empty($contactsToRemove)) {\n return;\n }\n\n $this->logContactAssociationChanges($opportunity, $currentContactCrmIds, $contactAssociations, $contactsToAdd, $contactsToRemove);\n\n $this->removeContactAssociations($opportunity, $contactsToRemove);\n $this->addContactAssociations($opportunity, $contactsToAdd, $contactAssociations);\n }\n\n private function getCurrentContactCrmIds(Opportunity $opportunity): array\n {\n return $opportunity->contacts()\n ->pluck('contacts.crm_provider_id')\n ->toArray();\n }\n\n private function logContactAssociationChanges(\n Opportunity $opportunity,\n array $currentContactCrmIds,\n array $contactAssociations,\n array $contactsToAdd,\n array $contactsToRemove\n ): void {\n $this->logger->info('[' . $this->getDisplayName() . '] Contact association changes', [\n 'opportunity_id' => $opportunity->getId(),\n 'current_contacts' => $currentContactCrmIds,\n 'new_contacts' => $contactAssociations,\n 'contacts_to_add' => $contactsToAdd,\n 'contacts_to_remove' => $contactsToRemove,\n ]);\n }\n\n private function removeContactAssociations(Opportunity $opportunity, array $contactsToRemove): void\n {\n if (empty($contactsToRemove)) {\n return;\n }\n\n $contactsToDetach = $opportunity->contacts()\n ->whereIn('contacts.crm_provider_id', $contactsToRemove)\n ->pluck('contacts.id')\n ->toArray();\n\n if (! empty($contactsToDetach)) {\n $opportunity->contacts()->detach($contactsToDetach);\n\n $this->logger->info('[' . $this->getDisplayName() . '] Removed contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'removed_contact_crm_ids' => $contactsToRemove,\n 'removed_contact_count' => count($contactsToDetach),\n ]);\n }\n }\n\n private function addContactAssociations(Opportunity $opportunity, array $contactsToAdd, array $contactAssociations): void\n {\n if (empty($contactsToAdd)) {\n return;\n }\n\n $contactsAdded = [];\n foreach ($contactsToAdd as $crmId) {\n $id = $contactAssociations[$crmId];\n\n if ($this->attachSingleContact($opportunity, (string) $crmId, $id)) {\n $contactsAdded[] = $crmId;\n }\n }\n\n $this->logAddedContacts($opportunity, $contactsAdded);\n }\n\n private function attachSingleContact(Opportunity $opportunity, string $crmId, int $id): bool\n {\n try {\n $contact = $this->crmEntityRepository->findContactByConfigurationAndId($this->config, $id);\n\n if (! $contact) {\n return false;\n }\n\n return $this->performContactAttachment($opportunity, $contact, $crmId);\n } catch (\\Throwable $e) {\n $this->logger->warning('[' . $this->getDisplayName() . '] Failed to add contact association', [\n 'opportunity_id' => $opportunity->getId(),\n 'contact_crm_id' => $crmId,\n 'error' => $e->getMessage(),\n ]);\n\n return false;\n }\n }\n\n private function performContactAttachment(Opportunity $opportunity, Contact $contact, string $crmId): bool\n {\n try {\n $opportunity->contacts()->attach($contact->getId(), [\n 'crm_provider_id' => $crmId,\n ]);\n\n return true;\n } catch (\\Illuminate\\Database\\QueryException $e) {\n if (str_contains($e->getMessage(), 'Duplicate entry')) {\n $this->logger->info('[' . $this->getDisplayName() . '] Contact association already exists', [\n 'contact_id' => $contact->getId(),\n 'contact_crm_id' => $crmId,\n 'opportunity_id' => $opportunity->getId(),\n ]);\n\n return false;\n }\n\n throw $e;\n }\n }\n\n private function logAddedContacts(Opportunity $opportunity, array $contactsAdded): void\n {\n if (! empty($contactsAdded)) {\n $this->logger->info('[' . $this->getDisplayName() . '] Added contact associations', [\n 'opportunity_id' => $opportunity->getId(),\n 'contacts_to_add_count' => count($contactsAdded),\n 'added_contact_crm_ids' => $contactsAdded,\n 'added_contacts_count' => count($contactsAdded),\n ]);\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.23320313,"top":1.0,"width":0.01015625,"height":0.0},"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.23320313,"top":1.0,"width":0.01015625,"height":0.0},"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.23320313,"top":1.0,"width":0.049609374,"height":0.0},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXButton","text":"Hide","depth":4,"bounds":{"left":0.23320313,"top":1.0,"width":0.01015625,"height":0.0},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"6","depth":4,"bounds":{"left":0.6839844,"top":0.13055556,"width":0.009375,"height":0.013194445},"role_description":"text"},{"role":"AXStaticText","text":"32","depth":4,"bounds":{"left":0.69570315,"top":0.13055556,"width":0.012109375,"height":0.013194445},"role_description":"text"},{"role":"AXButton","text":"Previous Highlighted Error","depth":4,"bounds":{"left":0.7097656,"top":0.12916666,"width":0.00859375,"height":0.015972223},"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.71835935,"top":0.12916666,"width":0.008203125,"height":0.015972223},"role_description":"button","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false}]...
|
4902465284012378591
|
-8178087410993426138
|
click
|
accessibility
|
NULL
|
Project: faVsco.js, menu
#11894 on JY-18909-automa Project: faVsco.js, menu
#11894 on JY-18909-automated-reports-ask-jiminny, menu
Start Listening for PHP Debug Connections
AutomatedReportsCommandTest
Run 'AutomatedReportsCommandTest'
Debug 'AutomatedReportsCommandTest'
More Actions
JetBrains AI
Search Everywhere
IDE and Project Settings
Show Replace Field
Search History
$stage
New Line
Match Case
Words
Regex
Replace History
Replace
New Line
Preserve case
13/29
Previous Occurrence
Next Occurrence
Filter Search Results
Open in Window, Multiple Cursors
Click to highlight
Close
Code changed:
Hide
Sync Changes
Hide This Notification
32
2
19
Previous Highlighted Error
Next Highlighted Error
<?php
declare(strict_types=1);
namespace Jiminny\Services\Crm\Hubspot\ServiceTraits;
use Carbon\Carbon;
use HubSpot\Client\Crm\Deals\Model\CollectionResponseAssociatedId;
use Jiminny\Exceptions\InvalidArgumentException;
use Jiminny\Models\Account;
use Exception;
use Jiminny\Component\DealInsights\Forecast\Forecast;
use Jiminny\Jobs\Crm\MatchActivitiesToNewOpportunity;
use Jiminny\Models\Contact;
use Jiminny\Models\Crm\BusinessProcess;
use Jiminny\Exceptions\CrmException;
use Jiminny\Models\Opportunity;
use Illuminate\Support\Collection;
use Jiminny\Models\Stage;
use Jiminny\Repositories\Crm\CrmEntityRepository;
use Jiminny\Services\Crm\Hubspot\DealFieldsService;
use Jiminny\Services\Crm\Hubspot\OpportunitySyncStrategy\HubspotSingleSyncStrategy;
use Jiminny\Services\Crm\Hubspot\WebhookSyncBatchProcessor;
use Jiminny\Services\Crm\OpportunitySyncStrategyResolver;
use Jiminny\Utils\CurrencyFormatter;
/**
* Optimized sync methods for better performance
* These methods can be integrated into SyncCrmEntitiesTrait for significant performance gains
*/
trait OpportunitySyncTrait
{
private const int BATCH_SIZE = 100;
private const int BATCH_PROCESS_SIZE = 800;
protected OpportunitySyncStrategyResolver $opportunitySyncStrategyResolver;
protected CrmEntityRepository $crmEntityRepository;
protected DealFieldsService $dealFieldsService;
private ?array $cachedClosedDealStages = null;
private array $cachedBusinessProcesses = [];
private array $cachedStages = [];
public function syncOpportunities(array $parameters, ?string $strategy = null): int
{
$strategies = $this->opportunitySyncStrategyResolver->getStrategies($this->config, $strategy);
$parameters['config'] = $this->config;
$syncCount = 0;
$reportedTotal = 0;
$lastSyncedId = [];
try {
foreach ($strategies as $strategyName => $syncStrategy) {
$this->logger->info(
'[' . $this->getDisplayName() . '] Syncing opportunities using strategy: ' .
$strategyName
);
$total = 0;
$lastId = null;
$buffer = [];
// HubspotWebhookBatchSyncStrategy returns empty generator, this is for other strategies
foreach ($syncStrategy->fetchOpportunities($parameters, $total, $lastId) as $hsOpportunity) {
$buffer[] = $hsOpportunity;
// process every 800 rows (fits < 1 000 association limit)
if (\count($buffer) >= self::BATCH_PROCESS_SIZE) {
$syncCount += $this->processOpportunityBatch($buffer);
$buffer = [];
}
}
// leftovers
if ($buffer) {
$syncCount += $this->processOpportunityBatch($buffer);
}
$reportedTotal += $total;
$lastSyncedId = $lastId;
}
} catch (\HubSpot\Client\Crm\Deals\ApiException | CrmException $e) {
$this->handleSyncException($e, $parameters);
}
$this->logger->info(
'[HubSpot] Synced opportunities',
[
'team' => $this->team->getId(),
'sync_count' => $syncCount,
'total' => $reportedTotal,
'last_synced_id' => $lastSyncedId,
]
);
return $reportedTotal;
}
private function handleSyncException(\Throwable $e, array $parameters): void
{
if (($parameters['since'] ?? null) instanceof Carbon) {
$parameters['since'] = $parameters['since']->toDateTimeString();
}
$parameters['config'] = $this->config->getId();
$this->logger->warning('[' . $this->getDisplayName() . '] Sync opportunities failed', [
'teamId' => $this->team->getUuid(),
'parameters' => $parameters,
'reason' => $e->getMessage(),
]);
}
/**
* @inheritdoc
*/
public function syncOpportunity(string $crmId): ?Opportunity
{
$strategy = $this->opportunitySyncStrategyResolver->resolve(
$this->config,
OpportunitySyncStrategyResolver::SINGLE_SYNC_OPPORTUNITY_STRATEGY,
);
$parameters = [
'config' => $this->config,
'crm_id' => $crmId,
];
try {
if (! $strategy instanceof HubspotSingleSyncStrategy) {
throw new InvalidArgumentException('Strategy must by HubspotSingleSyncStrategy');
}
$hsOpportunity = $strategy->fetchOpportunity($parameters);
} catch (\HubSpot\Client\Crm\Deals\ApiException $e) {
$this->logger->info('[' . $this->getDisplayName() . '] Opportunity not found', [
'teamId' => $this->team->getUuid(),
'crmId' => $crmId,
'reason' => $e->getMessage(),
]);
return null;
}
$hsOpportunity['associations'] = $this->convertDealAssociations($hsOpportunity['associations'] ?? []);
return $this->importOrUpdateOpportunity($hsOpportunity);
}
/**
* Process webhook-collected opportunity batches.
*
* Drains Redis sets containing company CRM IDs collected from webhook events
* and dispatches ImportOpportunityBatch jobs for batch processing.
*
* @return int Number of opportunity IDs dispatched to jobs
*/
public function batchSyncOpportunities(): int
{
$configId = $this->team->getCrmConfiguration()->getId();
return $this->batchProcessor->processBatchesForObjectType(
WebhookSyncBatchProcessor::OBJECT_TYPE_DEAL,
$configId
);
}
/**
* Import a batch of opportunities by their CRM IDs.
* Fetches opportunity data from HubSpot API and delegates to importOpportunityBatch().
*
* @param array<string> $crmIds HubSpot deal CRM IDs
*
* @return array{success: array, failed_ids: array, errors?: array<string, string>}
*/
public function importOpportunityBatchByIds(array $crmIds): array
{
$fields = $this->dealFieldsService->getFieldsForConfiguration($this->config);
$allDeals = [];
foreach (array_chunk($crmIds, self::BATCH_SIZE) as $chunk) {
$deals = $this->client->getOpportunitiesByIds($chunk, $fields);
foreach ($deals as $deal) {
$allDeals[] = $deal;
}
}
// IDs not returned by HubSpot are likely deleted or inaccessible deals.
// These are not failures — retrying won't bring them back.
$fetchedIds = array_map('strval', array_column($allDeals, 'id'));
$notFoundIds = array_values(array_diff(array_map('strval', $crmIds), $fetchedIds));
if (! empty($notFoundIds)) {
$this->logger->info('[' . $this->getDisplayName() . '] CRM IDs not found in HubSpot (likely deleted)', [
'teamId' => $this->team->getId(),
'notFoundCount' => \count($notFoundIds),
'notFoundIds' => $notFoundIds,
'requestedCount' => \count($crmIds),
'fetchedCount' => \count($allDeals),
]);
}
if (empty($allDeals)) {
return ['success' => [], 'failed_ids' => []];
}
return $this->importOpportunityBatch($allDeals);
}
private function getClosedDealStages(): array
{
if ($this->cachedClosedDealStages !== null) {
return $this->cachedClosedDealStages;
}
$stages = $this->crmEntityRepository->getOpportunityClosedStages($this->config);
$data = [
'lost' => [],
'won' => [],
];
foreach ($stages as $stage) {
if ($stage->probability == 0.00) {
$data['lost'][] = $stage->crm_provider_id;
}
if ($stage->probability == 100.00) {
$data['won'][] = $stage->crm_provider_id;
}
}
$this->cachedClosedDealStages = $data;
return $data;
}
/**
* Import deals into the database with pre-fetched associations.
*
* API calls here (getAssociationsData, getExistingOpportunityCrmIds) are NOT
* caught — if they throw, the exception propagates to ImportOpportunityBatch::handle()
* where Laravel retries the whole job with backoff. After all retries exhausted,
* failed() requeues all IDs to Redis.
*
* The per-deal loop catches exceptions individually. A deal can end up in three states:
* - success: imported/updated successfully
* - failed_ids: exception thrown (DB constraint violation, corrupt data, etc.)
* These are permanent issues — retrying won't fix them.
* - skipped (null): missing dependencies (no account, unknown pipeline/stage).
* This is acceptable — the deal cannot be imported until those exist.
*/
private function importOpportunityBatch(array $deals): array
{
$syncedOpportunities = [
'success' => [],
'failed_ids' => [],
];
$dealIds = array_column($deals, 'id');
// Shared association/existing-ID preparation is batch-level state. If it fails, rethrow so the
// queue job retries the whole batch and eventually requeues all deal IDs back to Redis.
try {
$companyAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'companies');
$contactAssociations = $this->client->getAssociationsData($dealIds, 'deals', 'contacts');
$associationsData = $this->prepareAssociatedEntities($companyAssociations, $contactAssociations);
$existingCrmIds = $this->crmEntityRepository->getExistingOpportunityCrmIds(
$this->config,
array_map('strval', $dealIds)
);
$existingCrmIdSet = array_flip($existingCrmIds);
} catch (\Throwable $e) {
$this->logger->error('[' . $this->getDisplayName() . '] Failed to fetch associations or existing IDs', [
'teamId' => $this->team->getId(),
'dealCount' => count($dealIds),
'error' => $e->getMessage(),
]);
throw $e;
}
foreach ($deals as $deal) {
try {
$deal['associations'] = $this->prepareAssociationsForOpportunity(
$deal['id'],
$companyAssociations,
$contactAssociations,
$associationsData
);
$syncedOpportunity = $this->importOrUpdateOpportunity(
$deal,
isset($existingCrmIdSet[(string) $deal['id']])
);
if ($syncedOpportunity) {
$syncedOpportunities['success'][] = $syncedOpportunity;
}
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to import opportunity', [
'teamId' => $this->team->getId(),
'crmId' => $deal['id'],
'error' => $e->getMessage(),
]);
$syncedOpportunities['failed_ids'][] = $deal['id'];
$syncedOpportunities['errors'][$deal['id']] = $e->getMessage();
}
}
return $syncedOpportunities;
}
/**
* Prepare associated entities for opportunities with optimized batch processing
* Returns structured data with CRM ID to DB ID mappings for each opportunity
*/
private function prepareAssociatedEntities(array $companyAssociations, array $contactAssociations): array
{
// Step 1: Collect all unique company and contact IDs from associations
$allCompanyIds = $this->flattenAssociationIds($companyAssociations);
$allContactIds = $this->flattenAssociationIds($contactAssociations);
// Step 2: Batch sync missing entities and get CRM ID to DB ID mappings
$companyIdMappings = [];
$contactIdMappings = [];
if (! empty($allCompanyIds)) {
$companyIdMappings = $this->prepareAssociatedAccounts($allCompanyIds);
}
if (! empty($allContactIds)) {
$contactIdMappings = $this->prepareAssociatedContacts($allContactIds);
}
return [
'company_id_mappings' => $companyIdMappings,
'contact_id_mappings' => $contactIdMappings,
];
}
/**
* Flatten association data to get unique IDs
*/
private function flattenAssociationIds(array $associations): array
{
$ids = [];
foreach ($associations as $dealAssociations) {
if (is_array($dealAssociations)) {
foreach ($dealAssociations as $id) {
$ids[$id] = true;
}
}
}
return array_keys($ids);
}
/**
* Batch sync missing accounts
*/
private function prepareAssociatedAccounts(array $companyIds): array
{
// Find which accounts already exist
$existingAccounts = $this->crmEntityRepository
->findAccountsByExternalIds($this->config, $companyIds);
$existingCompanyIds = $existingAccounts->pluck('crm_provider_id')->toArray();
$existingAccountsData = $existingAccounts->mapWithKeys(function ($account) {
return [$account->getCrmProviderId() => $account->getId()];
})->toArray();
$missingCompanyIds = array_diff($companyIds, $existingCompanyIds);
if (empty($missingCompanyIds)) {
return $existingAccountsData;
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing accounts', [
'teamId' => $this->team->getUuid(),
'total_companies' => count($companyIds),
'existing_companies' => count($existingCompanyIds),
'missing_companies' => count($missingCompanyIds),
]);
// we already have limit on opportunity ids count
// Initialize variable before try block
$syncedAccountsData = [];
try {
$syncedAccountsData = $this->batchSyncCrmObjects('companies', $missingCompanyIds);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing accounts', [
'size' => count($missingCompanyIds),
'error' => $e->getMessage(),
]);
$syncedAccountsData = [];
}
return $existingAccountsData + $syncedAccountsData;
}
/**
* Prepare associated contacts - find existing and sync missing ones
* Returns mapping of CRM ID to DB ID
*/
private function prepareAssociatedContacts(array $contactIds): array
{
// Find which contacts already exist
$existingContacts = $this->crmEntityRepository
->findContactsByExternalIds($this->config, $contactIds);
$existingContactIds = $existingContacts->pluck('crm_provider_id')->toArray();
// Create mapping for existing contacts
$existingContactsData = $existingContacts->mapWithKeys(function ($contact) {
return [$contact->getCrmProviderId() => $contact->getId()];
})->toArray();
$missingContactIds = array_diff($contactIds, $existingContactIds);
if (empty($missingContactIds)) {
return $existingContactsData;
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch syncing missing contacts', [
'teamId' => $this->team->getUuid(),
'total_contacts' => count($contactIds),
'existing_contacts' => count($existingContactIds),
'missing_contacts' => count($missingContactIds),
]);
// Sync missing contacts using batch API
try {
$syncedContactsData = $this->batchSyncCrmObjects('contacts', $missingContactIds);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to sync missing contacts', [
'size' => count($missingContactIds),
'error' => $e->getMessage(),
]);
$syncedContactsData = [];
}
return $existingContactsData + $syncedContactsData;
}
private function batchSyncCrmObjects(string $objectType, array $crmIds): array
{
$syncObjects = [];
$crmObjectIds = array_values($crmIds);
foreach (array_chunk($crmObjectIds, self::BATCH_SIZE) as $chunk) {
try {
$objects = $objectType === 'companies' ?
$this->client->getCompaniesByIds($chunk, $this->getCompanyFields()) :
$this->client->getContactsByIds($chunk, $this->getContactFields());
foreach ($objects as $objectId => $objectData) {
$this->importCrmObject($objectType, (string) $objectId, $objectData, $syncObjects);
}
$this->logger->info('[' . $this->getDisplayName() . '] Batch synced ' . $objectType, [
'requested_count' => count($chunk),
'synced_count' => count($objects),
]);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Batch ' . $objectType . ' sync failed', [
'ids' => $chunk,
'error' => $e->getMessage(),
]);
}
}
return $syncObjects;
}
private function importCrmObject(string $objectType, string $objectId, mixed $objectData, array &$syncObjects): void
{
try {
$object = $objectType === 'companies' ?
$this->importAccount($objectData) :
$this->importContact($objectData);
if ($object) {
$syncObjects[$object->getCrmProviderId()] = $object->getId();
}
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to import batch ' . $objectType, [
'id' => $objectId,
'error' => $e->getMessage(),
]);
}
}
/**
* Prepare associations for a single opportunity
*
* The return value is an array with the following structure:
* [
* 'companies' => [
* $companyCrmId => $companyId,
* ...
* ],
* 'contacts' => [
* $contactCrmId => $contactId,
* ...
* ],
* 'account_id' => $accountId,
* ]
*/
private function prepareAssociationsForOpportunity(
string $oppCrmId,
array $companyAssociations,
array $contactAssociations,
array $associationsData
): array {
$associations = [
'companies' => [],
'contacts' => [],
'account_id' => null, // Primary account for opportunity
];
$oppCompanyIds = $companyAssociations[$oppCrmId] ?? [];
foreach ($oppCompanyIds as $companyCrmId) {
if (isset($associationsData['company_id_mappings'][$companyCrmId])) {
$associations['companies'][$companyCrmId] = $associationsData['company_id_mappings'][$companyCrmId];
// Set primary account (first company becomes primary account)
if ($associations['account_id'] === null) {
$associations['account_id'] = $associationsData['company_id_mappings'][$companyCrmId];
}
}
}
$oppContactIds = $contactAssociations[$oppCrmId] ?? [];
foreach ($oppContactIds as $contactCrmId) {
if (isset($associationsData['contact_id_mappings'][$contactCrmId])) {
$associations['contacts'][$contactCrmId] = $associationsData['contact_id_mappings'][$contactCrmId];
}
}
return $associations;
}
/**
* Update only associations for an opportunity
*/
private function updateOpportunityAssociations(Opportunity $opportunity, array $associations): void
{
// Update contact associations
$this->importOpportunityContacts($opportunity, $associations['contacts']);
// Update company (account) associations
$this->updateOpportunityAccount($opportunity, $associations['account_id']);
}
/**
* Remove all contact associations from an opportunity
*/
private function removeAllOpportunityContacts(Opportunity $opportunity): void
{
$currentCount = (int) $opportunity->contacts()->count();
if ($currentCount > 0) {
$opportunity->contacts()->detach();
$this->logger->info('[' . $this->getDisplayName() . '] Removed all contact associations', [
'opportunity_id' => $opportunity->getId(),
'removed_count' => $currentCount,
]);
}
}
private function updateOpportunityAccount(Opportunity $opportunity, ?int $accountId): void
{
if ($accountId === null) {
// No account ID provided - keep current account
return;
}
$currentAccountId = $opportunity->getAccountId();
// Only update if account has changed
if ($currentAccountId !== $accountId) {
$opportunity->account_id = $accountId;
$opportunity->save();
$this->logger->info('[' . $this->getDisplayName() . '] Updated opportunity account association', [
'opportunity_id' => $opportunity->getId(),
'old_account_id' => $currentAccountId,
'new_account_id' => $accountId,
]);
}
}
/**
* Find existing opportunities by external IDs (OPTIMIZED VERSION)
* Uses batch query for better performance
*/
private function findExistingOpportunities(array $crmIds): Collection
{
return $this->crmEntityRepository
->findOpportunitiesByExternalIds($this->config, $crmIds);
}
private function processOpportunityBatch(array $opportunities): int
{
$syncedOpportunities = $this->importOpportunityBatch($opportunities);
return count($syncedOpportunities['success'] ?? []);
}
/**
* Convert single deal associations from HubSpot format to internal format
* Handles both HubSpot SDK objects and array formats
*
* @param array $opportunityAssociations Raw associations from HubSpot API or pre-processed
*
* @return array Processed associations with DB IDs
*/
private function convertDealAssociations(array $opportunityAssociations): array
{
$associations = $this->initializeAssociationsStructure();
if (empty($opportunityAssociations)) {
return $associations;
}
$associationIds = $this->extractAssociationIds($opportunityAssociations);
$this->processCompanyAssociations($associationIds, $associations);
$this->processContactAssociations($associationIds, $associations);
return $associations;
}
private function initializeAssociationsStructure(): array
{
return [
'companies' => [],
'contacts' => [],
'account_id' => null, // Primary account for opportunity
];
}
private function extractAssociationIds(array $opportunityAssociations): array
{
$associationIds = [];
foreach ($opportunityAssociations as $type => $associationData) {
if (! empty($associationData)) {
$associationIds[$type] = $this->convertSingleDealAssociations($associationData);
}
}
return $associationIds;
}
private function processCompanyAssociations(array $associationIds, array &$associations): void
{
if (empty($associationIds['companies'])) {
return;
}
$companyId = $associationIds['companies'][0];
$account = $this->findOrSyncAccount($companyId);
if ($account instanceof Account) {
$associations['companies'][$companyId] = $account->getId();
$associations['account_id'] = $account->getId();
}
}
private function processContactAssociations(array $associationIds, array &$associations): void
{
if (empty($associationIds['contacts'])) {
return;
}
foreach ($associationIds['contacts'] as $contactId) {
$contact = $this->findOrSyncContact($contactId);
if ($contact instanceof Contact) {
$associations['contacts'][$contactId] = $contact->getId();
}
}
}
private function findOrSyncAccount(string $companyId): ?Account
{
$account = $this->crmEntityRepository->findAccountByExternalId($this->config, $companyId);
if (! $account instanceof Account) {
$account = $this->syncAccount($companyId);
}
return $account;
}
private function findOrSyncContact(string $contactId): ?Contact
{
$contact = $this->crmEntityRepository->findContactByExternalId($this->config, $contactId);
if (! $contact instanceof Contact) {
$contact = $this->syncContact($contactId);
}
return $contact;
}
private function convertSingleDealAssociations($opportunityAssociations = null): array
{
$associationData = [];
if ($opportunityAssociations === null) {
return $associationData;
}
// Handle array input (from extractAssociationIds)
if (is_array($opportunityAssociations)) {
return $opportunityAssociations;
}
// Handle CollectionResponseAssociatedId object
if ($opportunityAssociations instanceof CollectionResponseAssociatedId) {
foreach ($opportunityAssociations->getResults() as $association) {
$associationData[] = $association->getId();
}
}
return $associationData;
}
private function importOrUpdateOpportunity($crmData, ?bool $exists = null): ?Opportunity
{
if (empty($crmData['properties'])) {
return null;
}
$crmId = (string) $crmData['id'];
$properties = $crmData['properties'];
$associations = $crmData['associations'] ?? [];
$opportunityExists = $exists ?? (bool) $this->crmEntityRepository->findOpportunityByExternalId(
$this->config,
$crmId
);
if ($opportunityExists) {
return $this->updateOpportunity($crmId, $properties, $associations);
} else {
return $this->createOpportunity($crmId, $properties, $associations);
}
}
/**
* Create new opportunity
*/
private function createOpportunity(string $crmId, array $properties, array $associations): ?Opportunity
{
$accountId = $this->resolveAccountId($associations);
if (! $accountId) {
return null;
}
$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);
if (! $businessProcess) {
return null;
}
$stage = $this->resolveStage($businessProcess, $properties['dealstage'] ?? null);
if (! $stage) {
return null;
}
$data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);
$attributes = [
'crm_configuration_id' => $this->config->getId(),
'crm_provider_id' => $crmId,
];
$values = array_merge($attributes, $data);
$opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);
$this->importExternalFieldData($properties, $opportunity->getId());
$this->importOpportunityContacts($opportunity, $associations['contacts']);
if ($opportunity->wasRecentlyCreated) {
MatchActivitiesToNewOpportunity::dispatch($opportunity->getId());
}
return $opportunity;
}
/**
* Update existing opportunity
*/
private function updateOpportunity(string $crmId, array $properties, array $associations): Opportunity
{
$accountId = $this->resolveAccountId($associations);
$businessProcess = $this->resolveBusinessProcess($properties['pipeline'] ?? null);
$stage = $businessProcess ? $this->resolveStage($businessProcess, $properties['dealstage'] ?? null) : null;
$data = $this->buildOpportunityData($properties, $accountId, $businessProcess, $stage);
$attributes = [
'crm_configuration_id' => $this->config->getId(),
'crm_provider_id' => $crmId,
];
$values = array_merge($attributes, $data);
$opportunity = $this->crmEntityRepository->upsertOpportunity($attributes, $values);
$this->importExternalFieldData($properties, $opportunity->getId());
$this->updateOpportunityAssociations($opportunity, $associations);
return $opportunity;
}
private function resolveAccountId(array $associations): ?int
{
if (! empty($associations['accountId'])) {
return $associations['accountId'];
}
if (empty($associations)) {
return null;
}
// we can't resolve multiple account ids (currently SDK returns one company)
foreach ($associations['companies'] as $accountId) {
return $accountId;
}
return null;
}
private function buildOpportunityData(
array $properties,
?int $accountId,
?BusinessProcess $businessProcess,
?Stage $stage
): array {
$ownerId = null;
$profile = null;
if (! empty($properties['hubspot_owner_id'])) {
$ownerId = $properties['hubspot_owner_id'];
$profile = $this->crmEntityRepository->findProfileByExternalId($this->config, (string) $ownerId);
}
$name = 'Unknown';
if (isset($properties['dealname'])) {
$name = mb_strimwidth($properties['dealname'], 0, 128);
}
$amount = $this->resolveAmount($properties);
$currency = $properties['deal_currency_code'] ?? null;
$closeDate = null;
if (! empty($properties['closedate'])) {
$closeDate = Carbon::parse($properties['closedate'])->format('Y-m-d');
}
$remotelyCreatedAt = null;
if (! empty($properties['createdate']) && strtotime($properties['createdate'])) {
$date = $this->parseCleanDatetime($properties['createdate']);
$remotelyCreatedAt = $date?->format('Y-m-d H:i:s');
}
$closedStages = $this->getClosedDealStages();
$isWon = in_array($properties['dealstage'], $closedStages['won']);
$isLost = in_array($properties['dealstage'], $closedStages['lost']);
$data = [
'team_id' => $this->team->getId(),
'user_id' => $profile ? $profile->user_id : null,
'owner_id' => $ownerId,
'name' => $name,
'value' => ! empty($amount) ? $amount : null,
'currency_code' => CurrencyFormatter::formatCode($currency),
'close_date' => $closeDate,
'is_closed' => $isWon || $isLost,
'is_won' => $isWon,
'remotely_created_at' => $remotelyCreatedAt,
'probability' => $this->resolveDealProbability($properties['hs_deal_stage_probability']),
'forecast_category' => $this->resolveForecastCategory($properties['hs_manual_forecast_category']),
];
if ($accountId) {
$data['account_id'] = $accountId;
}
if ($stage) {
$data['stage_id'] = $stage->id;
}
if ($businessProcess) {
$recordType = $this->crmEntityRepository->getBusinessProcessRecordType($businessProcess);
if ($recordType) {
$data['record_type_id'] = $recordType->id;
}
}
return $data;
}
private function resolveBusinessProcess(?string $pipelineId): ?BusinessProcess
{
if ($pipelineId === null) {
return null;
}
if (isset($this->cachedBusinessProcesses[$pipelineId])) {
return $this->cachedBusinessProcesses[$pipelineId];
}
$businessProcess = $this->getBusinessProcess($pipelineId);
if (! $businessProcess instanceof BusinessProcess) {
$this->importStages();
$businessProcess = $this->getBusinessProcess($pipelineId);
}
if (! $businessProcess instanceof BusinessProcess) {
$this->logger->info(
'[HubSpot] Deal is not attached to a pipeline',
[
'pipeline' => $pipelineId]
);
}
$this->cachedBusinessProcesses[$pipelineId] = $businessProcess;
return $businessProcess;
}
private function getBusinessProcess(string $pipelineId): ?BusinessProcess
{
return $this->crmEntityRepository->findBusinessProcessesByExternalId($this->config, $pipelineId);
}
private function resolveStage(BusinessProcess $businessProcess, ?string $stageId): ?Stage
{
if (empty($stageId)) {
return null;
}
$cacheKey = $businessProcess->getId() . ':' . $stageId;
if (isset($this->cachedStages[$cacheKey])) {
return $this->cachedStages[$cacheKey];
}
$stage = $this->crmEntityRepository->getPipelineStageByConditions(
$businessProcess,
[
'crm_provider_id' => $stageId,
'type' => Stage::TYPE_OPPORTUNITY,
]
);
if ($stage === null) {
$this->importStages(null, $stageId);
}
if ($stage === null) {
$this->logger->info('[HubSpot] Stage does not exist => ' . $stageId);
}
$this->cachedStages[$cacheKey] = $stage;
return $stage;
}
private function resolveAmount(array $properties): ?string
{
$amount = null;
if (! empty($properties['amount'])) {
$amount = str_replace(',', '', $properties['amount']);
}
if ($this->config->hasDefaultCurrencyFieldSet()) {
$valueFieldName = $this->config->getDefaultCurrencyField()->getCrmProviderId();
$amount = $properties[$valueFieldName] ?? $amount;
}
return $amount;
}
private function parseCleanDatetime(string $datetime): ?Carbon
{
// Treat pre-1980 values as invalid
$minValidDate = Carbon::parse('1980-01-01 00:00:00');
try {
$date = Carbon::parse($datetime);
if ($minValidDate->gt($date)) {
return null;
}
return $date;
} catch (Exception) {
return null; // On parse error, treat as null
}
}
private function resolveDealProbability(?string $stageProbability): int
{
if ($stageProbability === null) {
return 0;
}
$probability = (float) $stageProbability;
return $probability > 1 ? 0 : (int) ($probability * 100);
}
private function resolveForecastCategory(?string $forecastCategory): string
{
if (! $forecastCategory) {
return Forecast::FORECAST_CATEGORY_UNCATEGORIZED;
}
$forecastCategory = str_replace('_', ' ', $forecastCategory);
return ucwords(strtolower($forecastCategory));
}
private function importExternalFieldData(array $properties, int $opportunityId): void
{
$crmFields = $this->getOpportunitySyncableFields();
$this->importOpportunityCrmFieldData($properties, $crmFields, $opportunityId);
}
private function importOpportunityContacts(Opportunity $opportunity, array $associations): void
{
// Handle empty or missing contact associations
if (empty($associations)) {
// Remove all existing contact associations if none provided
$this->removeAllOpportunityContacts($opportunity);
return;
}
// Use differential sync approach for better performance and accuracy
$this->syncOpportunityContactsDifferential($opportunity, $associations);
}
/**
* Sync opportunity contacts using differential approach
* This compares current vs new associations and only makes necessary changes
*/
private function syncOpportunityContactsDifferential(Opportunity $opportunity, array $contactAssociations): void
{
$currentContactCrmIds = $this->getCurrentContactCrmIds($opportunity);
$contactAssociationIds = array_keys($contactAssociations);
$contactsToAdd = array_diff($contactAssociationIds, $currentContactCrmIds);
$contactsToRemove = array_diff($currentContactCrmIds, $contactAssociationIds);
if (empty($contactsToAdd) && empty($contactsToRemove)) {
return;
}
$this->logContactAssociationChanges($opportunity, $currentContactCrmIds, $contactAssociations, $contactsToAdd, $contactsToRemove);
$this->removeContactAssociations($opportunity, $contactsToRemove);
$this->addContactAssociations($opportunity, $contactsToAdd, $contactAssociations);
}
private function getCurrentContactCrmIds(Opportunity $opportunity): array
{
return $opportunity->contacts()
->pluck('contacts.crm_provider_id')
->toArray();
}
private function logContactAssociationChanges(
Opportunity $opportunity,
array $currentContactCrmIds,
array $contactAssociations,
array $contactsToAdd,
array $contactsToRemove
): void {
$this->logger->info('[' . $this->getDisplayName() . '] Contact association changes', [
'opportunity_id' => $opportunity->getId(),
'current_contacts' => $currentContactCrmIds,
'new_contacts' => $contactAssociations,
'contacts_to_add' => $contactsToAdd,
'contacts_to_remove' => $contactsToRemove,
]);
}
private function removeContactAssociations(Opportunity $opportunity, array $contactsToRemove): void
{
if (empty($contactsToRemove)) {
return;
}
$contactsToDetach = $opportunity->contacts()
->whereIn('contacts.crm_provider_id', $contactsToRemove)
->pluck('contacts.id')
->toArray();
if (! empty($contactsToDetach)) {
$opportunity->contacts()->detach($contactsToDetach);
$this->logger->info('[' . $this->getDisplayName() . '] Removed contact associations', [
'opportunity_id' => $opportunity->getId(),
'removed_contact_crm_ids' => $contactsToRemove,
'removed_contact_count' => count($contactsToDetach),
]);
}
}
private function addContactAssociations(Opportunity $opportunity, array $contactsToAdd, array $contactAssociations): void
{
if (empty($contactsToAdd)) {
return;
}
$contactsAdded = [];
foreach ($contactsToAdd as $crmId) {
$id = $contactAssociations[$crmId];
if ($this->attachSingleContact($opportunity, (string) $crmId, $id)) {
$contactsAdded[] = $crmId;
}
}
$this->logAddedContacts($opportunity, $contactsAdded);
}
private function attachSingleContact(Opportunity $opportunity, string $crmId, int $id): bool
{
try {
$contact = $this->crmEntityRepository->findContactByConfigurationAndId($this->config, $id);
if (! $contact) {
return false;
}
return $this->performContactAttachment($opportunity, $contact, $crmId);
} catch (\Throwable $e) {
$this->logger->warning('[' . $this->getDisplayName() . '] Failed to add contact association', [
'opportunity_id' => $opportunity->getId(),
'contact_crm_id' => $crmId,
'error' => $e->getMessage(),
]);
return false;
}
}
private function performContactAttachment(Opportunity $opportunity, Contact $contact, string $crmId): bool
{
try {
$opportunity->contacts()->attach($contact->getId(), [
'crm_provider_id' => $crmId,
]);
return true;
} catch (\Illuminate\Database\QueryException $e) {
if (str_contains($e->getMessage(), 'Duplicate entry')) {
$this->logger->info('[' . $this->getDisplayName() . '] Contact association already exists', [
'contact_id' => $contact->getId(),
'contact_crm_id' => $crmId,
'opportunity_id' => $opportunity->getId(),
]);
return false;
}
throw $e;
}
}
private function logAddedContacts(Opportunity $opportunity, array $contactsAdded): void
{
if (! empty($contactsAdded)) {
$this->logger->info('[' . $this->getDisplayName() . '] Added contact associations', [
'opportunity_id' => $opportunity->getId(),
'contacts_to_add_count' => count($contactsAdded),
'added_contact_crm_ids' => $contactsAdded,
'added_contacts_count' => count($contactsAdded),
]);
}
}
}
Sync Changes
Hide This Notification
Code changed:
Hide
6
32
Previous Highlighted Error
Next Highlighted Error...
|
NULL
|
|
45182
|
NULL
|
0
|
2026-04-17T09:24:00.345279+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776417840345_m1.jpg...
|
NULL
|
NULL
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
FirefoxFileProfilesWindowEditViewHistoryBookmarks→ FirefoxFileProfilesWindowEditViewHistoryBookmarks→ToolsHelpmeet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)‹ >0 lhl¿ Support Daily • in 2h 37 m+NNYllian KyuchukovNikolay NikoloyVasil VasilevMihail Mihaylov"Lukas KovalikFo 17 kor 12.23SwSCloudWatchLop monooeen* Al Operations• GenAl Observability• Application Signals (APM)ktrascratare Monitoring* LogsLog ManaohLog Acalytios [Uve TalLogs inighes• Metrics• Netwock Monitoring(Option+s)©wocker-delayed/worker-delryed/BbMABM8ND40he968a52464e13e254Log eventYou can une the hiter bar beiow to search for and match terms, phrases, or walues inn your lon events. Leann more anulee deoewos desomMessage(2826-04-37 06:17:23) peodaction, INFO: (etersinecpenCX000181:20008800070018001000001-30086lemdoWrewit[c8xt-04-1700:17225) production.3M0: (ProceasAlAutonottorinelynis) Anolysis is to bo written in Cok(toeyч.0в3e1_1F (79449, "tange1d03eCt,type* (*opportumtty*, *remte.a0jeCt_peovtder.U°/^310297S8243*, *renote.field,grevtcer.l6*/@chargion__detatls*) (caereletion.16°1*340542) 6t)e-4301-|кахіести", tлеск,16:*2/30972e-0017-4a5/.bcdl-cofch(*nn,(8 12M24, "tenget, 16° (794)4), "terget, tyße" ( "oporteity", Чеsое,noryet,ho"1 вкотоодавв золнони, содескакуро сoрonnltу leycoonorgies seeoiotes emereororee aernortition deteils*:*Corgetition: X soGeee Tila(vidence(fevien af ell calls ond emitls)(2826-04-17 06:17:24) production. IN/0: OkeindexforoppdItykistener) Schedule reindexing job ['opportueity.i6° :734349) ("correlation,(6*: ^H49562%-4P%e -4381-«S74-осдостевстк", "вресе_16°1*2130972e-0еf7-405f-вc68-сbfceersbs")|(2826-04-17 06:17:25) production. IN/0: (DetermineUpdateOperationAction)wosrdos 18 Wrerentes Uoodtttwwwttwosktio.NotProcessiwtonsttoeenicnswisisto.bearittentmtem(Ttonget_dbject,1f":759434), "terpet_object,type*:*opportunity*."renote_object.provider,(4":"5802925424}*, "renote,field,provider_(d*: *Conpetition_detalla") ("correlatiso, 16°:"34954296-419e-43os-0G100% C8• Fri 17 Apr 12:23:596Daily - Processing16352| 4738|2026-03-17 09:21:10|2026-04-17 07:50:59|16378| 240|2026-04-16 12:42:37|2026-04-17 05:19:20|18281| 1911|2026-04-17 04:30:48|2026-04-17 07:50:59|20612| 2425|2026-04-17 04:31:13|2026-04-17 07:50:56|Mihail Mihaylov 11:44 AMMihail Mihaylov sent an imageSELECT os.stage_id,s.crm_provider_id, s.name,COUNT(*) as cntFROM opportunity_stages osJOIN stages s ON s.id =os.stage_idWHERE os.opportunity_id =7594349GROUP BY os.stage_id,s.crm_provider _id, s.nameORDER BY cnt DESC:Send a message© Cиен12:23 PM | Daily - Processing...
|
NULL
|
5534840259384766938
|
NULL
|
visual_change
|
ocr
|
NULL
|
FirefoxFileProfilesWindowEditViewHistoryBookmarks→ FirefoxFileProfilesWindowEditViewHistoryBookmarks→ToolsHelpmeet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)‹ >0 lhl¿ Support Daily • in 2h 37 m+NNYllian KyuchukovNikolay NikoloyVasil VasilevMihail Mihaylov"Lukas KovalikFo 17 kor 12.23SwSCloudWatchLop monooeen* Al Operations• GenAl Observability• Application Signals (APM)ktrascratare Monitoring* LogsLog ManaohLog Acalytios [Uve TalLogs inighes• Metrics• Netwock Monitoring(Option+s)©wocker-delayed/worker-delryed/BbMABM8ND40he968a52464e13e254Log eventYou can une the hiter bar beiow to search for and match terms, phrases, or walues inn your lon events. Leann more anulee deoewos desomMessage(2826-04-37 06:17:23) peodaction, INFO: (etersinecpenCX000181:20008800070018001000001-30086lemdoWrewit[c8xt-04-1700:17225) production.3M0: (ProceasAlAutonottorinelynis) Anolysis is to bo written in Cok(toeyч.0в3e1_1F (79449, "tange1d03eCt,type* (*opportumtty*, *remte.a0jeCt_peovtder.U°/^310297S8243*, *renote.field,grevtcer.l6*/@chargion__detatls*) (caereletion.16°1*340542) 6t)e-4301-|кахіести", tлеск,16:*2/30972e-0017-4a5/.bcdl-cofch(*nn,(8 12M24, "tenget, 16° (794)4), "terget, tyße" ( "oporteity", Чеsое,noryet,ho"1 вкотоодавв золнони, содескакуро сoрonnltу leycoonorgies seeoiotes emereororee aernortition deteils*:*Corgetition: X soGeee Tila(vidence(fevien af ell calls ond emitls)(2826-04-17 06:17:24) production. IN/0: OkeindexforoppdItykistener) Schedule reindexing job ['opportueity.i6° :734349) ("correlation,(6*: ^H49562%-4P%e -4381-«S74-осдостевстк", "вресе_16°1*2130972e-0еf7-405f-вc68-сbfceersbs")|(2826-04-17 06:17:25) production. IN/0: (DetermineUpdateOperationAction)wosrdos 18 Wrerentes Uoodtttwwwttwosktio.NotProcessiwtonsttoeenicnswisisto.bearittentmtem(Ttonget_dbject,1f":759434), "terpet_object,type*:*opportunity*."renote_object.provider,(4":"5802925424}*, "renote,field,provider_(d*: *Conpetition_detalla") ("correlatiso, 16°:"34954296-419e-43os-0G100% C8• Fri 17 Apr 12:23:596Daily - Processing16352| 4738|2026-03-17 09:21:10|2026-04-17 07:50:59|16378| 240|2026-04-16 12:42:37|2026-04-17 05:19:20|18281| 1911|2026-04-17 04:30:48|2026-04-17 07:50:59|20612| 2425|2026-04-17 04:31:13|2026-04-17 07:50:56|Mihail Mihaylov 11:44 AMMihail Mihaylov sent an imageSELECT os.stage_id,s.crm_provider_id, s.name,COUNT(*) as cntFROM opportunity_stages osJOIN stages s ON s.id =os.stage_idWHERE os.opportunity_id =7594349GROUP BY os.stage_id,s.crm_provider _id, s.nameORDER BY cnt DESC:Send a message© Cиен12:23 PM | Daily - Processing...
|
45180
|
|
45183
|
953
|
0
|
2026-04-17T09:24:03.471717+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776417843471_m1.jpg...
|
PhpStorm
|
faVsco.js – console [EU]
|
1
|
NULL
|
monitor_1
|
NULL
|
NULL
|
NULL
|
NULL
|
FirefoxFileEditViewHistoryBookmarksProfiles→ToolsW FirefoxFileEditViewHistoryBookmarksProfiles→ToolsWindowHelpmeet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)< >0 mhSupport Daily - in 2h 36 m+IVYllian KyuchukovNikolay NikolovVasil VasilevMihail MihaylovLukas KovalikHeatoryHeloFo 17 kor 12:24SwSQ SeerchLop woreooeen(Option+s)©wocker-delayed/worker-delryed/B0M1GBM874740teB68aS24e4e13e254CloudWatchLog eventOashboardsAlarms B+ 0» 01* Al Operations• GenAl Observability• Application Signals (APM)• Intrastructure Monitorin)* LogsLog ManaghLog Acalytios [. 4A3S /Romm/jialony/vendbe/lereve:/fronework/vec/Mlumtrete/Phgeltna/Pipel(ee.phe(1M): Itlamvnane/l@uewe/[EMAIL]/)(clesare)(Ob ject(HlhencneneiN/ventet(Cel/Queved (steer))B0 ThAG Nn TONX TO NKU NONG NYT HuANGO NHCTOnHTC Tố BNn Buểg hểN Tộ mừTHừn gg PhHnToHnVn pcC T Ciơvaсовзесьспи«‹7 Л∞æ/}ú∞g#›edœeЛвræveÎ/{соok/SÆCÎIĨo|лte/Qe/Cæ?!Qvve&#$e_(1?9):ЛÎ∞t»te\VgelVse:\P\дeÏ##thæ(@$e1(CLea»)>is Momn/Jirtney/vendoe /orevel/fcom19Phome/jwmtoy/vtodor/Loreve//romerork/src//1luninote/@ueve/Jobn/3o0.pfo(109:#1lumtnate/Nwtur/Wat/@wewedhondter-o08/1(0b./ct(fTTamnate/Qurwe/Jo0s/JaxJo0).Arroy128/home/jteiny/opp/Queve/orker/Borker.gPW72): IlainateliQuee/Uobr1Uck-yfireOObjACICTUM122. Aone/y1eUve TalLogs inighesrw/src/llluetnate/@eue/Necker.ghv(281): Dluatostel1Queve//Aorker-srwAJoeC0eyeCt(Tl1umneten/@veve/Uo0s115e0o%), *ses".123 /home/yurt.nny/vendoe/torevel/1rompork/src/Tltuminata/Queue/Comole/RorkConnond,php/341): 111untnete/Queur\Wiorkar-odoenon("tqs* "deloyed', Cbject(Tlturinote/Vueue)(BorkerOptions)1• Metrics• Netwock Monitoringk25 /home/jlrtrry/vendoe/Lerevel/franework/seC/1ilunineta/Conteiner/BounJiethed.ph/0):Tlluminate/l@wnwe/VCoensle/UMorkComond-shandieUetodeaiweoorle seewro427./home/jswcney/vendceNerevel/frogork/SPC/1Lluetsate/Cortatnee/Bounethod.pe(M)t Illuminete/\Coreetner/Wf(1/5wnarop1(Clobu+(00Jet(Clesv*))n28/home/J6eieny/vesdoe/loceveL/frunmosk/vec/11lur/nete/torteines/MouDethed.9M(35): 1IT1um/nete//Cortetsen./WBounalethodt11to1lBoun/Methoo/00ject/Cllarinete/eundetiom/6911/C&tLon), MCrmy.INJAREEEEETE SEAEETURОT О ЕЕ EDОЕНТЕ СЕЛЕТЕРА СОСТАСОООУИ ПЕСТОЗЕ СЕТЕНОРОЕ ЕЕТСТЕЕ ВИСОРЕСОТЕИЕ ПСОТОТОВУОТОЕДЕРВЕ ПЛТСUТО УEЛEТРLENEТS430/hoee/Jieimy/vendor/arevel/fraweock/veC/11 tuninate/Coesele/Comond.P9P(211): I1luminete/VContatner/Nontainer-ncell(Arrey)#13. home/jtrimny/vendor/tynfamy/contole/Comond/Comeond_ph9(M3): I11uminste/WCortole/VCcmmend-vewBC.teCDb/ject.(Jyefong/VCompenent/VConsete/lfreue/Mngvtrgut)Dejectcall100% C8• Fri 17 Apr 12:24:036Daily - ProcessingX16352| 4738|2026-03-17 09:21:10|2026-04-17 07:50:59|16378| 240|2026-04-16 12:42:37|2026-04-17 05:19:20|18281| 1911|2026-04-17 04:30:48|2026-04-17 07:50:59|20612| 2425|2026-04-17 04:31:13|2026-04-17 07:50:56|Mihail Mihaylov 11:44 AMMihail Mihaylov sent an imageSELECT os.stage_id,s.crm_provider_id, s.name,COUNT(*) as cntFROM opportunity_stages osJOIN stages s ON s.id =os.stage_idWHERE os.opportunity_id =7594349GROUP BY os.stage_id,s.crm_provider _id, s.nameORDER BY cnt DESC:Send a message© Cиен12:24 PM | Daily - Processing•.....
|
NULL
|
-8762058233111314127
|
NULL
|
click
|
ocr
|
NULL
|
FirefoxFileEditViewHistoryBookmarksProfiles→ToolsW FirefoxFileEditViewHistoryBookmarksProfiles→ToolsWindowHelpmeet.google.com/xpx-omah-rknllian Kyuchukov (Presenting, annotating)< >0 mhSupport Daily - in 2h 36 m+IVYllian KyuchukovNikolay NikolovVasil VasilevMihail MihaylovLukas KovalikHeatoryHeloFo 17 kor 12:24SwSQ SeerchLop woreooeen(Option+s)©wocker-delayed/worker-delryed/B0M1GBM874740teB68aS24e4e13e254CloudWatchLog eventOashboardsAlarms B+ 0» 01* Al Operations• GenAl Observability• Application Signals (APM)• Intrastructure Monitorin)* LogsLog ManaghLog Acalytios [. 4A3S /Romm/jialony/vendbe/lereve:/fronework/vec/Mlumtrete/Phgeltna/Pipel(ee.phe(1M): Itlamvnane/l@uewe/[EMAIL]/)(clesare)(Ob ject(HlhencneneiN/ventet(Cel/Queved (steer))B0 ThAG Nn TONX TO NKU NONG NYT HuANGO NHCTOnHTC Tố BNn Buểg hểN Tộ mừTHừn gg PhHnToHnVn pcC T Ciơvaсовзесьспи«‹7 Л∞æ/}ú∞g#›edœeЛвræveÎ/{соok/SÆCÎIĨo|лte/Qe/Cæ?!Qvve&#$e_(1?9):ЛÎ∞t»te\VgelVse:\P\дeÏ##thæ(@$e1(CLea»)>is Momn/Jirtney/vendoe /orevel/fcom19Phome/jwmtoy/vtodor/Loreve//romerork/src//1luninote/@ueve/Jobn/3o0.pfo(109:#1lumtnate/Nwtur/Wat/@wewedhondter-o08/1(0b./ct(fTTamnate/Qurwe/Jo0s/JaxJo0).Arroy128/home/jteiny/opp/Queve/orker/Borker.gPW72): IlainateliQuee/Uobr1Uck-yfireOObjACICTUM122. Aone/y1eUve TalLogs inighesrw/src/llluetnate/@eue/Necker.ghv(281): Dluatostel1Queve//Aorker-srwAJoeC0eyeCt(Tl1umneten/@veve/Uo0s115e0o%), *ses".123 /home/yurt.nny/vendoe/torevel/1rompork/src/Tltuminata/Queue/Comole/RorkConnond,php/341): 111untnete/Queur\Wiorkar-odoenon("tqs* "deloyed', Cbject(Tlturinote/Vueue)(BorkerOptions)1• Metrics• Netwock Monitoringk25 /home/jlrtrry/vendoe/Lerevel/franework/seC/1ilunineta/Conteiner/BounJiethed.ph/0):Tlluminate/l@wnwe/VCoensle/UMorkComond-shandieUetodeaiweoorle seewro427./home/jswcney/vendceNerevel/frogork/SPC/1Lluetsate/Cortatnee/Bounethod.pe(M)t Illuminete/\Coreetner/Wf(1/5wnarop1(Clobu+(00Jet(Clesv*))n28/home/J6eieny/vesdoe/loceveL/frunmosk/vec/11lur/nete/torteines/MouDethed.9M(35): 1IT1um/nete//Cortetsen./WBounalethodt11to1lBoun/Methoo/00ject/Cllarinete/eundetiom/6911/C&tLon), MCrmy.INJAREEEEETE SEAEETURОT О ЕЕ EDОЕНТЕ СЕЛЕТЕРА СОСТАСОООУИ ПЕСТОЗЕ СЕТЕНОРОЕ ЕЕТСТЕЕ ВИСОРЕСОТЕИЕ ПСОТОТОВУОТОЕДЕРВЕ ПЛТСUТО УEЛEТРLENEТS430/hoee/Jieimy/vendor/arevel/fraweock/veC/11 tuninate/Coesele/Comond.P9P(211): I1luminete/VContatner/Nontainer-ncell(Arrey)#13. home/jtrimny/vendor/tynfamy/contole/Comond/Comeond_ph9(M3): I11uminste/WCortole/VCcmmend-vewBC.teCDb/ject.(Jyefong/VCompenent/VConsete/lfreue/Mngvtrgut)Dejectcall100% C8• Fri 17 Apr 12:24:036Daily - ProcessingX16352| 4738|2026-03-17 09:21:10|2026-04-17 07:50:59|16378| 240|2026-04-16 12:42:37|2026-04-17 05:19:20|18281| 1911|2026-04-17 04:30:48|2026-04-17 07:50:59|20612| 2425|2026-04-17 04:31:13|2026-04-17 07:50:56|Mihail Mihaylov 11:44 AMMihail Mihaylov sent an imageSELECT os.stage_id,s.crm_provider_id, s.name,COUNT(*) as cntFROM opportunity_stages osJOIN stages s ON s.id =os.stage_idWHERE os.opportunity_id =7594349GROUP BY os.stage_id,s.crm_provider _id, s.nameORDER BY cnt DESC:Send a message© Cиен12:24 PM | Daily - Processing•.....
|
NULL
|
|
45184
|
NULL
|
0
|
2026-04-17T09:24:03.365169+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776417843365_m2.jpg...
|
PhpStorm
|
faVsco.js – console [EU]
|
1
|
NULL
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
PhpStormFV faVsco.js vProjectv= ids.txt=infection. PhpStormFV faVsco.js vProjectv= ids.txt=infection.son.distM+ INSTALL.mdM+ INTERNAL_WEBHOOK SETUPE jiminny_storageM+ licenses.mdM MakefileO package-lock.json= phpstan.neon.dist= phpstan-baseline.neor< phpunit.xmlTe raw_sql_query.sqlM+ KEADME.mO{o sonar-project.propertiesE test.py<> Untitled Diagram.xmlIs vetur.config.jsM+ WEBHOOK_FILTERING_IMPLE› ih External Librariesv E* Scratches and Consolesv D Database ConsolesvA-Uc consoe -u4 DEAL RISKS [EU]A DI [EU]A EU [EU]v A jiminny@localhostA console [jiminny@localtDI [jiminny@localhost]A HS_local [iminny@localA SF [jiminny@localhost]A zoho_dev ljiminny@loceV & PROD& consoe PRODIA console_1 [PROD]A DI [PROD]> LQAA QAI2 QAI PROD4 STAGINGA console [STAGING]L console_1 [STAGING]« uranus [STAGING]> D Extensionsv D Scratches= phostorm_shortcuts.txtE scratch.txtC° scratch_1.json(° scratch_2.jsonC* scratch_3.json= scratch_4.txtong scratch_5.phpphỹ scratch_6.php(° scratch_7.jsonC° stage2.jsonE° test<° test.htmlptS tmp.phpViewNavigatelaraveRefactor#1894 on.lY-18909-automated-renorts-ask-liminnv• AutomatedReportsService.php© SendReportJob.php© SendReportMailJob.php© ReportController.phpTokenBuilder.phpc leamsetuocontroller.onopnp apl.onoFilesystem.php• Team.php© TrackProviderInstalledEvent.php© RequestGenerateReportJob.php© OpportunitySyncTrait.phpc CrealenelaAcuiviyevent.onoOpportunity.php€ InteractsWithPivotTable.php© OpportunityStageUpdated.phpC OpportunityPendingAiAnalysisAfterStageChanged.phpC RunOpportunityAiAnalysis.phpProcessaiAulomalionAnalysiskesults.ono© ImportOpportunityBatch.phpImportBatchJobTrait.php© Service.php$stageCo W .*13/29PLT :trait OpportunitySyncTraitHSVEVIAVprivate function update0pportunity(string $crmId,array $properties,array $associations): Opportuni$data = $this->build0pportunityData($properties, $accountId, $businessProcess,E custom.logV connect.vue= laravel.logA SF [jiminny@localhost]C* scratch_1.jsonV Onboard.vueHs local liminnyalocalnostiL console [EU] X© CrmEntityRepository.phpfi crm_configurations [EU]A console [PROD]X:Auto vPlaygroundt.owner_id FROM social_accounts sa157115721573JOIN users u on u.id = sa.sociable_idJOIN teams t1.n<->1: on t.id = u.team_idWHERE u. team_id = 400 and sa.provider = 'hubspat';804806807808809810811812813814816817818819820838839840841842843845846847848849850851852853854855856857858859860861862$attributes = ['crm_configuration_id' $this->config->getId(),'crm_provider_id' => $crmId,E15791:-1583$values = array_merge(Sattributes, $data);$opportunity = $this->crmEntityRepository->upsert0pportunity($attributes, $values);=1584-1586фchis->importexcerna triecabatalepropercles, фopporcuntty-sgectaoe$this->update0pportunityAssociations(Sopportunity, $associations);158715881589return $opportunity;159015911592Lusages1593private function resolveAccountId(array $associations): Pintf...}=159415952 usages1596private function buildOpportunityData(array $properties,1597nint naccouncro1599?BusinessProcess SbusinessProcess.1600?Stage=1601): array {$ownerId = null;$profile = null;1603if (! empty($properties['hubspot_owner_id'])) {$ownerId = $properties['hubspot_owner_id'];-1606Sprofile = $this->cNmEnt¿tyReposіtory->fjndProf1LeByExternaLId(Sthis->config, (string) $owner* 26071608Sname = "Unknown"1610if (isset($propertiesl'dealname'])) {—1611$name = mb_strimwidth($properties['dealname'],start:0,width: 128);1613-1614$amount = $this->resolveAmount($properties);1615$currency = $properties[ 'deal_currency_code'] ?? null;E1616$closeDate = null;:1618if (! empty($propertiesl'elosedate'])) {_1619$closebate = cardon::parse(sproperclest closedateJ)->tormaut format: "Y-m-d))$remotelyCreatedAt = null;if (! empty(Sproperties['createdate']) && strtotime(Spropertiesl' createdate'])) €ttings. // Modify Shortcuts // Don't Show Again (a minute ago)A console [STAGING]S"jiminny026 49 A22 X3 X104 A Vselect x trol tearuresaselect * from team_features where feature_id = 40;select * from teams where id = 556; # owner: 18101, crm: 477select * from crm_configurations where id = 477;SELECT * FROM users WHERE id = 18101;SELECTICONCAT(u.id, LASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE "' END)u.email,sa.*,t.owner id FROM social accounts saJOIN users u on u.id = sa.sociable idJOIN teams t1..n<->1: on t.id = u.team idWHERE U. team_id = 556 and sa.provider = 'integration-app';select * from opportunities where id = 7594349;select * from opportunity_stages where opportunity_id = 7594349;select * from business_processes where id = 6024;select * frombusiness_process_stages where stage_id = 16352;select * from business_process_stages where business_process_id = 6024;select * from stages where team_id = 459;select * from teams where id = 459;SELECTCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' ELSE "' END)u.email,sa.*,t.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable_idJOIN teams t1..n<->1: on t.id = u.team_idWHERE U.team_id = 459 and sa.provider = 'hubspot':SELECT os.stage_id, s.crm_provider_id, s.name, COUNT(*) as cntFROM opportunity_stages osJOIN stages s1..n<->1: ON s.id = os.stage_idWHERE os.opportunity_id = 7594349GROUP BY os.stage_id, s.crm_provider_id, s.nameORDER BY cnt DESO;s. cri_provider_id, s.name, fs. team_id, s.crm_configuration_icFROM stages sJOIN business_process_stages bps1<->1..n: ON bps.stage_id = s.idWHERE bps.business_process_id = 6024AND s.crm_provider_id ='contractsent' :select * from stages where id IN (16352,20612,18281, 7344,16378, 16309, 50362> 0Support Daily - in 2 h 36 m100% C28 • Fri 17 Apr 12:24:02CascadeAutomated Report RetrDebugging Opportunit+D..Letme check exacuy now derripelinestacebyconaltions euerles.Exo orec Crmcnulvreotorv ono ano searcheo ce riellnestacebvconeltionsNow I have the complete picture.This Is Exactly The Cause Of The OscillationgetPipelineStageByConditions does ->where(['crm_provider_id' => 'contractsent', 'type' » 'opporLundly do-ILrsl.with 12 rows all having erm provider 1d = "contractsent", →tirsto returns a non-dererministieresult - whichever row MySQL decides to return first, which can vary between:different query executionsomerent index scansafter imoortstaoeso runs ano creates/vocates rows chanaino insertion order)So each call to resolveStage() for this deal can return a different one of those 12 stage IDs. Theoooonuniy's stare 1. cers Writen Witn Wnarever →tirst reuins — wnich is wnv vou see he 10. 4high-count stages (16352, 20612, 18281, 7344) that each have thousands of hits and the rarer ones onlynave l-<Why there are 12 stages with crm_provider_id = "contractsent"These come from 12 different business processes (different pipelines) across other CRM configurationsTnar were mooned over time, Wnen 1moortstadeso runs,coes updateorcreate kevec on omn provider_id scoped to $this->config - but the businessProcess->stages () relationship in getPipelineStageByConditions traverses the pivot table business_process_stages, and those 12 stages all belong to businessprocess 6024 va that pivotRun this to confirm:• sqlSELECT s.id, s.crm_provider_id, s.name, s.team_id, s.crm_configuration_idFROM stages sJOIN business_process_stages bps ON bps.stage_id = s.idWHERE bps.business_process_id = 6024AND s.crm provider id = 'contractsent':If all 12 have team_id = 459, then imoortStages( with businessProcess→>staqes()→>sync($stages) isattaching stages from other pipelines to business process 6024 each time it runs — because sync()replaces the entire pivot with whatever stage IDs were just upserted.Cascade & XIThe FixresolveStage() needs to scope the lookup to the specific business process only - which it already doesvia sousinessprocess->stades. but anporcsraces s corruotine tne oivor oy syncine all stages acrossall hinalinac inta te same ousiness orocess,Command 9el ata fix:• sạl- Check which of the 12 stages actually belongs to pipeline "default" (bp 6024)SELECT S.id, S.crm_provider_id, s.name, s.crm_contiguration_idFROM stages sJOIN business process stages bps ON bps.stage id = s.idWhckE bos.business process 1d = 6024OKDekbys.crn provlder 1o. S.lohThis will show you all stages attached to bp 6024 - and you'll almost certainly see stages from completelydifterent oioelines/CRM contias attached there because sunco In importstageso is re-writina the oivoton every run.Just one record ["id": 16352"crm_provider_id": "contractsent",: "Commercials","team_id": 459"crm_configuration_id": 367Shortcuts conflictsCone caler Aoove ane imo e snorcr contlctwith macOS shortcuts. Modify these shortcuts or..Modltv shortcutsDon't show Again<> CodeClaude Sonnet 4.6...
|
NULL
|
7727310981134914522
|
NULL
|
click
|
ocr
|
NULL
|
PhpStormFV faVsco.js vProjectv= ids.txt=infection. PhpStormFV faVsco.js vProjectv= ids.txt=infection.son.distM+ INSTALL.mdM+ INTERNAL_WEBHOOK SETUPE jiminny_storageM+ licenses.mdM MakefileO package-lock.json= phpstan.neon.dist= phpstan-baseline.neor< phpunit.xmlTe raw_sql_query.sqlM+ KEADME.mO{o sonar-project.propertiesE test.py<> Untitled Diagram.xmlIs vetur.config.jsM+ WEBHOOK_FILTERING_IMPLE› ih External Librariesv E* Scratches and Consolesv D Database ConsolesvA-Uc consoe -u4 DEAL RISKS [EU]A DI [EU]A EU [EU]v A jiminny@localhostA console [jiminny@localtDI [jiminny@localhost]A HS_local [iminny@localA SF [jiminny@localhost]A zoho_dev ljiminny@loceV & PROD& consoe PRODIA console_1 [PROD]A DI [PROD]> LQAA QAI2 QAI PROD4 STAGINGA console [STAGING]L console_1 [STAGING]« uranus [STAGING]> D Extensionsv D Scratches= phostorm_shortcuts.txtE scratch.txtC° scratch_1.json(° scratch_2.jsonC* scratch_3.json= scratch_4.txtong scratch_5.phpphỹ scratch_6.php(° scratch_7.jsonC° stage2.jsonE° test<° test.htmlptS tmp.phpViewNavigatelaraveRefactor#1894 on.lY-18909-automated-renorts-ask-liminnv• AutomatedReportsService.php© SendReportJob.php© SendReportMailJob.php© ReportController.phpTokenBuilder.phpc leamsetuocontroller.onopnp apl.onoFilesystem.php• Team.php© TrackProviderInstalledEvent.php© RequestGenerateReportJob.php© OpportunitySyncTrait.phpc CrealenelaAcuiviyevent.onoOpportunity.php€ InteractsWithPivotTable.php© OpportunityStageUpdated.phpC OpportunityPendingAiAnalysisAfterStageChanged.phpC RunOpportunityAiAnalysis.phpProcessaiAulomalionAnalysiskesults.ono© ImportOpportunityBatch.phpImportBatchJobTrait.php© Service.php$stageCo W .*13/29PLT :trait OpportunitySyncTraitHSVEVIAVprivate function update0pportunity(string $crmId,array $properties,array $associations): Opportuni$data = $this->build0pportunityData($properties, $accountId, $businessProcess,E custom.logV connect.vue= laravel.logA SF [jiminny@localhost]C* scratch_1.jsonV Onboard.vueHs local liminnyalocalnostiL console [EU] X© CrmEntityRepository.phpfi crm_configurations [EU]A console [PROD]X:Auto vPlaygroundt.owner_id FROM social_accounts sa157115721573JOIN users u on u.id = sa.sociable_idJOIN teams t1.n<->1: on t.id = u.team_idWHERE u. team_id = 400 and sa.provider = 'hubspat';804806807808809810811812813814816817818819820838839840841842843845846847848849850851852853854855856857858859860861862$attributes = ['crm_configuration_id' $this->config->getId(),'crm_provider_id' => $crmId,E15791:-1583$values = array_merge(Sattributes, $data);$opportunity = $this->crmEntityRepository->upsert0pportunity($attributes, $values);=1584-1586фchis->importexcerna triecabatalepropercles, фopporcuntty-sgectaoe$this->update0pportunityAssociations(Sopportunity, $associations);158715881589return $opportunity;159015911592Lusages1593private function resolveAccountId(array $associations): Pintf...}=159415952 usages1596private function buildOpportunityData(array $properties,1597nint naccouncro1599?BusinessProcess SbusinessProcess.1600?Stage=1601): array {$ownerId = null;$profile = null;1603if (! empty($properties['hubspot_owner_id'])) {$ownerId = $properties['hubspot_owner_id'];-1606Sprofile = $this->cNmEnt¿tyReposіtory->fjndProf1LeByExternaLId(Sthis->config, (string) $owner* 26071608Sname = "Unknown"1610if (isset($propertiesl'dealname'])) {—1611$name = mb_strimwidth($properties['dealname'],start:0,width: 128);1613-1614$amount = $this->resolveAmount($properties);1615$currency = $properties[ 'deal_currency_code'] ?? null;E1616$closeDate = null;:1618if (! empty($propertiesl'elosedate'])) {_1619$closebate = cardon::parse(sproperclest closedateJ)->tormaut format: "Y-m-d))$remotelyCreatedAt = null;if (! empty(Sproperties['createdate']) && strtotime(Spropertiesl' createdate'])) €ttings. // Modify Shortcuts // Don't Show Again (a minute ago)A console [STAGING]S"jiminny026 49 A22 X3 X104 A Vselect x trol tearuresaselect * from team_features where feature_id = 40;select * from teams where id = 556; # owner: 18101, crm: 477select * from crm_configurations where id = 477;SELECT * FROM users WHERE id = 18101;SELECTICONCAT(u.id, LASE WHEN u.id = t.owner_id THEN ' (owner)' ELSE "' END)u.email,sa.*,t.owner id FROM social accounts saJOIN users u on u.id = sa.sociable idJOIN teams t1..n<->1: on t.id = u.team idWHERE U. team_id = 556 and sa.provider = 'integration-app';select * from opportunities where id = 7594349;select * from opportunity_stages where opportunity_id = 7594349;select * from business_processes where id = 6024;select * frombusiness_process_stages where stage_id = 16352;select * from business_process_stages where business_process_id = 6024;select * from stages where team_id = 459;select * from teams where id = 459;SELECTCONCAT(u.id, CASE WHEN U.id = t.owner_id THEN ' (owner)' ELSE "' END)u.email,sa.*,t.owner_id FROM social_accounts saJOIN users u on u.id = sa.sociable_idJOIN teams t1..n<->1: on t.id = u.team_idWHERE U.team_id = 459 and sa.provider = 'hubspot':SELECT os.stage_id, s.crm_provider_id, s.name, COUNT(*) as cntFROM opportunity_stages osJOIN stages s1..n<->1: ON s.id = os.stage_idWHERE os.opportunity_id = 7594349GROUP BY os.stage_id, s.crm_provider_id, s.nameORDER BY cnt DESO;s. cri_provider_id, s.name, fs. team_id, s.crm_configuration_icFROM stages sJOIN business_process_stages bps1<->1..n: ON bps.stage_id = s.idWHERE bps.business_process_id = 6024AND s.crm_provider_id ='contractsent' :select * from stages where id IN (16352,20612,18281, 7344,16378, 16309, 50362> 0Support Daily - in 2 h 36 m100% C28 • Fri 17 Apr 12:24:02CascadeAutomated Report RetrDebugging Opportunit+D..Letme check exacuy now derripelinestacebyconaltions euerles.Exo orec Crmcnulvreotorv ono ano searcheo ce riellnestacebvconeltionsNow I have the complete picture.This Is Exactly The Cause Of The OscillationgetPipelineStageByConditions does ->where(['crm_provider_id' => 'contractsent', 'type' » 'opporLundly do-ILrsl.with 12 rows all having erm provider 1d = "contractsent", →tirsto returns a non-dererministieresult - whichever row MySQL decides to return first, which can vary between:different query executionsomerent index scansafter imoortstaoeso runs ano creates/vocates rows chanaino insertion order)So each call to resolveStage() for this deal can return a different one of those 12 stage IDs. Theoooonuniy's stare 1. cers Writen Witn Wnarever →tirst reuins — wnich is wnv vou see he 10. 4high-count stages (16352, 20612, 18281, 7344) that each have thousands of hits and the rarer ones onlynave l-<Why there are 12 stages with crm_provider_id = "contractsent"These come from 12 different business processes (different pipelines) across other CRM configurationsTnar were mooned over time, Wnen 1moortstadeso runs,coes updateorcreate kevec on omn provider_id scoped to $this->config - but the businessProcess->stages () relationship in getPipelineStageByConditions traverses the pivot table business_process_stages, and those 12 stages all belong to businessprocess 6024 va that pivotRun this to confirm:• sqlSELECT s.id, s.crm_provider_id, s.name, s.team_id, s.crm_configuration_idFROM stages sJOIN business_process_stages bps ON bps.stage_id = s.idWHERE bps.business_process_id = 6024AND s.crm provider id = 'contractsent':If all 12 have team_id = 459, then imoortStages( with businessProcess→>staqes()→>sync($stages) isattaching stages from other pipelines to business process 6024 each time it runs — because sync()replaces the entire pivot with whatever stage IDs were just upserted.Cascade & XIThe FixresolveStage() needs to scope the lookup to the specific business process only - which it already doesvia sousinessprocess->stades. but anporcsraces s corruotine tne oivor oy syncine all stages acrossall hinalinac inta te same ousiness orocess,Command 9el ata fix:• sạl- Check which of the 12 stages actually belongs to pipeline "default" (bp 6024)SELECT S.id, S.crm_provider_id, s.name, s.crm_contiguration_idFROM stages sJOIN business process stages bps ON bps.stage id = s.idWhckE bos.business process 1d = 6024OKDekbys.crn provlder 1o. S.lohThis will show you all stages attached to bp 6024 - and you'll almost certainly see stages from completelydifterent oioelines/CRM contias attached there because sunco In importstageso is re-writina the oivoton every run.Just one record ["id": 16352"crm_provider_id": "contractsent",: "Commercials","team_id": 459"crm_configuration_id": 367Shortcuts conflictsCone caler Aoove ane imo e snorcr contlctwith macOS shortcuts. Modify these shortcuts or..Modltv shortcutsDon't show Again<> CodeClaude Sonnet 4.6...
|
45181
|
|
45187
|
954
|
0
|
2026-04-17T09:24:08.582793+00:00
|
/Users/lukas/.screenpipe/data/data/2026-04-17/1776 /Users/lukas/.screenpipe/data/data/2026-04-17/1776417848582_m2.jpg...
|
Firefox
|
Meet - Daily - Processing — Work
|
1
|
meet.google.com/xpx-omah-rkn
|
monitor_2
|
NULL
|
NULL
|
NULL
|
NULL
|
Meet - Daily - Processing
Close tab
New Tab
Open G Meet - Daily - Processing
Close tab
New Tab
Open Google Gemini (⌃X)
Tabs from other devices
Open history (⇧⌘H)
Open bookmarks (⌘B)
Customize sidebar
Ilian Kyuchukov (Presenting, annotating)
Ilian Kyuchukov (Presenting, annotating)
People
6
Take notes with Gemini
Take notes with Gemini
Gemini
Gemini
Pop out this video More screens are more fun. Play this video while you do other things.
Pop out this video
More screens are more fun. Play this video while you do other things.
Zoom in
Open in new window
Enter Full Screen
Ilian Kyuchukov
Nikolay Nikolov
Vasil Vasilev
Mihail Mihaylov
Lukas Kovalik
Others might see more of your background. Click to view your full video.
Daily - Processing...
|
[{"role":"AXRadioButton","text [{"role":"AXRadioButton","text":"Meet - Daily - Processing","depth":4,"bounds":{"left":0.23320313,"top":1.0,"width":0.018945312,"height":-0.045138836},"help_text":"","role_description":"tab","subrole":"AXTabButton","is_enabled":true,"is_focused":false,"is_selected":true},{"role":"AXButton","text":"Close tab","depth":5,"bounds":{"left":0.23398438,"top":1.0,"width":0.005859375,"height":-0.045138836},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXButton","text":"New Tab","depth":4,"bounds":{"left":0.23652343,"top":1.0,"width":0.0125,"height":-0.07500005},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open Google Gemini (⌃X)","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Tabs from other devices","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open history (⇧⌘H)","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Open bookmarks (⌘B)","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXCheckBox","text":"Customize sidebar","depth":6,"help_text":"","role_description":"toggle button","subrole":"AXToggle","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXHeading","text":"Ilian Kyuchukov (Presenting, annotating)","depth":12,"bounds":{"left":0.27558595,"top":1.0,"width":0.1015625,"height":-0.063194394},"help_text":"","role_description":"heading","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Ilian Kyuchukov (Presenting, annotating)","depth":13,"bounds":{"left":0.27558595,"top":1.0,"width":0.1015625,"height":-0.06388891},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"People","depth":15,"bounds":{"left":0.7320312,"top":1.0,"width":0.023046875,"height":-0.05590272},"role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"6","depth":22,"bounds":{"left":0.7476562,"top":1.0,"width":0.002734375,"height":-0.063194394},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Take notes with Gemini","depth":14,"bounds":{"left":0.75820315,"top":1.0,"width":0.0140625,"height":-0.05590272},"role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false,"is_expanded":false},{"role":"AXStaticText","text":"Take notes with Gemini","depth":17,"bounds":{"left":0.7597656,"top":1.0,"width":0.051171876,"height":-0.063194394},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Gemini","depth":22,"bounds":{"left":0.7769531,"top":1.0,"width":0.015820313,"height":-0.063194394},"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Gemini","depth":21,"bounds":{"left":0.7757813,"top":1.0,"width":0.01328125,"height":-0.056597233},"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXButton","text":"Pop out this video More screens are more fun. Play this video while you do other things.","depth":15,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Pop out this video","depth":17,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"More screens are more fun. Play this video while you do other things.","depth":16,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Zoom in","depth":13,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXButton","text":"Open in new window","depth":13,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXButton","text":"Enter Full Screen","depth":13,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXStaticText","text":"Ilian Kyuchukov","depth":17,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Nikolay Nikolov","depth":17,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Vasil Vasilev","depth":17,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Mihail Mihaylov","depth":17,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXStaticText","text":"Lukas Kovalik","depth":17,"help_text":"","role_description":"text","subrole":"AXUnknown"},{"role":"AXButton","text":"Others might see more of your background. Click to view your full video.","depth":14,"help_text":"","role_description":"button","subrole":"AXUnknown","is_enabled":true,"is_focused":false,"is_selected":false},{"role":"AXHeading","text":"Daily - Processing","depth":13,"help_text":"","role_description":"heading","subrole":"AXUnknown"}]...
|
4708883039031699112
|
-6461762368714899696
|
click
|
accessibility
|
NULL
|
Meet - Daily - Processing
Close tab
New Tab
Open G Meet - Daily - Processing
Close tab
New Tab
Open Google Gemini (⌃X)
Tabs from other devices
Open history (⇧⌘H)
Open bookmarks (⌘B)
Customize sidebar
Ilian Kyuchukov (Presenting, annotating)
Ilian Kyuchukov (Presenting, annotating)
People
6
Take notes with Gemini
Take notes with Gemini
Gemini
Gemini
Pop out this video More screens are more fun. Play this video while you do other things.
Pop out this video
More screens are more fun. Play this video while you do other things.
Zoom in
Open in new window
Enter Full Screen
Ilian Kyuchukov
Nikolay Nikolov
Vasil Vasilev
Mihail Mihaylov
Lukas Kovalik
Others might see more of your background. Click to view your full video.
Daily - Processing...
|
NULL
|